首页 > 解决方案 > 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")
 }

标签: javaunit-testingasynchronousspock

解决方案


这不是一个完整的答案,因为您也没有提供完整的MCVE。因此,我无法通过复制、编译和运行您的代码片段来重现您的问题。但有几件事让我觉得很奇怪:

  • 你只是说有些东西不工作,但不显示任何错误消息和堆栈跟踪。

  • 你的生产服务类使用mockedclient,至少名字很奇怪。为什么要在生产中使用模拟或使用模拟测试某些东西?

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

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

  • 在这两种功能方法中,您都使用了一个变量mockedClient,但忘记显示它的定义/初始化位置和方式。

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


推荐阅读