springmockMVC测试方法GET

mar*_*ine 2 junit spring-boot mockmvc

我在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");
}
Run Code Online (Sandbox Code Playgroud)

我想写GET方法。

如何在mock mvc中编写get方法?如何验证我扔的东西是否被退回?

小智 5

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(MockMvcResultMatchers.status().isOk()).
        andExpect(MockMvcResultMatchers.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(MockMvcResultMatchers.status().isCreated())
        .andExpect(MockMvcResultMatchers.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);
}
Run Code Online (Sandbox Code Playgroud)