[英]Mocking a method with other methods
I have the following method that I want to test: 我有以下要测试的方法:
public boolean sendMessage(Agent destinationAgent, String message, Supervisor s, MessagingSystem msgsys, String time) throws ParseException {
if(mailbox.getMessages().size() > 25){
return false;
}else{
if(login(s, msgsys, time)){
try {
sentMessage = msgsys.sendMessage(sessionkey, this, destinationAgent, message);
if(sentMessage.equals("OK")) {
return true;
}
return false;
} catch (ParseException e) {
e.printStackTrace();
return false;
}
}
return false;
}
}
I want to mock the method login(s, msgsys, time)
. 我想模拟
login(s, msgsys, time)
方法login(s, msgsys, time)
。 I am doing this as follows: 我这样做如下:
@Mock
private Supervisor supervisor;
@Mock
private MessagingSystem msgsys;
@Test
public void testSendMessageSuccess() throws ParseException {
String message = "Hey";
Agent destination = new Agent("Alex", "2");
agent.sessionkey = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
when(agent.login(supervisor, msgsys, anyString())).thenReturn(true);
when(msgsys.sendMessage(agent.sessionkey, destination, agent, message)).thenReturn("OK");
boolean result = agent.sendMessage(destination, message, supervisor, msgsys, time);
assertEquals(true, result);
}
However, the following error is encountered: 但是,遇到以下错误:
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
Boolean cannot be returned by getLoginKey()
getLoginKey() should return String
Please do note that the method getLoginKey()
- returns a String, is called inside the method login(s, msgsys, time)
, and it belongs to an interface class. 请注意方法
getLoginKey()
- 返回一个String,在方法login(s, msgsys, time)
调用,它属于一个接口类。
@Before
public void setup(){
MockitoAnnotations.initMocks(this);
agent = new Agent("David", "1");
time = dateFormat.format(new Date());
}
@After
public void teardown(){
agent = null;
}
If you want to mock one of the methods of Agent ( login()
in your case) then the Agent you are trying to stub needs to be a mock or a spy. 如果你想模拟Agent的一个方法
login()
在你的情况下是login()
)那么你试图存根的代理需要是模拟或间谍。
Since in your case login() is the only method you want to mock with the rest of the functionality of the Agent class intact then you should make a spy of this object: 因为在你的情况下,login()是你想要使用Agent类的其余功能进行模拟的唯一方法,那么你应该让这个对象成为间谍:
@Before
public void setup(){
MockitoAnnotations.initMocks(this);
agent = Mockito.spy(new Agent("David", "1"));
time = dateFormat.format(new Date());
}
Note that when stubbing spies to you need to use the following syntax: 请注意,当你将间谍绑定到你时需要使用以下语法:
doReturn(true).when(agent).login(supervisor, msgsys, anyString());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.