当前位置: 首页 > 知识库问答 >
问题:

MongoDB存储库的MockBean-只保存生成描述的结果,其他mock方法返回null

丁沛
2023-03-14

我正在测试一个具有MongoDB ReactiveMongoRepository回购依赖项的服务。我正在使用@mockbean来注入mock存储库。4个中只有1个定义when().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);
}
    @Override
public Mono<BlogpostDTO> getByID(String id) {
    return repo.findById(id).map(this::toDTO);
}

共有1个答案

东郭和光
2023-03-14

当定义从前面移动到测试方法时也是如此:

    @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();
}
 类似资料:
  • 主类: 我尝试的任何与存储库相关的方法都返回null。有人能帮我提个建议吗?

  • 这是我要测试的类 这是测试类 当我做这个测试的时候 我创建这些类时参考了其他已有的代码,来自不同的地方,并且没有真正理解如何进行注释(部分原因是时间不够),所以如果有人能告诉我,不仅是如何修复,而且还有为什么我错了,我会非常感激的! 编辑: 我做了@Nikolas Charalambidis建议的更改(谢谢!),所以我的类现在看起来与 通过稍加搜索,从这个SO答案中,我觉得我不应该@autowir

  • 我试图实现一个链表类在C和我有问题。我有添加新节点的=运算符。 链接列表类接口: 这里我有=重载实现: 此外,我还有“数组”访问重载方法: 一切正常-我检查了dibugger, 问题是-=不在“head”中保存新节点- 有人知道为什么新的分配没有链接到头- 谢谢!!

  • 我需要使用spring@Cacheable注释缓存对MongoDB的调用: 不幸的是,使用@Cacheable注释接口中的任何方法都会导致以下异常: 我正在寻找一种方法来缓存对DB的调用(这相当昂贵)。有什么想法吗?

  • 我刚开始使用Spring和JPA/Hibernate,我会拔下我的头发。 这是我的: 谢谢你的帮助。

  • 我已阅读此文档 所以我尝试了这个实验 它返回这个 我检查了我的值或@@DATEFIRST 它返回< code>7 那么,为什么我没有得到文件中描述的结果呢? 编辑 这是我在文档中看到的