当我返回null时,assertEquals失败

时间:2015-07-07 12:46:44

标签: java junit mockito powermock

我试图实现Mockito来测试特定方法,但.thenReturn(null)似乎没有返回空值。

@RunWith(PowerMockRunner.class)
@PrepareForTest({ ValidationServiceImpl.class})
public class ValidationServiceTest {

    @Test
    public void testGetProdList() throws Exception{
        IValidationDao validationDao = Mockito.mock(ValidationDaoImpl.class);
        IValidationService validationService = Mockito.mock(ValidationServiceImpl.class);
        ReflectionTestUtils.setField(validationService, "validationDao", validationDao);
        List<ProductDetailsBean> prodGroups = new  ArrayList<ProductDetailsBean>();
        for (int i = 0; i < 145; i++) 
            prodGroups.add(new ProductDetailsBean());
        Mockito.when(validationDao.getProdList(12345)).thenReturn(prodGroups);
        assertNotEquals(null, validationService.getProdList(12345));
    }

    @Test
    public void testGetProdListwithNullTest() throws Exception{
        IValidationDao validationDao = Mockito.mock(ValidationDaoImpl.class);
        IValidationService validationService = Mockito.mock(ValidationServiceImpl.class);
        ReflectionTestUtils.setField(validationService, "validationDao", validationDao);
        Mockito.when(validationDao.getProdList(11111)).thenReturn(null);
        assertEquals(null, validationService.getProdList(11111));
    }   
}

我的第一个测试用例正常,第二个测试用例失败..

堆栈追踪:

java.lang.AssertionError: expected:<null> but was:<[]>
    at org.junit.Assert.fail(Assert.java:88)
    at org.junit.Assert.failNotEquals(Assert.java:743)
    at org.junit.Assert.assertEquals(Assert.java:118)
    at org.junit.Assert.assertEquals(Assert.java:144)
    at uk.co.argos.pst.test.sevices.ValidationServiceTest.testGetProdListwithNullTest(ValidationServiceTest.java:53)

请在我做错的地方帮助我。

1 个答案:

答案 0 :(得分:2)

您正在嘲笑ValidationServiceImpl,因此它会返回getProdList的默认模拟值,这是一个空列表。实际上从未调用过你的基础模拟IValidationDao

你可以嘲笑电话:

Mockito.when(validationService.getProdList(11111)).thenReturn(null);

但是你没有测试任何代码。

使用真实ValidationServiceImpl。而不是嘲笑:

IValidationService validationService = Mockito.mock(ValidationServiceImpl.class);
ReflectionTestUtils.setField(validationService, "validationDao", validationDao);

构建一个真实的实例:

IValidationService validationService = new ValidationServiceImpl();
validationService.setValidationDao(validationDao);