【问题标题】:Spring boot test minimal test slice or manual configurationSpring Boot 测试最小测试片或手动配置
【发布时间】:2019-06-17 07:40:30
【问题描述】:

我有许多不同的 SpringBoot 测试正在运行。到目前为止,auto configuration slices 确实很有帮助,尤其是与@MockBean 结合使用。

但在我当前的测试中,没有这样的切片适合并且使用 @SpringBootTest 启动完整的上下文太慢了。

有没有办法手动设置要启动的对象树的顶端,并从那里弹簧自动装配所有需要的 bean?或者有没有办法手动设置所有需要的bean?

在我的具体情况下,我想测试一个 MapStruct 生成的映射器(使用componentModel = "spring"),这个映射器使用另外两个映射器,每个映射器都注入一个服务来完成他们的工作。

服务通过@MockBean提供:

@RunWith(SpringRunner.class)
@SpringBootTest
public class ProductResponsibleUnitMapperTest {

    @Autowired
    private PRUMapper mapper;

    @MockBean
    private TradingPartnerService tradingPartnerService;

    @MockBean
    private ProductHierarchyService productHierarchyService;

    @Test
    public void mapForthAndBack(){
      //works but takes ages to boot
    }

}

我无法在映射器(用于服务)上使用构造函数注入,因为 MapStruct 不会生成正确的实现。

如何获取只包含所需 bean 的 Spring-Context?

【问题讨论】:

  • 写给构造函数注入:你试过了吗:InjectionStrategy.CONSTRUCTOR (MapStruct 1.3Beta2)?
  • 很高兴知道这会来

标签: spring spring-boot mockito spring-boot-test mapstruct


【解决方案1】:

我通过明确声明使用的所有实现找到了一种方法:

@SpringBootTest(classes = {ProductResponsibleUnitMapperImpl.class, LegalEntityMapperImpl.class, ProductHierarchyMapperImpl.class}) 

对于更复杂的设置,声明生成的类既麻烦又危险。

我仍在寻找一种更简洁的方法来让 Spring 决定需要哪些类。应该可以将类设置在手,让 Spring 决定需要哪些类并实例化。

【讨论】:

  • 如果你不测试实际的 MapperImpl,那么仅仅模拟它怎么样:使用@SpringBean ProductResponsibleUnitMapper hedgingProfileMapper = Mock()
  • 我需要这些映射器,他们在做什么。关键是我可以用这个剪掉一个特定的测试框架。
  • 我明白了。我在@DataMongoTest 上遇到了同样的问题,但幸运的是我没有测试受 MapperImpl 影响的代码。
猜你喜欢
  • 1970-01-01
  • 2021-02-16
  • 1970-01-01
  • 2017-01-25
  • 2015-03-21
  • 2015-06-14
  • 2021-12-23
  • 2018-11-02
  • 2019-01-20
相关资源
最近更新 更多