标签: spring-test-mvc

如何使用mockMvc检查响应体中的String

我有简单的集成测试

    @Test
public void shouldReturnErrorMessageToAdminWhenCreatingUserWithUsedUserName() throws Exception {
    mockMvc.perform(post("/api/users").header("Authorization", base64ForTestUser).contentType(MediaType.APPLICATION_JSON)
            .content("{\"userName\":\"testUserDetails\",\"firstName\":\"xxx\",\"lastName\":\"xxx\",\"password\":\"xxx\"}"))
            .andDo(print())
            .andExpect(status().isBadRequest())
            .andExpect(?);
}
Run Code Online (Sandbox Code Playgroud)

在最后一行中,我想将响应体中收到的字符串与期望的字符串进行比较

作为回应,我得到:

MockHttpServletResponse:
          Status = 400
   Error message = null
         Headers = {Content-Type=[application/json]}
    Content type = application/json
            Body = "Username already taken"
   Forwarded URL = null
  Redirected URL = null
Run Code Online (Sandbox Code Playgroud)

尝试使用content(),body()但没有任何效果.

java spring mocking spring-test-mvc

214
推荐指数
10
解决办法
24万
查看次数

用jsonpath计算成员?

是否可以使用JsonPath计算成员数?

使用spring mvc test我正在测试一个生成的控制器

{"foo": "oof", "bar": "rab"}
Run Code Online (Sandbox Code Playgroud)

standaloneSetup(new FooController(fooService)).build()
            .perform(get("/something").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
            .andExpect(jsonPath("$.foo").value("oof"))
            .andExpect(jsonPath("$.bar").value("rab"));
Run Code Online (Sandbox Code Playgroud)

我想确保生成的json中没有其他成员.希望通过使用jsonPath计算它们.可能吗?也欢迎替代解决方案.

java testing spring jsonpath spring-test-mvc

95
推荐指数
3
解决办法
6万
查看次数

如何为Spring Boot Controller端点编写单元测试

我有一个示例Spring Boot应用程序,其中包含以下内容

启动主类

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
Run Code Online (Sandbox Code Playgroud)

调节器

@RestController
@EnableAutoConfiguration
public class HelloWorld {
    @RequestMapping("/")
    String gethelloWorld() {
        return "Hello World!";
    }

}
Run Code Online (Sandbox Code Playgroud)

为控制器编写单元测试最简单的方法是什么?我尝试了以下但它抱怨无法自动装载WebApplicationContext

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = DemoApplication.class)
public class DemoApplicationTests {

    final String BASE_URL = "http://localhost:8080/";

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void testSayHelloWorld() throws Exception{

         this.mockMvc.perform(get("/")
                 .accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
                 .andExpect(status().isOk())
                 .andExpect(content().contentType("application/json"));
    }

    @Test
    public void contextLoads() {
    } …
Run Code Online (Sandbox Code Playgroud)

java junit unit-testing spring-test-mvc spring-boot

68
推荐指数
4
解决办法
10万
查看次数

如何使用mockMvc检查响应体中的JSON

这是我的控制器里面的方法,注释方法是 @Controller

@RequestMapping(value = "/getServerAlertFilters/{serverName}/", produces = "application/json; charset=utf-8")
    @ResponseBody
    public JSONObject getServerAlertFilters(@PathVariable String serverName) {
        JSONObject json = new JSONObject();
        List<FilterVO> filteredAlerts = alertFilterService.getAlertFilters(serverName, "");
        JSONArray jsonArray = new JSONArray();
        jsonArray.addAll(filteredAlerts);
        json.put(SelfServiceConstants.DATA, jsonArray);
        return json;
    }
Run Code Online (Sandbox Code Playgroud)

我期待着{"data":[{"useRegEx":"false","hosts":"v2v2v2"}]}作为我的json.

这是我的JUnit测试:

@Test
    public final void testAlertFilterView() {       
        try {           
            MvcResult result = this.mockMvc.perform(get("/getServerAlertFilters/v2v2v2/").session(session)
                    .accept("application/json"))
                    .andDo(print()).andReturn();
            String content = result.getResponse().getContentAsString();
            LOG.info(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是控制台输出:

MockHttpServletResponse:
              Status = 406
       Error message = null
             Headers = {} …
Run Code Online (Sandbox Code Playgroud)

java junit spring mocking spring-test-mvc

34
推荐指数
4
解决办法
7万
查看次数

使用Spring Security进行Spring MVC集成测试

我正在尝试使用mvc-test测试我的登录页面.在我添加spring security之前,我工作得很好.

我的代码是:

 mockMvc.perform(
     post("j_spring_security_check")
                    .param(LOGIN_FORM_USERNAME_FIELD, testUsernameValue)
                    .param(LOGIN_FORM_PASSWORD_FIELD, testPasswordValue))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(model().attribute(LOGIN_PAGE_STATUS_VALUE, LOGIN_PAGE_STATUS_FALSE_INDICATOR));
Run Code Online (Sandbox Code Playgroud)

测试类添加了正确的注释:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:security-context.xml", "classpath:applicationContext.xml", "classpath:test-contexts/test-context.xml" })
Run Code Online (Sandbox Code Playgroud)

我的过滤器已定义(在web.xml中):

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
Run Code Online (Sandbox Code Playgroud)

当我尝试在@ContextConfiguration中添加web.xml时,它会失败,当我删除它时,我得到一个例外:

java.lang.AssertionError: Status expected:<200> but was:<405>
Run Code Online (Sandbox Code Playgroud)

有没有办法添加DelegatingProxyFilter来测试上下文与我的security-context.xml中定义的配置,使其工作?我尝试了一些注入FilterProxyChain的教程,但它不适用于我的情况.

有人可以帮助我吗?提前致谢

spring-mvc spring-security spring-test-mvc

26
推荐指数
1
解决办法
3万
查看次数

如何在Spring MVC中模拟安全上下文进行测试

我需要测试一些受保护的URL,因此我需要在我的测试中设置一个模拟安全上下文(junit).
特别是我需要使用经过身份验证的用户对我的Web应用程序执行一些获取和发布.下面是我的代码,我能够创建这样的安全上下文,但我需要将它注入'MockMvc'对象.
我在安全上下文中设置了身份验证对象并且它正常工作,'SecurityContextHolder.getContext().getAuthentication().getPrincipal()'的输出结果是chanelle.evans@616747.com但是当我在/ profile上调用GET时有一个断言错误,因为我被重定向到我的登录页面,而不是/ profile.

@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:spring/security.xml", "classpath:spring/view.xml"})
@ActiveProfiles("default")
@RunWith(SpringJUnit4ClassRunner.class)
public class AuthenticationTest {

@Autowired
WebApplicationContext ctx;

private MockMvc mockMvc;

@Autowired
private FilterChainProxy springSecurityFilterChain;

@BeforeClass
public static void setUpBeforeClass() throws Exception {
}

@AfterClass
public static void tearDownAfterClass() throws Exception {
}

@Before
public void setUp() throws Exception {
    mockMvc = MockMvcBuilders.webAppContextSetup(ctx).addFilters(springSecurityFilterChain).build();

    //@formatter:off

    UserDetailsLogic userDetailsLogic = null;
    userDetailsLogic = ctx.getBean(UserDetailsLogic.class);
    final UserDetailsImp userDetailsImp = new UserDetailsImp();
    userDetailsImp.setAccountId(1001);
    userDetailsImp.setUserId(8001);
    userDetailsImp.setPassword("a378c92df7531df6fdf351f7ae1713f91f2dd2d45b9c6e1a8b02736ee3afec6595ff60465e9cb8da");
    userDetailsImp.setUsername("chanelle.evans@616747.com");
    userDetailsImp.setEmail("chanelle.evans@616747.com");

    final Collection<GrantedAuthorityImplementation> authorities= new ArrayList<GrantedAuthorityImplementation>();
    authorities.add(new GrantedAuthorityImplementation("ROLE_USER")); …
Run Code Online (Sandbox Code Playgroud)

junit spring spring-mvc spring-security spring-test-mvc

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

使用MockMVC进行集成测试Spring Boot

我在使用MockMvc测试Spring Boot应用程序时遇到了一些麻烦.

我有以下测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {SpringConfiguration.class, SecurityConfiguration.class})
@IntegrationTest({"server.port=8080"})
@WebAppConfiguration
public class DemoTest {

@Autowired
private EmbeddedWebApplicationContext webApplicationContext;

private MockMvc mockMvc;

@Before
public void setUp() throws Exception {
    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}

@Test
public void testGetAccountUnauthenticated() throws Exception {
    mockMvc.perform(get("/accounts/1").accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isUnauthorized());
}
}
Run Code Online (Sandbox Code Playgroud)

这导致HTTP 200而不是401.我启用了组件扫描和自动配置,并在我的SecuityConfiguration类中配置了spring安全性,如下所示:

@Configuration
@EnableWebSecurity
@EnableWebMvcSecurity // required for use of @AuthenticationPrincipal in MVC controllers.
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Override
public void configure(WebSecurity web) {
    web.debug(true);
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    //set …
Run Code Online (Sandbox Code Playgroud)

spring-security spring-test spring-test-mvc spring-boot mockmvc

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

Spring的MockMvc用于单元测试或集成测试吗?

Spring有两个MockMvc设置:

  1. 独立设置
  2. WebApplicationContext设置

一般来说,MockMvc用于什么样的测试?单位还是整合?或两者?

我是否正确地说使用独立设置(在Spring的应用程序上下文之外运行)允许您编写单元测试,并且使用WebApplicationContext设置可以编写集成测试?

java spring spring-mvc spring-test spring-test-mvc

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

在SpringBoot 1.4中测试Spring MVC切片的问题

我正在尝试新的Spring Boot 1.4 MVC测试功能.我有以下控制器.

@Controller
public class ProductController {

  private ProductService productService;

  @Autowired
  public void setProductService(ProductService productService) {
    this.productService = productService;
  }

  @RequestMapping(value = "/products", method = RequestMethod.GET)
  public String list(Model model){
    model.addAttribute("products", productService.listAllProducts());
     return "products";
  }
}
Run Code Online (Sandbox Code Playgroud)

我最小的ProductService实现是:

@Service
public class ProductServiceImpl implements ProductService {
  private ProductRepository productRepository;

  @Autowired
  public void setProductRepository(ProductRepository productRepository) {
    this.productRepository = productRepository;
  }

  @Override
  public Iterable<Product> listAllProducts() {
    return productRepository.findAll();
  }

}
Run Code Online (Sandbox Code Playgroud)

ProductRepository的代码是:

public interface ProductRepository extends CrudRepository<Product,    
 Integer>{
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用新的@WebMvcTest来测试控制器.我的观点是百里香的teamplate.我的控制器测试是这样的:

@RunWith(SpringRunner.class)
@WebMvcTest(ProductController.class)

public …
Run Code Online (Sandbox Code Playgroud)

spring-mvc spring-test-mvc spring-boot

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

如何使用Spring MockMvc输出multipart/form-data?

我有方法的控制器PUT方法,它接收multipart/form-data:

   @RequestMapping(value = "/putIn", method = RequestMethod.PUT)
   public Foo updateFoo(HttpServletRequest request,
                           @RequestBody Foo foo,
                           @RequestParam("foo_icon") MultipartFile file) {
    ...
   }
Run Code Online (Sandbox Code Playgroud)

我想用它来测试它MockMvc.不幸的是,MockMvcRequestBuilders.fileUpload基本上创建了MockMultipartHttpServletRequestBuilder一个POST方法:

super(HttpMethod.POST, urlTemplate, urlVariables)
Run Code Online (Sandbox Code Playgroud)

编辑: 我一定能 ,我不能创建自己的实现MockHttpServletRequestBuilder,比如

public MockPutMultipartHttpServletRequestBuilder(String urlTemplate, Object... urlVariables) {
    super(HttpMethod.PUT, urlTemplate, urlVariables);
    super.contentType(MediaType.MULTIPART_FORM_DATA);
}
Run Code Online (Sandbox Code Playgroud)

因为MockHttpServletRequestBuilder有包本地构造函数.

但我想知道是否更方便有任何方法可以做到这一点,可能是我错过了一些现有的课程或方法吗?

java spring multipartform-data spring-test-mvc mockmvc

14
推荐指数
3
解决办法
7089
查看次数