我有一个将被其他集成测试使用的基本测试场景。此方案包括一些用于外部集成的模拟 bean ( @MockBean
)。
今天,我在集成测试类中有这样的东西:
@SpringBootTest
@WebAppConfiguration
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
@RunWith(SpringRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class OrderIT {
以及准备集成测试的字段和注释:
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@Autowired
private ObjectMapper mapper;
@MockBean
private SomeGateway someGateway;
@MockBean
private SomeRabbitMqService someRabbitMqService ;
@MockBean
private AnotherRabbitMqService anotherRabbitMqService;
@MockBean
private SomeIntegrationService someIntegrationService ;
@MockBean
private Clock clock;
@Before
public void setup() {
//some methods mocking each service above, preparing mockMvc, etc
}
这个场景是使用
MockMvc
所必需的。并在系统中创建主要功能,我的 Order
.此 Order
通过在 Rest API 中调用 POST 方法创建,保存 order
在内存数据库中。即使这样运作良好,我也需要 重复 此代码块包含这些
@MockBean
和一些 @Autowired
在另一个测试中,因为 Order
是 基本场景将产品添加到订单中,设置要交付的地址等。每个场景都有不同的集成测试,但所有这些都需要一个 Order
.那么,如何在我的集成测试中共享“MockBeans”和模拟它们的方法?我真的有使用继承的糟糕体验 在测试中,我真的很想尝试不同的方法。
最佳答案
我最终使用了 Spring profiles .
我创建了一个用 @Profile("test")
注释的配置类并在那里创建了模拟 bean 。喜欢:
@Profile("test")
@Configuration
public class MyMockConfiguration {
@Bean
public SomeService someService() {
SomeService someService = mock(SomeService .class);
// mocked methods and results
return someService ;
}
在 Test 类中:@ActiveProfiles("test")
@SpringBootTest
@WebAppConfiguration
@RunWith(SpringRunner.class)
public class MyControllerIT {
如果某些集成测试需要覆盖配置文件上的当前模拟实现,则测试只需要声明 @MockBean
在类里面,像往常一样继续模拟。我还没有决定是否
test
是个好名字,因为对我来说,通过“上下文”来模拟配置更有意义。因此,不要使用通用名称 test
在个人资料名称上,我可以使用 createOrder
并且有不同的配置文件,每个文件都有不同的名称和不同的模拟:createOrder
, createOrderWithoutProducts
.
关于spring - 如何在没有继承的情况下在我的测试中共享 @MockBeans 和模拟方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49139591/