Spring boot - 无法模拟 MongoTemplate

2024-02-11

我想测试服务中的一个方法并使用它Mongo模板如下:

@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);
    }       
}

然后我试图test此方法具有 mongo 模板的模拟方法:

@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 https://stackoverflow.com/questions/62383977/unable-to-mock-mongotemplate-executequery-using-mockito问题,但当我尝试标记为解决方案的答案时,它说 MongoTemplate 无法初始化。我更喜欢模拟它而不是使用和嵌入数据库,因为我可以使用的库有限。

我的错误:

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

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

对于 @Service 的测试来说,这是一种过度的杀伤力:

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

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

  • 使用 Mockito 扩展/运行器(取决于 junit 版本)
  • 摆脱@SpringBootTest、@ActiveProfiles和SpringRunner
  • 使用@Mock代替@MockBean
  • 使用@InjectMocks代替@Autowired
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring boot - 无法模拟 MongoTemplate 的相关文章

随机推荐