弹簧测试中@Autowired MockMvc和webAppContextSetup之间的区别

时间:2018-02-21 08:08:26

标签: java spring spring-test

有两种方法可以在spring测试中实例化MockMvc@AutowiredwebAppContextSetup(webApplicationContext).build();

在春天的getting started guide

@RunWith(SpringRunner.class)
@WebMvcTest(GreetingController.class)
public class WebMockTest {

    @Autowired
    private MockMvc mockMvc;

    // ...

    @Test
    public void greetingShouldReturnMessageFromService() throws Exception {
        this.mockMvc.perform(get("/greeting")).andDo(print()).andExpect(status().isOk());
    }
}

在春天的tutorial

@Before
public void setup() throws Exception {
    this.mockMvc = webAppContextSetup(webApplicationContext).build();
    // ...
}

我的一个观察是,当spring-security在类路径中时,两个mockMvc的行为不同。在类路径中使用spring-security时,所有HTTP端点都使用基本身份验证进行保护,如doc中所述。

我希望测试

this.mockMvc.perform(get("/greeting")).andDo(print()).andExpect(status().isOk());

因为没有提供凭据而无法使用HTTP 401。 @Autowired

就属于这种情况
MockHttpServletResponse:
           Status = 401
    Error message = Full authentication is required to access this resource
          Headers = {X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY], Strict-Transport-Security=[max-age=31536000 ; includeSubDomains], WWW-Authenticate=[Basic realm="Spring"]}
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

但测试仍然通过mockMvc = webAppContextSetup(...).build()版本

它们的区别和使用时间是什么?

0 个答案:

没有答案
相关问题