首页 > 解决方案 > 如果未调用实体类设置器,如何在 Mockito 中进行验证

问题描述

我有一门课,我想使用 mockito 对其进行单元测试:

public class ServiceImpl {

    @Autowired
    private TestDao testDao;

    @Transactional
    public void setData(Long id) {
        TestClass testClass = testDao.findOne(id);
        if (testClass != null) {
            testClass.setStatus(true);
        }
    }
}

我需要测试这个类。所以我创建了如下测试类:

@RunWith(MockitoJUnitRunner.class)
public class ServiceImplTest{
    @Mock
    private TestDao testDao;

    @InjectMocks
    private ServiceImpl service;

    @Test
    public void setData_success() {
        TestClass testClass = new TestClass();
        when(testDao.findOne(1L)).thenReturn(testClass);
        service.setData(1L);
        assertTrue(testClass.getStatus());
    }
}

上面的场景是 testClass 对象存在的时候。同样,我想测试 testClass 对象为空时的场景。就像是:

 @Test
 public void setData_testClass_null() {
    TestClass testClass = null;
    when(testDao.findOne(1L)).thenReturn(testClass);
    service.setData(1L);
    //how to I verify here that testClass.setStatus(true) is never called????
   //or should I just ignore the test case?
  }

标签: javaspringunit-testingjunitmockito

解决方案


推荐阅读