mockito:如何模拟webclient配置bean

mitkmikd  于 2021-07-24  发布在  Java
关注(0)|答案(0)|浏览(326)

我正在使用mockio、wiremock和webclient,我想测试我的服务层。我的目标是使用webclient的一个示例并对wiremock进行真正的请求。
因此,我必须使用标准配置,而不是生产模式下的oauth配置。
在服务类中,我对另一个api执行reuqets。所以被测试的类是用@service注解的。
以下是课程:

  1. @Service
  2. public class UserServiceImpl implements UserService{
  3. private final Logger log = Logger.getLogger(this.getClass().getName());
  4. private final WebClient webClient;
  5. private final ApplicationConstants applicationConstants;
  6. public UserServiceImpl (WebClient webClient, ApplicationConstants applicationConstants) {
  7. this.applicationConstants = applicationConstants;
  8. this.webClient = webClient;
  9. }
  10. @Override
  11. public User getUserById(@NotNull(message = "userId must not be null.") @NotBlank(message = "userId must not be blank.") String userId) {
  12. return webClient.get()...
  13. }

我在一个用@configuration注解的类中通过两个bean方法将我的webclient配置为使用oauth。

  1. @Configuration
  2. public class WebClientConfig {
  3. @Bean
  4. public WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) {
  5. ...
  6. }
  7. /*
  8. Manages the auth process and token refresh process
  9. */
  10. @Bean
  11. public OAuth2AuthorizedClientManager authorizedClientManager(
  12. ClientRegistrationRepository clientRegistrationRepository,
  13. OAuth2AuthorizedClientRepository authorizedClientRepository) {
  14. ...
  15. }
  16. }

因为我想使用不带oauth的webclient来调用wiremock,所以我想替换bean来返回一个简单的webclient.builder().build();
所以我做了:

  1. @ExtendWith({SpringExtension.class, WireMockExtension.class, MockitoExtension.class})
  2. public class TestClass {
  3. @Mock
  4. WebClientConfig webClientConfig;
  5. @MockBean
  6. WebClient webClient;
  7. @InjectMocks
  8. UserServiceImpl userService;

一般来说,根据我对mockito的理解,我会将我的被测类(userserviceinpl)与 @InjectMocks ,这样就使用了一个真实的示例并注入了依赖关系。因此,我必须为webclient提供一个mock。因为我不想模仿webclient,只想将其配置为不同的,所以我不必使用 @Mock . 相反,它应该是这样的 @MockBean 因为这个注解创建了一个bean并替换了上下文中现有的bean。所以我必须用@mock来模拟webclientconfig类,并定义如下内容

  1. when(webclientConfig).webclient(any(OAuth2AuthorizedClientManager.class)).thenReturn(Webclient.builder.build);

但这不起作用,因为我总是在调用中遇到nullpointer异常。所以基本问题是:
我对Mockito的理解正确吗?
如何管理webclient配置?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题