1

给定一个进行一些组件测试的类。我想在测试中只模拟一次 fooService.send 并在 aService 和 bService 中使用它:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AComponentTestConfiguration.class)
public class AComponentTest {

    @Autowired
    private AService aService;

    @Autowired
    private BService bService;

    @Autowired
    private FooService fooService;

    // ... when(fooService.send(any())).thenReturn(response); 
}

和配置:

@Configuration
public class AComponentTestConfiguration {

    private CService cService = new CService(); // 1

    @Bean public FooService fooService() { return mock(FooService.class); } // 2
    @Bean public BarService barService() { return new BarService(); } // 3

    @Bean public AService aService() { return new AService(fooService(), barService(), cService); } // 4
    @Bean public BService bService() { return new AService(fooService(), barService(), cService); }
}

如何使用必须提供给多个 bean 的服务实例或模拟?

1:在 AService 和 BService 的实例中使用私有变量
2、3:使用函数 - 这将导致 FooService 和 BarService 的 2 个实例,对吗?
4:模拟和真实服务实例必须使用哪个选项?

4

0 回答 0