【问题标题】:Mocking a method with other methods用其他方法模拟一个方法
【发布时间】:2017-12-06 16:21:03
【问题描述】:

我有以下方法要测试:

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() - 返回一个String,在方法@​​987654326@内部调用,它属于一个接口类。

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

@After
public void teardown(){
    agent = null;
}

【问题讨论】:

  • 这里实例化的对象“代理”在哪里?
  • @Plog 它是在设置方法@Before 中实例化的,我编辑了问题给你看。

标签: java unit-testing mocking mockito


【解决方案1】:

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

由于在您的情况下 login() 是您想要模拟的唯一方法,而 Agent 类的其余功能保持不变,那么您应该对该对象进行间谍:

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

请注意,在对间谍进行 stub 时,您需要使用以下语法:

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

【讨论】:

  • 谢谢,我将 when() 语句安排到 doReturn 语句中,并且它起作用了。谢谢。
  • 哦,是的,我忘了提到这一点。我会把它添加到我的答案中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-18
  • 2017-08-29
相关资源
最近更新 更多