spring-boot:mockito忽略测试标准并返回通过的测试

时间:2016-09-13 07:54:55

标签: java unit-testing spring-boot mockito

我有下面提到的测试课使用Mockito。问题是它似乎忽略了我的setClientId参数。如果我把它设置为:

Bundle bundle = new Bundle();
        bundle.putParcelableArrayList("list",list);
        intent.putExtras(bundle);

测试仍然通过。他们不应该失败吗?或者我在Mockito中误解了什么?

测试类

when(mockTransactRepViewRepository.findByClientIdAndBatchDateBetween("SETRANDOMHERE", todayDateTime.toDate(), todayDateTime.plusDays(1).toDate()))
                    .thenReturn(Arrays.asList(transactRepViewModelTest, transactRepViewModelTest2));

以防万一,这是Repository类:

@RunWith(MockitoJUnitRunner.class)
@SpringApplicationConfiguration(classes = TransactRepViewRepository.class)
public class TransactRepViewRepositoryTest {

    @Rule
    public MockitoRule mockitoRule = MockitoJUnit.rule();

    @Mock
    private TransactRepViewRepository mockTransactRepViewRepository;

    @Test
    public void testFindByClientIdAndBatchDateBetween() {
        DateTime todayDateTime = new DateTime().withTimeAtStartOfDay();

        TransactRepViewModel transactRepViewModelTest = new TransactRepViewModel();
        transactRepViewModelTest.setClientId("123456");
        transactRepViewModelTest.setBatchDate(todayDateTime.toDate());
        mockTransactRepViewRepository.save(transactRepViewModelTest);

        TransactRepViewModel transactRepViewModelTest2 = new TransactRepViewModel();
        transactRepViewModelTest2.setClientId("123456");
        transactRepViewModelTest2.setBatchDate(todayDateTime.plusDays(1).toDate());
        mockTransactRepViewRepository.save(transactRepViewModelTest2);

        when(mockTransactRepViewRepository.findByClientIdAndBatchDateBetween("123465", todayDateTime.toDate(), todayDateTime.plusDays(1).toDate()))
                .thenReturn(Arrays.asList(transactRepViewModelTest, transactRepViewModelTest2));
        verify(mockTransactRepViewRepository, times(1)).save(transactRepViewModelTest);
        verify(mockTransactRepViewRepository, times(1)).save(transactRepViewModelTest2);
    }

1 个答案:

答案 0 :(得分:1)

实际上,你不是assert。在您的情况下,您仅verify 调用特定方法。这就是为什么你在这种情况下取​​得成功的原因。您必须添加assert,或者您可以更改verify

而不是:

verify(mockTransactRepViewRepository, times(1)).save(transactRepViewModelTest);

你可以这样做:

verify(mockTransactRepViewRepository, times(2)).save(transactRepViewModelTest);

此处您verify(此处出现错误)您的方法仅被调用一次,但不是两次

快速注释

我看到你正在编写Spring Boot个测试。请看一下如何正确编写测试。顺便说一句,还有很多额外的助手加入。你可以在Spring blog看一下它。