Я тестирую службу с зависимостью репозитория MongoDB ReactiveMongoRepository. Я использую @MockBean для внедрения фиктивного репозитория. Только 1 из 4 определен при работе (). ThenReturn (), остальные выдают null при запуске модульного теста. Вот код:
@Autowired
private BlogpostServicePersist testee;
@MockBean
private BlogpostRepository repo;
private Class<BlogpostMongoDoc> entityClass = BlogpostMongoDoc.class;
private String testId1 = "save 01 ID";
private BlogpostMongoDoc postMongoDOc = (BlogpostMongoDoc) initialize(
BlogpostMongoDoc.newInstance(testId1, "save 01 title", "save 01 text", "save 01 author"));;
private BlogpostDTO postDTO = (BlogpostDTO) initialize(
BlogpostDTO.newInstance(testId1, "save 01 title", "save 01 text", "save 01 author"));
@BeforeAll
void setup() {
when(repo.save(any(entityClass))).thenReturn(just(postMongoDOc));
when(repo.deleteById(anyString())).thenReturn(Mono.empty().then());
when(repo.findById(eq(testId1))).thenReturn(just(postMongoDOc));
when(repo.findAll()).thenReturn(Flux.just(postMongoDOc, postMongoDOc));
}
@Test
void testSave() {
create(testee.save(postDTO)).expectNextMatches(this::matchPost).expectComplete().verify();
}
@Test
void testGetStream() {
create(testee.getAll()).expectNextMatches(this::matchPost).expectNextMatches(this::matchPost).expectComplete()
.verify();
}
@Test
void testDelete() {
create(testee.delete(testId1)).expectComplete().verify();
}
@Test
void testGetByID() {
create(testee.getByID(testId1)).expectNextMatches(this::matchPost).expectComplete().verify();
}
testSave работает нормально. Вот код службы:
@Override
public Mono<BlogpostDTO> save(BlogpostDTO newPost) {
return repo.save(toEntity(newPost)).map(this::toDTO);
}
В остальном существует исключение NullPointer в службе, когда репо возвращает значение, например:
@Override
public Mono<BlogpostDTO> getByID(String id) {
return repo.findById(id).map(this::toDTO);
}
return repo.findById (id ) возвращает null.
У меня есть equals, определенные в классе сущности BlogpostMongoDo c, который я использую, и он основан на поле String ID.
В чем разница между when (save) определение и остальное?
Спасибо.