spring boot-无法模拟mongotemplate

wztqucjr  于 2021-07-23  发布在  Java
关注(0)|答案(1)|浏览(522)

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

  1. @Service
  2. public class MongoUpdateUtilityImpl implements MongoUpdateUtility {
  3. private final MongoTemplate mongoTemplate;
  4. @Autowired
  5. MongoUpdateUtilityImpl (final MongoTemplate mongoTemplate) {
  6. this.mongoTemplate = mongoTemplate;
  7. }
  8. @Override
  9. public Object update(final String id, final Map<String, Object> fields, final Class<?> classType) {
  10. ...
  11. this.mongoTemplate.updateFirst(query, update, classType);
  12. return this.mongoTemplate.findById(id, classType);
  13. }
  14. }

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

  1. @SpringBootTest
  2. @RunWith(SpringJUnit4ClassRunner.class)
  3. @ActiveProfiles("test")
  4. public class MongoUpdateUtilityTest {
  5. @MockBean
  6. private MongoTemplate mongoTemplate;
  7. @Autowired
  8. private MongoUpdateUtility mongoUpdateUtility;
  9. /**
  10. * Test en el que se realiza una actualización correctamente.
  11. */
  12. @Test
  13. public void updateOK1() {
  14. final Map<String, Object> map = new HashMap<>();
  15. map.put("test", null);
  16. map.put("test2", "value");
  17. when(mongoTemplate.updateFirst(Mockito.any(Query.class), Mockito.any(Update.class), Mockito.any(Class.class)))
  18. .thenReturn(null);
  19. when(mongoTemplate.findById(Mockito.anyString(), Mockito.any(Class.class))).thenReturn(null);
  20. assertNull(this.mongoUpdateUtility.update("2", map, Map.class));
  21. }
  22. }

我读过这个问题,但是当我尝试标记为solution的答案时,它说mongotemplate无法初始化。我更喜欢模拟这个,而不是使用和盗用数据库,因为我只能使用有限的库。
我的错误:

  1. 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
icnyk63a

icnyk63a1#

您正在使用@springboottest,它将显示整个应用程序上下文。这意味着应用程序中定义的每个bean都将被初始化。
对@service的测试来说,这是一个过度的杀伤力:
您的测试将需要更长的时间来执行
整个上下文必须正确
对于@服务的测试,我建议您采用更简单的方法,单独测试服务。
使用mockito扩展/运行程序(取决于junit版本)
摆脱@springboottest、@activeprofiles和springrunner
使用@mock而不是@mockbean
使用@injectmocks而不是@autowired

相关问题