问题描述
我使用 Spring Boot 2.4.0 创建了一个项目。在这里,我使用 Google DialogFlow API 来编写聊天机器人。代码工作正常并返回所需的输出。但是在为代码编写测试用例时会出现问题。
作为 SessionClient,SessionName 都以某种方式具有静态功能,如下面的代码段所示。
DetectIntentResponse response;
SessionsSettings settings = config.getSessionsSettings();
try (SessionsClient sessionsClient = SessionsClient.create(settings)) {
requestMapper.setLANG_CODE(this.config.getLangCode());
SessionName session = SessionName.of(this.config.getProjectId(),UUID.randomUUID().toString());
final DetectIntentRequest intentRequest =
requestMapper.mapToRequest(request,session.toString());
response = sessionsClient.detectIntent(intentRequest);
sessionsClient.shutdown();
return responseMapper.mapResponse(response);
} catch (Exception e) {
log.error("Exception occurred :{}",e.getMessage());
throw e;
}
下面是我与 junit5 和 Mackito 3.4.0 一起使用的内联依赖
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>3.4.6</version>
<scope>test</scope>
</dependency>
下面是测试用例:
@Test
public void testDialogFlow(){
try(MockedStatic<SessionsClient> sessionsClientMockedStatic = Mockito.mockStatic(SessionsClient.class)){
Mockito.when(config.getSessionsSettings()).thenReturn(Mockito.mock(SessionsSettings.class));
Mockito.when(config.getProjectId()).thenReturn("projectId");
sessionsClientMockedStatic.when(() -> SessionsClient.create(any(SessionsSettings.class)))
.thenReturn(sessionClientMock);
MockedStatic<SessionName> sessionNameMockedStatic = Mockito.mockStatic(SessionName.class);
sessionNameMockedStatic.when(() -> SessionName.of(anyString(),anyString())).thenReturn(sessionNameMock);
final MyResponse response = facade.getIntentResponse(spy(MyRequest.class));
Assertions.assertNotNull(response);
}
}
我在运行测试用例时遇到以下错误:
"java.lang.NullPointerException: Cannot invoke "com.google.cloud.dialogflow.v2.SessionName.toString()" because "session" is null"
这不仅是空引用,sessionClient 也是空的。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)