繁体   English   中英

有没有办法将 MockBean 注入另一个 MockBean 中

[英]Is there any way to inject MockBean inside another MockBean

我有课

@Service
@RequiredArgsConstructor
public class UserService {
    private final WalletService walletService;

    public void increaseBalance() {
      walletService.increaseBalance();
    }
}

@Service
@RequiredArgsConstructor
public class WalletService {
    public void increaseBalance() {}
}

和测试班

@RunWith(SpringRunner.class)
@SpringBootTest()
public class UserServiceTest {
  @MockBean
  private UserService userService;

  @Test
  public void testIncreaseBalance_realMethod() {
    //here I want to call real UserService method
    doCallRealMethod().when(userService).increaseBalance();

    userService.increseBalance();
  }

  @Test
  public void testIncreaseBalance_mockedMethod() {
    //here I don't want to call real UserService method

    userService.increseBalance();
  }

}

在这种情况下WalletService 没有注入 UserService 正如我所见,原因是 UserService 是一个@MockBean。 因此,我在测试中有 NullPointerException。

但是,当我创建 UserService @SpyBean 时,WalletService 被注入到 UserService 中。

有什么方法可以在 UserService 中注入 WalletService 并且仍然将其作为@MockBean?

你需要使用指定调用方法后的返回值,主动调用时,会被Mockito拦截,返回你指定的值,就像:

Mockito.when(userService.increaseBalance()).thenReturn(1);
userService.increaseBalance() // print :1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM