有没有办法把MockBean注入另一个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();
}
}

在这种情况下,不会在UserService中注入WalletService。正如我所看到的,原因是UserService是一个@MockBean。因此,我在测试中出现了NullPointerException。

然而,当我制作UserService@SpyBean时,WalletService被注入到UserService中。

有没有办法在UserService中注入WalletService,并将其作为@MockBean?

您需要在指定的调用方法之后使用返回值,当initiative被调用时,它会被Mockito拦截,返回到您指定的值,就像:

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

相关内容

  • 没有找到相关文章

最新更新