stakowerflol
stakowerflol

Reputation: 1079

Why mock throws nullpointerexception?

I want to mock AddressRepo which implements JpaRepository. The AddressRepo goes as constructor to AddressMapper. I am trying to do this like this:

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 at AddressMapperTest2.setUp(AddressMapperTest2.java:27)

Upvotes: 0

Views: 119

Answers (1)

JB Nizet
JB Nizet

Reputation: 691635

MockBean is not a Mockito annotation. It's a Spring annotation, telling Spring to inject a mock bean into your Spring integration test executed using the Spring test runner.

You're writing a simple unit test, not a Spring integration test run by the Spring runner. Use the @Mock annotation of Mockito (and read the documentation to understand what it takes to make that annotation functional), or simply use the Mockito API:

addressRepo = Mockito.mock(AddressRepo.class);

Upvotes: 2

Related Questions