如何在春季测试中发送json而不是params



我使用org.springframework.test.web.servlet.MockMvc.调用Spring控制器

它看起来像这样:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/spring/root-context.xml" })
public class TestController {
    @Mock
    private TestService testService;
    @InjectMocks
    private TestController testController;
    private MockMvc mockMvc;
    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        this.setMockMvc(MockMvcBuilders.standaloneSetup(testtController).build());
    }
    @Test
    public void test() throws Exception {
        this.mockMvc.perform(post("/trans/").param("name", "grep")).andExpect(status().isOk());
    }

一切看起来都很好。我也可以通过参数。但现在我需要发送JSON(字符串)而不是params。我该怎么做?

您应该使用.content()而不是.param():

post("/trans/").content("{"name": "grep"}")

使用.content()而不是.param(),并且应该设置contentType

post("/trans/").contentType(MediaType.APPLICATION_JSON).content("{"name": "grep"}")

最新更新