使用其他方法模拟方法



我有以下我要测试的方法:

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;
    }
}

我想模拟方法login(s, msgsys, time)。我这样做如下:

@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);
}

但是,遇到以下错误:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
Boolean cannot be returned by getLoginKey()
getLoginKey() should return String

请注意,方法getLoginKey()-返回字符串,在方法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;
}

如果要模拟一种代理的方法之一(在您的情况下为login()),那么您试图存根的代理需要是模拟或间谍。

因为在您的情况下登录()是您要使用代理类的其余功能完整嘲笑的唯一方法,因此您应该对此对象进行间谍:

@Before
public void setup(){
    MockitoAnnotations.initMocks(this);
    agent = Mockito.spy(new Agent("David", "1"));
    time = dateFormat.format(new Date());
}

请注意,当固执间谍时,您需要使用以下语法:

doReturn(true).when(agent).login(supervisor, msgsys, anyString());

最新更新