【问题标题】:Mockito: How to mock WebClient configuring BeansMockito:如何模拟 WebClient 配置 Bean
【发布时间】:2021-01-28 12:30:40
【问题描述】:

我正在使用 Mockio、Wiremock 和 WebClient,我想测试我的服务层。 我的目标是使用 webclient 的实例并对wiremock 发出真正的请求。

因此,我必须使用标准配置,而不是生产模式下的 oauth 配置。

在服务类中,我对另一个 api 执行 reuqets。所以被测试的类是用@Service注解的。

这是课程:

@Service
public class UserServiceImpl implements UserService{

    private final Logger log = Logger.getLogger(this.getClass().getName());
    private final WebClient webClient;
    private final ApplicationConstants applicationConstants;

    public UserServiceImpl (WebClient webClient, ApplicationConstants applicationConstants) {
        this.applicationConstants = applicationConstants;
        this.webClient = webClient;
    }

    @Override
    public User getUserById(@NotNull(message = "userId must not be null.") @NotBlank(message = "userId must not be blank.") String userId) {
        return  webClient.get()...
}

我将我的 WebClient 配置为通过使用 @Configuration 注释的类中的两个 Bean 方法来使用 Oauth。

@Configuration
public class WebClientConfig {

    @Bean
    public WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) {
       ...
    }

    /*
    Manages the auth process and token refresh process
     */
    @Bean
    public OAuth2AuthorizedClientManager authorizedClientManager(
            ClientRegistrationRepository clientRegistrationRepository,
            OAuth2AuthorizedClientRepository authorizedClientRepository) {

        ...
    }
}

因为我想用不带oauth的webClient来调用wiremock,所以我想替换Beans返回一个简单的Webclient.builder().build();

所以我做到了:

@ExtendWith({SpringExtension.class, WireMockExtension.class, MockitoExtension.class})
public class TestClass {

    @Mock
    WebClientConfig webClientConfig;

    @MockBean
    WebClient webClient;

    @InjectMocks 
    UserServiceImpl userService;

一般来说,据我了解 Mockito,我会将我的测试类 (userServiceImpl) 与 @InjectMocks 一起使用,因此使用真实实例并注入依赖项。因此,我必须为 Webclient 提供一个 Mock。由于我不想模拟 webclient 并且只想配置它不同,我不必使用@Mock。相反,它应该是 @MockBean 之类的东西,因为此注释创建一个 bean 并替换上下文中现有的。所以我必须用@Mock 模拟 Webclientconfig 类并定义类似的东西

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

但这不起作用,因为我总是在调用时遇到空指针异常。 所以基本问题是:

  1. 我对 Mockito 的理解对吗?
  2. 如何管理 Webclient 配置?

【问题讨论】:

  • 您找到解决方案了吗?我面临同样的事情。
  • 是的。而不是 userServiceImpl 我自动装配了 UserService 接口。然后注入模拟。我还为我通过活动配置文件选择的 web 客户端使用了一个单独的测试 Bean
  • 我正在尝试你上面提到的但继续得到“servletRequest不能为空”
  • 您能分享一下您是如何创建特定于配置文件的测试 bean 的吗?

标签: spring testing mockito webclient


【解决方案1】:

看起来像是在应用程序的其余部分启动之前配置 MockBeans 的情况,这里回答: Configure @MockBean component before application start

在撰写本文时,上述答案提到使用 @Primary@MockBean(answer = Answers.CALLS_REAL_METHODS) 作为解决方法。

【讨论】:

    猜你喜欢
    • 2021-09-02
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 2019-02-26
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多