当异步客户端调用涉及多个测试时,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,至少名称很奇怪。为什么要在生产中使用mock或使用mock测试某些东西?

  • 两种特征方法中的futureList都不是模拟对象,而是真实对象。因此,您无法检查交互并在其上返回像0 * futureList.thenApplyAsync(_) >> futureSet这样的存根结果

  • 两种特征方法中的futureSet都不是模拟对象,而是真实对象。因此,您无法检查交互并在其上返回像0 * futureSet.get(_,_) >> Collections.toSet("RESULT")这样的存根结果

  • 在这两种特性方法中,您都使用了一个变量mockedClient,但忘记了显示它在哪里以及如何定义/初始化。

我认为您的测试不仅在Maven上抛出错误,而且在本地也抛出错误,因为它们包含错误。

最新更新