java - Spock 测试用例在涉及异步客户端调用的多个测试时失败,但在单独运行时成功运行
问题描述
测试场景是从一个异步调用的模拟客户端服务中获取结果。在这里,如果我尝试单独运行上述测试,它们会成功执行。但是当尝试通过 构建项目时mvn clean install
,成功的测试用例给出了错误。
如何处理异常情况,使其不影响预期的方法行为测试用例?或者可能是什么导致了多个异步调用的问题?如何处理/关闭生成的线程,或在开始下一个客户端调用之前等待其完成?
// SERVICE CLASS
public String serviceMethod(String arg1, String arg2) {
return mockedclient.fetchDetails(arg1, arg2)
.toCompletableFuture()
.thenapplyasync(HashSet::new) // assuming the received response is a list
.get(3,TimeUnit.SECONDS);
}
//TEST CLASS
def " should return result retrieved from the client" () {
given:
def arg1 = "value1"
def arg2 = "value2"
def futureList = CompletableFuture.completedFuture(Collections.toList("RESULT"))
def futureSet = new BlockingVariable<Set<String>>()
when:
def result = serviceMethod(arg1, arg2)
then:
1 * mockedClient.fetchDetails(_) >> futureList
0 * futureList.thenApplyAsync(_) >> futureSet
0 * futureSet.get(_,_) >> Collections.toSet("RESULT")
}
def " should return empty response when result retrieved from the client" () {
given:
def arg1 = "value1"
def arg2 = "value2"
def futureList = CompletableFuture.completedFuture(Collections.toList("RESULT"))
def futureSet = new BlockingVariable<Set<String>>()
when:
def result = serviceMethod(arg1, arg2)
then:
1 * mockedClient.fetchDetails(_) >> CompletableFuture.runAsync( { throw new Exception("Failed to fetch broker Analyst details " } )
0 * futureList.thenApplyAsync(_) >> futureSet
0 * futureSet.get(_,_) >> Collections.toSet("RESULT")
}
解决方案
这不是一个完整的答案,因为您也没有提供完整的MCVE。因此,我无法通过复制、编译和运行您的代码片段来重现您的问题。但有几件事让我觉得很奇怪:
你只是说有些东西不工作,但不显示任何错误消息和堆栈跟踪。
你的生产服务类使用
mockedclient
,至少名字很奇怪。为什么要在生产中使用模拟或使用模拟测试某些东西?futureList
在这两种功能方法中都不是模拟而是真实的对象。因此,您无法检查交互并返回类似0 * futureList.thenApplyAsync(_) >> futureSet
的存根结果。futureSet
在这两种功能方法中都不是模拟而是真实的对象。因此,您无法检查交互并返回类似0 * futureSet.get(_,_) >> Collections.toSet("RESULT")
的存根结果。在这两种功能方法中,您都使用了一个变量
mockedClient
,但忘记显示它的定义/初始化位置和方式。
我假设您的测试不仅在 Maven 上而且在本地也抛出错误,因为它们包含错误。
推荐阅读
- php - PHP:一个 HTML 隐藏的输入值在查询 mysql 时会产生一个错误
- swift - 如何将 Firestore DocumentID 映射到 RealmObject 属性?
- java - 在 MySQL WorkBench 中正确的 MySQL Query 在 JDBC 中给出 SQLSyntaxErrorException
- react-native - React Native 测试 - 无需等待即可行动
- java - 修复现场错误 - HRS_REQUEST_PARAMETER_TO_HTTP_HEADER
- python - 在 Python 中尝试使用 Matlab 时如何有效地解决此错误?
- html - 仅对列表中的第一项进行必填字段验证
- gf - 关于 prep 在 GF 中不存在
- sql - 具有唯一值的列的 SQL 总和量
- sql - 解析为表时 Oracle 游标声明不正确