为什么模拟会抛出nullpointerexception?

时间:2018-12-28 17:17:10

标签: spring-data-jpa mockito

我想模拟实现JpaRepository的AddressRepo。 AddressRepo用作AddressMapper的构造函数。我正在尝试这样做:

public class AddressMapperTest2 {

    GenericMapper<Address, AddressDto> mapper;

    @MockBean
    private AddressRepo addressRepo;

    @Before
    public void setUp() {
        Optional<Address> tmpOptionalAddress = Optional.of(new Address("a", "1b", "c", "00-001"));
        when(addressRepo.findByCityAndStreetAndHouseNumberEtcAndPostalCode(anyString(), anyString(), anyString(), anyString())).thenReturn(tmpOptionalAddress);
        this.mapper = new AddressMapper(addressRepo);
    }

    @Test
    public void testDtoToNewSource() {
        // given
        AddressDto dto = new AddressDto();
        dto.setCity("a").setHouseNumberEtc("1b").setStreet("c").setPostalCode("00-001");

        // when
        Address addressFromDto = mapper.dtoToNewSource(dto);

        // then
        assertEquals("a", addressFromDto.city);
        assertEquals("1b", addressFromDto.houseNumberEtc);
        assertEquals("c", addressFromDto.street);
        assertEquals("00-001", addressFromDto.postalCode);
    }
}

java.lang.NullPointerException     在AddressMapperTest2.setUp(AddressMapperTest2.java:27)

1 个答案:

答案 0 :(得分:2)

MockBean不是Mockito注释。这是一个Spring注释,告诉Spring将模拟bean注入到使用Spring测试运行程序执行的Spring集成测试中。

您正在编写一个简单的单元测试,而不是由Spring运行程序运行的Spring集成测试。使用Mockito的@Mock注释(并阅读文档以了解使该注释生效所需的条件),或简单地使用Mockito API:

addressRepo = Mockito.mock(AddressRepo.class);