我想模拟实现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 at AddressMapperTest2.setUp(AddressMapperTest2.java:27)
MockBean
不是Mockito注释。这是一个 Spring 注释,告诉 Spring 将模拟 bean 注入到 Spring 测试运行器执行的 Spring 集成测试中。
您正在编写一个简单的单元测试,而不是由 Spring 运行器运行的 Spring 集成测试。使用 Mockito 的@Mock
注释(并阅读文档以了解使该注释起作用所需的条件),或者简单地使用 Mockito API:
addressRepo = Mockito.mock(AddressRepo.class);