Mockito测试void方法

时间:2011-03-09 17:44:00

标签: java unit-testing mockito

我有以下要测试的代码:

public class MessageService {
    private MessageDAO dao;

    public void acceptFromOffice(Message message) {
        message.setStatus(0);
        dao.makePersistent(message);

        message.setStatus(1);
        dao.makePersistent(message);

    }
    public void setDao (MessageDAO mD) { this.dao = mD; }
}

public class Message {
    private int status;
    public int getStatus () { return status; }
    public void setStatus (int s) { this.status = s; }

    public boolean equals (Object o) { return status == ((Message) o).status; }

    public int hashCode () { return status; }
}

我需要验证,该方法acceptFromOffice确实将状态设置为0,而不是持久消息,然后将其状态变为1,然后再次保持状态。

对于Mockito,我试图做以下事情:

@Test
    public void testAcceptFromOffice () throws Exception {

        MessageDAO messageDAO = mock(MessageDAO.class);

        MessageService messageService = new MessageService();
        messageService.setDao(messageDAO);

        final Message message = spy(new Message());
        messageService.acceptFromOffice(message);

        verify(messageDAO).makePersistent(argThat(new BaseMatcher<Message>() {
            public boolean matches (Object item) {
                return ((Message) item).getStatus() == 0;
            }

            public void describeTo (Description description) { }
        }));

        verify(messageDAO).makePersistent(argThat(new BaseMatcher<Message>() {
            public boolean matches (Object item) {
                return ((Message) item).getStatus() == 1;
            }

            public void describeTo (Description description) { }
        }));

    }

我实际上期望验证将验证调用两次具有不同Message对象状态的makePersistent方法。但它没有说那个

  

论据不同!

任何线索?

2 个答案:

答案 0 :(得分:25)

测试代码并非易事,但并非不可能。我的第一个想法是使用ArgumentCaptor,与ArgumentMatcher相比,使用和理解起来要容易得多。不幸的是,测试仍然失败 - 原因肯定超出了这个答案的范围,但如果您感兴趣,我可以提供帮助。我仍然觉得这个测试用例足够有趣(不正确的解决方案):

@RunWith(MockitoJUnitRunner.class)
public class MessageServiceTest {

    @Mock
    private MessageDAO messageDAO = mock(MessageDAO.class);

    private MessageService messageService = new MessageService();

    @Before
    public void setup() {
        messageService.setDao(messageDAO);
    }

    @Test
    public void testAcceptFromOffice() throws Exception {
        //given
        final Message message = new Message();

        //when
        messageService.acceptFromOffice(message);

        //then
        ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);

        verify(messageDAO, times(2)).makePersistent(captor.capture());

        final List<Message> params = captor.getAllValues();
        assertThat(params).containsExactly(message, message);

        assertThat(params.get(0).getStatus()).isEqualTo(0);
        assertThat(params.get(1).getStatus()).isEqualTo(1);
    }

}

不幸的是,工作解决方案需要使用Answer。简而言之,您不是让Mockito记录并验证每次调用,而是提供一种回调方法,每次执行测试代码时都会执行mock。在这个回调方法(我们的示例中为MakePersistentCallback对象)中,您可以访问参数,并且可以更改返回值。这是一门重型大炮,你应该小心使用它:

    @Test
    public void testAcceptFromOffice2() throws Exception {
        //given
        final Message message = new Message();
        doAnswer(new MakePersistentCallback()).when(messageDAO).makePersistent(message);

        //when
        messageService.acceptFromOffice(message);

        //then
        verify(messageDAO, times(2)).makePersistent(message);
    }


    private static class MakePersistentCallback implements Answer {

        private int[] expectedStatuses = {0, 1};
        private int invocationNo;

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            final Message actual = (Message)invocation.getArguments()[0];
            assertThat(actual.getStatus()).isEqualTo(expectedStatuses[invocationNo++]);
            return null;
        }
    }

示例未完成,但现在测试成功,更重要的是,当您在CUT中更改几乎任何内容时失败。如您所见,每次调用模拟MakePersistentCallback.answer时都会调用messageService.acceptFromOffice(message)方法。在naswer内,您可以执行所需的所有验证。

注意:谨慎使用,至少可以说保持这样的测试很麻烦。

答案 1 :(得分:0)

您正在测试状态机。使用一些自定义实现测试MessageService非常容易。我认为TestMessage将是最有趣的课程。

为了允许DAO /消息记录持久化调用,我做了一个自定义实现。

这不是Mockito,但 很简单,应该可以胜任。

class TestMessageDAO implements MessageDAO {
  // I have no clue what the MessageDAO does except for makePersistent
  // which is the only relevant part here

  public void makePersistent(Message message) {
    if (message instanceof TestMessage) {
      TestMessage test = (TestMessage)message;
      test.persistCalled(); // will be recorded by TestMessage
    } else {
      throw RuntimeException("This test DAO does not support non-test messages");
    }
  }
}

// Message isn't final so...
class TestMessage extends Message {
  enum state {
    STARTED, STATUS0, PERSIST0, STATUS1, PERSIST1
  }

  public void persistCalled() { // For testing only
    switch (state) {
      case STATUS0:
        state = PERSIST0;
        break;
      case STATUS1:
        state = PERSIST1;
        break;
      default:
        throw new RuntimeException("Invalid transition");
    }
  }

  public void setStatus(int status) {
    switch(state) {
      case STARTED:
        if (status != 0) {
          throw new IllegalArgumentException("0 required");
        }
        state = STATUS0;
        break;
      case PERSIST0:
        if (status != 1) {
          throw new IllegalArgumentException("1 required");
        }

        state = STATUS1;
        break;
      default:
        throw new RuntimeException("Invalid transition");
    }
  }
}

public class TestMessageService {

  @Test
  public void testService() {
    MessageDAO dao = new TestMessageDAO();
    Message message = new TestMessage();
    MessageService service = new MessageService();
    service.setDao(dao);
    service.acceptFromOffice(message);
  }

}