【问题标题】:MockBean of MongoDB repository - only save produces described result, other mock methods return nullMongoDB 存储库的 MockBean - 仅保存产生描述的结果,其他模拟方法返回 null
【发布时间】:2020-08-04 10:36:53
【问题描述】:

我正在测试一个具有 MongoDB ReactiveMongoRepository 存储库依赖项的服务。 我正在使用@MockBean 注入模拟存储库。 4 个中只有 1 个定义 when().thenReturn() work ,其余的在运行单元测试时产生 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);
}

当repo返回值时,服务中会出现NullPointer异常, 例如:

    @Override
public Mono<BlogpostDTO> getByID(String id) {
    return repo.findById(id).map(this::toDTO);
}

return repo.findById(id) 返回 null。

我在我正在使用的实体类 BlogpostMongoDoc 上定义了 equals,它基于 String ID 字段。

when(save) 定义与其余定义有什么区别?

谢谢。

【问题讨论】:

    标签: spring mongodb unit-testing mockito


    【解决方案1】:

    当从 beforeAll 移动到测试方法时,相同的 when 定义起作用:

        @Test
    void testGetStream() {
        when(repo.findAll()).thenReturn(Flux.just(postMongoDOc, postMongoDOc));
        create(testee.getAll()).expectNextMatches(this::matchPost).expectNextMatches(this::matchPost).expectComplete()
                .verify();
        verify(repo).findAll();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      • 1970-01-01
      • 2021-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多