gpt4 book ai didi

testing - Spock 和 Spock 报告 : how "catch" and customize the error message for AssertionError?

转载 作者:行者123 更新时间:2023-11-28 20:00:04 27 4
gpt4 key购买 nike

我正在与:

  • Spock 核心
  • 史波克报告
  • 斯波克 Spring
  • Spring MVC 测试

我有以下代码:

@FailsWith(java.lang.AssertionError.class)
def "findAll() Not Expected"(){

given:

url = PersonaUrlHelper.FINDALL;

when:

resultActions = mockMvc.perform(get(url)).andDo(print())

then:

resultActions.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_XML))


}

这里的代码失败(预期如何)因为被测试的方法确实返回(MediaType.APPLICATION_JSON)而不是 (MediaType.APPLICATION_XML)

所以@FailsWith(java.lang.AssertionError.class)的原因。

即使我使用 @FailsWith(value=java.lang.AssertionError.class, reason="JSON returned ...") 我也看不到原因 通过 Spock Reports

问题一:我如何在 Spock 报告 上看到原因

我知道 Spock 提供了 thrown() 方法,因此我可以这样做:

  then:
def e = thrown(IllegalArgumentException)
e.message == "Some expected error message"
println e.message

遗憾的是,thrown 对 AssertionError 不起作用。

如果我使用 thrown(AssertionError) 测试方法没有通过,唯一的方法是通过 @FailsWith 但我无法得到错误消息 来自断言错误

问题二如何从 AssertionError 获取错误信息

我知道我可以做类似的事情

then: "Something to show on Spock Reports"

只是好奇问题二能不能解决..

最佳答案

关于问题一:

如果您查看 FailsWithExtension#visitFeatureAnnotation,您可以看到只有来自 @FailsWith 的值被评估,reason 根本没有被触及.您可以做的是引入您自己的注释类型(自定义注释,例如与 @FailsWith 相同)并覆盖 AbstractAnnotationDrivenExtension#visitFeatureAnnotation。您可以在那里访问 reason 参数。

关于问题二:

请查看此链接:http://spock-framework.3207229.n2.nabble.com/Validate-exception-message-with-FailsWith-td7573288.html

此外,也许您可​​以覆盖 AbstractAnnotationDrivenExtension#visitSpec 并添加自定义监听器(覆盖 AbstractRunListener)。然后你可以访问 AbstractRunListener#error 方法,其文档说:

Called for every error that occurs during a spec run. May be called multiple times for the same method, for example if both * the expect-block and the cleanup-block of a feature method fail.

没有测试问题二,但它可能有效。我用过类似的东西。

享受,

汤米

关于testing - Spock 和 Spock 报告 : how "catch" and customize the error message for AssertionError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33856092/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com