首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring引导-不能模仿MongoTemplate

Spring引导-不能模仿MongoTemplate
EN

Stack Overflow用户
提问于 2021-03-12 10:03:35
回答 1查看 3.9K关注 0票数 1

我在一个要测试的服务中有一个方法,它使用MongoTemplate,如下所示:

代码语言:javascript
复制
@Service
public class MongoUpdateUtilityImpl implements MongoUpdateUtility {
    private final MongoTemplate mongoTemplate;
    
    @Autowired
    MongoUpdateUtilityImpl (final MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    @Override
    public Object update(final String id, final Map<String, Object> fields, final Class<?> classType) {
        ...
        this.mongoTemplate.updateFirst(query, update, classType);
        return this.mongoTemplate.findById(id, classType);
    }       
}

然后,我尝试用模拟的mongo模板方法来测试这个方法:

代码语言:javascript
复制
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("test")
public class MongoUpdateUtilityTest {
    @MockBean
    private MongoTemplate mongoTemplate;

    @Autowired
    private MongoUpdateUtility mongoUpdateUtility;

    /**
     * Test en el que se realiza una actualización correctamente.
     */
    @Test
    public void updateOK1() {
        final Map<String, Object> map = new HashMap<>();

        map.put("test", null);
        map.put("test2", "value");

        when(mongoTemplate.updateFirst(Mockito.any(Query.class), Mockito.any(Update.class), Mockito.any(Class.class)))
                .thenReturn(null);
        when(mongoTemplate.findById(Mockito.anyString(), Mockito.any(Class.class))).thenReturn(null);

        assertNull(this.mongoUpdateUtility.update("2", map, Map.class));
    }
}

我读过this问题,但是当我尝试标记为解决方案的答案时,它说MongoTemplate不能被初始化。比起使用和嵌入式数据库,我更喜欢嘲弄这一点,因为我只能使用我可以使用的库。

我的错误:

代码语言:javascript
复制
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'operacionesPendientesRepository' defined in es.santander.gdopen.operpdtes.repository.OperacionesPendientesRepository defined in @EnableMongoRepositories declared on MongoRepositoriesRegistrar.EnableMongoRepositoriesConfiguration: Invocation of init method failed; nested exception is java.lang.NullPointerException
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-12 12:15:47

您正在使用@SpringBootTest,它将显示整个应用程序上下文。这意味着应用程序中定义的每个bean都将被初始化。

对于@Service的测试来说,这是过分的做法:

  • 您的测试需要更长的时间来执行
  • 整个上下文必须是正确的

对于@Service的测试,我建议您采用更简单的方法,并隔离地测试服务。

SpringRunner

  • use

  • 使用Mockito扩展/运行程序(取决于junit版本)

  • 不再使用@SpringBootTest、@ActiveProfiles和 @Mock,而不是使用@MockBean
  • use @InjectMocks而不是@Autowired
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66597809

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档