spring - 如何在没有继承的情况下在我的测试中共享 @MockBeans 和模拟方法?

标签 spring inheritance junit mocking integration-testing

我有一个将被其他集成测试使用的基本测试场景。此方案包括一些用于外部集成的模拟 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/

相关文章:

asp.net - 扩展 System.Web.HttpContext.User

java - 在 Mockito.when 中多次使用相同的 ArgumentMatchers

java - Maven Arquillian Junit 测试失败

java - 在不是参数的方法中模拟对象

node.js - org.springframework.web.multipart.MultipartException : Could not parse multipart servlet request. ..流意外结束

java - 终止 mvn spring-boot :run doesn't stop tomcat

json - Spring Web 应用程序,尝试将响应作为 json 抛出错误 500 错误发送

java - 使用应用程序上下文感知将数据从 servlet 传递到 spring

database - 继承变坏了吗?

Java 继承 - 可以简化将父类(super class)对象传递到子类的过程吗?