spring mockMVC测试方法GET
Posted
技术标签:
【中文标题】spring mockMVC测试方法GET【英文标题】:spring mockMVC testing method GET 【发布时间】:2018-10-22 15:03:01 【问题描述】:我在 mockMVC 中创建了 post 方法(在 spring boot 项目中) 这是我的方法测试
这是我的方法测试
@Test
public void createAccount() throws Exception
AccountDTO accountDTO = new AccountDTO("SAVINGS", "SAVINGS");
when(addaccountService.findByName("SAVING")).thenReturn(Optional.empty());
when(addaccountService.createAccount(any())).thenReturn(createdAccountDTO);
CreatedAccountDTO createdAccountDTO = new CreatedAccountDTO("a@wp.pl", "SAVINGS", "1234rds", uuid);
mockMvc.perform(
post("/account").contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(AccountNewDTO)))
.andExpect(status().isCreated())
.andExpect(header().string("location", containsString("/account/"+uuid.toString())));
System.out.println("aaa");
我想写GET方法。
如何在 mock mvc 中编写 get 方法?如何验证我扔的东西是否被退回?
【问题讨论】:
【参考方案1】:You can try the below for Mockmvc perform get and post methods
For get method
@Autowired
private MuffinRepository muffinRepository;
@Test
public void testgetMethod throws Exception()
Muffin muffin = new Muffin("Butterscotch");
muffin.setId(1L);
BddMockito.given(muffinRepository.findOne(1L)).
willReturn(muffin);
mockMvc.perform(MockMvcRequestBuilders.
get("/muffins/1")).
andExpect(MockMvcResutMatchers.status().isOk()).
andExpect(MockMvcResutMatchers.content().string("\"id\":1, "flavor":"Butterscotch""));
//Test to do post operation
@Test
public void testgetMethod throws Exception()
Muffin muffin = new Muffin("Butterscotch");
muffin.setId(1L);
BddMockito.given(muffinRepository.findOne(1L)).
willReturn(muffin);
mockMvc.perform(MockMvcRequestBuilders.
post("/muffins")
.content(convertObjectToJsonString(muffin))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResutMatchers.status().isCreated())
.andExpect(MockMvcResutMatchers.content().json(convertObjectToJsonString(muffin)));
If the response is empty then make sure to override equals() and hashCode() method on the Entity your repository is working with
//Converts Object to Json String
private String convertObjectToJsonString(Muffin muffin) throws JsonProcessingException
ObjectWriter writer = new ObjectWriter().writer().withDefaultPrettyPrinter();
return writer.writeValueAsString(muffin);
【讨论】:
@martine 你可以试试上面的代码sn-p 来做mockmvc的get和post操作【参考方案2】:可以使用MockMvcRequestBuilders
类的静态get
方法,见:https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/web/servlet/request/MockMvcRequestBuilders.html#get-java.lang.String-java.lang.Object...-
例子:
mockMvc.perform(get("/account")).andExpect(...);
如果您在控制器方法中抛出异常,它通常会触发异常处理程序的执行,该处理程序会将异常转换为 HTTP 错误响应。默认情况下,您可以检查响应的状态是否为 500。如果您已经实现了自己的异常处理程序,您可能还需要检查响应正文以验证它是否包含预期的错误数据。
【讨论】:
谢谢,所以我的get测试方法是:@Test public void getAccount()throws Exception AccountDTO accountDTO = new AccountDTO(); AccountDTO.setEmail("a@wp.pl"); AccountDTO.setName("SAVINGS"); when(addaccountService.findByName("SAVING")).thenReturn(Optional.empty()); when(addaccountService.createAccount(any())).thenReturn(createdAccountDTO); CreatedAccountDTO createdAccountDTO = new CreatedAccountDTO("a@wp.pl", "SAVINGS", "1234rds", uuid); mockMvc.perform(get("/account").contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); .content(asJsonString(accountDTO))).andExpect(status().isOk()) .andExpect(header().string("location", containsString("/users/"+uuid.toString()))); ; java.lang.AssertionError: Status Expected :200 Actual :500 at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:55) at org.springframework org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:617) 中的 .test.util.AssertionErrors.assertEquals(AssertionErrors.java:82)。 servlet.MockMvc$1.andExpect(MockMvc.java:179) 我实际上有一个错误。我的测试有什么问题?如何改进? @Test public void getUser()throws Exception mockMvc.perform( get( "/users" ) ).andExpect( status().isOk() ).andExpect( view().name( “家”));以上是关于spring mockMVC测试方法GET的主要内容,如果未能解决你的问题,请参考以下文章
使用mockMvc做Spring测试时怎么传递数组类型的参数啊?
我需要创建方法get()和status()来创建一个带有mockmvc的测试控制器?