而不是这样:

@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = {Application.class}, webEnvironment =
SpringBootTest.WebEnvironment.DEFINED_PORT)
public abstract class AbstractIT {

   @MockBean
   private FooAdapter fooAdapter;

   @MockBean
   private BarAdapter barAdapter;

   public void mockFoo() {
      FooResponse dto = new FooResponse();
      when(fooAdapter.fooRequest()).thenReturn(dto);
   }


我想拥有:

@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = {Application.class}, webEnvironment =
SpringBootTest.WebEnvironment.DEFINED_PORT)
public abstract class AbstractIT {

   @MockBean/Autowired?
   MockProvider mockProvider;


class MockProvider {

   @MockBean
   private FooAdapter fooAdapter;

   @MockBean
   private BarAdapter barAdapter;

   public void mockFoo() {
      FooResponse dto = new FooResponse();
      when(fooAdapter.fooRequest()).thenReturn(dto);
   }


但是,我不知道将Mockito与SpringRunner一起使用是否可行。由于我们有很多适配器(例如10个),所以我不想过多地污染AbstractIT,因此,我想将这些依赖关系的初始化和具体模拟委托给另一个类来解决。

最佳答案

您必须在要用于以下用途的每个测试的@ContextConfiguration中指定该提供程序类:

@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = {Application.class}, webEnvironment = WebEnvironment.DEFINED_PORT)
@ContextConfiguration(classes = {MockProvider.class}  // <-- this
public abstract class AbstractIT {


您必须确保将提供程序配置为一个类:

@Configuration
public class MockProvider {


根据@MockBean文档:


  该批注可直接用于测试类,
  您的测试,或@Configuration类和字段。

关于java - 将模拟委托(delegate)给单独的类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57623963/

10-08 21:24