【发布时间】:2019-01-10 22:54:17
【问题描述】:
我在我的测试类中为 WebClient.Builder 实例使用 @MockBean 注释,当我尝试设置 SSL 上下文时,它会导致 NullPointerException。
我不知道为什么当我没有尝试设置上下文并只是调用 build() api 时没有看到错误,如下所示:
服务类 v1:
@Service
public class ABCD {
private static final Logger logger = LoggerFactory.getLogger(ABCD.class);
private String apiUrl;
private final WebClient webClient;
private final XYZRepository repository;
public ABCD(WebClient.Builder webClientBuilder,
XYZRepository repository, @Value("${api-root-url}") String apiUrl) {
//------------------------
this.webClient = webClientBuilder.build();
//------------------------
this.repository = repository;
this.apiUrl = apiUrl;
}
}
服务类 v2:
@Service
public class ABCD {
private static final Logger logger = LoggerFactory.getLogger(ABCD.class);
private String apiUrl;
private final WebClient webClient;
private final XYZRepository repository;
public ABCD(WebClient.Builder webClientBuilder,
XYZRepository repository, @Value("${api-root-url}") String apiUrl) throws SSLException {
SslContext sslContext = SslContextBuilder
.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.build();
ClientHttpConnector httpConnector = new ReactorClientHttpConnector(options -> options.sslContext(sslContext));
//------------------------
this.webClient = webClientBuilder
.clientConnector(httpConnector)
.build();
//------------------------
this.repository = repository;
this.apiUrl = apiUrl;
}
}
测试类:
@RunWith(SpringRunner.class)
@WebFluxTest(ABCD.class)
public class ABCDTest {
@MockBean
XYZRepository repository;
@MockBean
WebClient.Builder webClientBuilder;
@SpyBean
ABCD ABCDService;
WebClient webClient;
@Value("${api-root-url}")
String apiRootUrl;
@Before
public void setup() {
this.objMapper = new ObjectMapper();
this.mockWebServer = new MockWebServer();
String baseUrl = this.mockWebServer.url("/").toString();
this.webClient = WebClient.create(baseUrl);
MockitoAnnotations.initMocks(this);
ReflectionTestUtils.setField(ABCDService,
"apiRootUrl", API_ROOT_URL);
ReflectionTestUtils.setField(ABCDService,
"webClient", this.webClient);
}
}
在 v2 中
this.webClient = webClientBuilder .clientConnector(httpConnector) .build();
在 build() 调用中导致 NPE。如何在不引起 NPE 的情况下模拟 webclient?
我试过了,在 setup() 方法中添加以下代码来模拟 clientConnector 方法的响应:
when(this.webClientBuilder.clientConnector(any()))
.thenReturn(this.webClientBuilder);
所以,我很好奇在哪里可以添加这段代码来使用上面的模拟。
【问题讨论】:
标签: java spring spring-boot mocking mockito