问题描述
我正在尝试测试应该使用自定义错误属性的Spring Boot RestController.
I am trying to test a Spring Boot RestController that should use custom error attributes.
@Bean
public ErrorAttributes errorAttributes() {
return new DefaultErrorAttributes() {
@Override
public Map<String, Object> getErrorAttributes(
RequestAttributes requestAttributes,
boolean includeStackTrace) {
Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
Throwable error = getError(requestAttributes);
return errorAttributes;
}
};
}
但是,当我尝试使用简单的测试来测试自定义错误属性时,不会考虑这些属性.下面的测试实际上触发一个请求,除了使用自定义属性外,我.但是我似乎做的任何事情似乎都没有考虑到代码.
But when i try to test the custom error attributes using a simple test these properties are not taken into account. The test below actually fires a request and i except that the custom attributes are used. But whatever i seem to do the code seems to be not taken into account.
class TestSpec extends Specification {
MockMvc mockMvc
def setup() {
mockMvc = MockMvcBuilders.standaloneSetup(new HelloWorldController()).build()
}
def "Test simple action"() {
when:
def response = mockMvc.perform(post("/hello")
.contentType(MediaType.APPLICATION_JSON)
.content('{"sayHelloTo": ""}')
)
then:
response.andExpect(status().isOk())
}
}
关于如何测试自定义属性的任何线索吗?
Any clue on how i could test if the custom attributes?
推荐答案
Spring Boot的错误基础结构通过将请求转发到错误控制器来工作.这是使用ErrorAttributes
实例的错误控制器. MockMvc仅具有相当基本的支持来测试请求的转发(您可以检查请求是否将被转发,但不能检查该转发的实际结果).这意味着使用独立安装程序或基于Web应用程序基于上下文的安装程序调用您的HellowWorldController
的MockMvc测试不会驱动正确的代码路径.
Spring Boot's error infrastructure works by forwarding requests to an error controller. It's this error controller that uses an ErrorAttributes
instance. MockMvc only had fairly basic support for testing the forwarding of requests (you can check that the request would be forwarded, but not the actual outcome of that forward). This means that a MockMvc test that calls your HellowWorldController
, either using standalone setup or a web application context-based setup, isn't going to drive the right code path.
一些选项:
- 直接对自定义的
ErrorAttributes
类进行单元测试 - 编写一个基于MockMvc的测试,该测试调用使用自定义
ErrorAttributes
实例配置的Spring Boot的BasicErrorController
- 编写一个集成测试,该测试使用
RestTemplate
对您的服务进行实际的HTTP调用
- Unit test your custom
ErrorAttributes
class directly - Write a MockMvc-based test that calls Spring Boot's
BasicErrorController
configured with your customErrorAttributes
instance - Write an integration test that uses
RestTemplate
to make an actual HTTP call into your service
这篇关于使用自定义的ErrorAttributes测试Spring Boot应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!