@Mockbean 不适用于多个 类 上未使用的 bean

@Mockbean doesn't work on a bean unsed on multiple classes

我的申请中有以下上下文。一个组件用于两个服务,这些服务用于第三个服务。我想测试这些服务之间的集成,所以我使用 @MockBean 来模拟组件的响应。在第一个服务上,模拟工作并且我得到了响应,但是在第二个服务上,我总是从组件中得到一个空值。

这是我的应用程序上下文。

public class Service1 {
  @Autowired
  private Component component;

  public Mono<String> getText() {
     return component.getText()
               .flatMap(string-> string.toUpperCase());
  }
}
public class Service2 {
  @Autowired
  private Component component;

  public Mono<String> getSubString() {
     // always got null from component here
     return component.getText()
                .flatMap(string-> string.substring(1,2));
  }
}
public class Service3 {
  @Autowired
  private Service1 service1;
  @Autowired
  private Service2 service2;
  @Autowired
  private Repository repository;

  public Mono<String> getData() {
      Mono<String> text1 = service1.getText();
      Mono<String> subString = service2.getSubString();
      return Mono.zip(text1, subString).flatMap( tuple -> {
          return tuple.getT1(), tuple.getT2();
      }).onSuccess(string-> repository.save(string));
  }
} 
@ActiveProfiles(profiles = "test")
@SpringBootTest(classes = {Application.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ApplicationTest {

  @MockBean
  Component component;
  @Autowired
  Service3 service3;
  @Autowired
  Repository repository;

  @Test
  public testService3() {
    given(component.getText()).willReturn("abc");
    
    service.getData().subscribe();

    assertNotNull(repository.findAll());   
  }
}

我尝试用这些方式模拟:

 given(component.getText()).willReturn("abc").willReturn("def");

 given(component.getText()).willReturn("abc","def");

如何使用相同的@MockBean 从 service1 和 service2 上的组件获取响应?

您应该模拟 Service1Service2,因为 Component 是它们的依赖项,而不是 Service3

像这样修复你的代码

    @MockBean
    Service1 service1;

    @MockBean
    Service2 service2;

    //...

    given(service1.getText()).willReturn("abc");
    given(service2.getSubString()).willReturn("def");