小编Vol*_*ıcı的帖子

使用MockMvc在Spring MVC中进行单元测试/登录

我有一个使用Spring MVC创建的非常简单的REST应用程序.(代码可在GitHub上获得.)它有WebSecurityConfigurer如下简单:

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
            .csrf().disable()
            .exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint)
                .and()
            .authorizeRequests()
                .antMatchers("/user/new").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login").permitAll()
                .successHandler(authenticationSuccessHandler)
                .failureHandler(authenticationFailureHandler)
                .and()
            .logout()
                .permitAll()
                .logoutSuccessHandler(logoutSuccessHandler);
}
Run Code Online (Sandbox Code Playgroud)

当我运行应用程序时,自定义控制器和登录/注销页面都可以正常运行.我甚至可以通过单元测试 .但是,当我尝试使用以下功能进行测试时/user/newMockMvc/login

@Test
public void testUserLogin() throws Exception {
    RequestBuilder requestBuilder = post("/login")
            .param("username", testUser.getUsername())
            .param("password", testUser.getPassword());
    mockMvc.perform(requestBuilder)
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(cookie().exists("JSESSIONID"));
}
Run Code Online (Sandbox Code Playgroud)

它失败如下:

MockHttpServletRequest:
         HTTP Method = POST
         Request URI = /login
          Parameters = {username=[test-user-UserControllerTest], password=[test-user-UserControllerTest-password]}
             Headers = {}

             Handler:
                Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler

               Async: …
Run Code Online (Sandbox Code Playgroud)

java spring unit-testing spring-mvc mockmvc

10
推荐指数
2
解决办法
1万
查看次数

Spring MVC测试中的空异常体

我在尝试使MockMvc在响应正文中包含异常消息时遇到了麻烦.我有一个控制器如下:

@RequestMapping("/user/new")
public AbstractResponse create(@Valid NewUserParameters params, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) throw BadRequestException.of(bindingResult);
    // ...
}
Run Code Online (Sandbox Code Playgroud)

这里BadRequestException看上去某事像这样:

@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "bad request")
public class BadRequestException extends IllegalArgumentException {

    public BadRequestException(String cause) { super(cause); }

    public static BadRequestException of(BindingResult bindingResult) { /* ... */ }

}
Run Code Online (Sandbox Code Playgroud)

我对/user/new控制器运行以下测试:

@Test
public void testUserNew() throws Exception {
    getMockMvc().perform(post("/user/new")
            .param("username", username)
            .param("password", password))
            .andDo(print())
            .andExpect(status().isOk());
}
Run Code Online (Sandbox Code Playgroud)

它打印以下输出:

  Resolved Exception:
                Type = controller.exception.BadRequestException

        ModelAndView:
           View name = null
                View …
Run Code Online (Sandbox Code Playgroud)

spring exception-handling spring-mvc spring-mvc-test

9
推荐指数
1
解决办法
2825
查看次数

如何仅针对单个 Maven 模块运行测试?

dad给定一个带有模块和的 Maven 项目son,其中son依赖于dad,也mvn -am -pl son test运行测试dad。有没有办法避免这种情况并且只对son模块运行测试?

请注意,有几种方法可以实现此目的,尽管每种方法都有其自己的警告,但我不喜欢:

  • 使用-Dtest="**/son/*Test.java" -DfailIfNoTests=false覆盖maven-surefire-plugin模块中的配置。
  • 与 类似-Dtest,JUnit 5 标签也可以被过滤,但这种方法也有前面提到的同样的缺点。
  • 可以先执行 aninstall -DskipTests=true然后执行mvn -pl son test,尽管这会因部分工作而污染本地 Maven 存储库。

java maven maven-surefire-plugin

9
推荐指数
2
解决办法
2544
查看次数