【问题标题】:How to reuse @MockBean definitions in Spring?如何在 Spring 中重用 @MockBean 定义?
【发布时间】:2021-10-04 23:29:56
【问题描述】:

是否可以将@MockBean 定义外部化,并将它们与组合而不是继承结合起来?

因为我发现自己经常重复模拟定义,我宁愿能够加载/注入它们并在测试类之外定义它们。

例子:

@SpringBootTest
public class Service1Test {
    @MockBean
    private Service1 service1;
    
    @BeforeEach
    public void mock() {
        when(service1.call()).thenReturn(result1);
    }
}

@SpringBootTest
public class Service2Test {
    @MockBean
    private Service2 service2;
    
    @BeforeEach
    public void mock() {
        when(service2.call()).thenReturn(result2);
    }
}

@SpringBootTest
public class Service3Test {
    @MockBean
    private Service1 service1;
    
    @MockBean
    private Service2 service2;
    
    @BeforeEach
    public void mock() {
        when(service1.call()).thenReturn(result1);
        when(service2.call()).thenReturn(result2);
    }
}

我想以某种方式外部化模拟,所以我可以加载它们。 伪代码如下:

public class MockService1 {
    @MockBean
    private Service1 service1;
    
    @BeforeEach
    public void mock() {
        when(service1.call()).thenReturn(result1);
    }
}

@SpringBootTest
@Import({MockService1.class, MockService2.class})
public class Service3Test {

}

【问题讨论】:

标签: java spring spring-boot junit spring-boot-test


【解决方案1】:

是的,您可以通过使用外部配置类来实现。例如:

@TestConfiguration
public class TestConfig {

 @Bean
 @Primary
 public Foo foo() {
   return mock(Foo.class); //you can use Mockito or a different approach 
   here
 }

 @Bean
 @Primary
 public Bar bar() {
   return mock(Foo.class); 
 }
}

@Import(TestConfig.class)
public class MyTestClass {
 @Autowire 
 private Foo foo;
 @Autowire
 private Bar bar;  
}

【讨论】:

    猜你喜欢
    • 2021-07-07
    • 2019-10-10
    • 2019-08-10
    • 2019-05-01
    • 2017-05-11
    • 1970-01-01
    • 2021-07-28
    • 1970-01-01
    • 2019-02-24
    相关资源
    最近更新 更多