Tool preparation
Test framework dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter-test</artifactId>
<version>3.5.2</version>
</dependency>
Test base class
@Configuration
@AutoConfigureMybatisPlus
@ImportAutoConfiguration
@MapperScan(basePackages = "com.xxx.osp.basic.mapper.**.*")
@EnableWebMvc
public class TestConfiguration {
}
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class)
@AutoConfigureMockMvc
@WebAppConfiguration
public class BaseControllerTest {
@Autowired
public MockMvc mockMvc;
public String doPost(String url, String json) throws Exception {
ResultActions perform = mockMvc.perform(MockMvcRequestBuilders.post(url)
.content(json)
.contentType(MediaType.APPLICATION_JSON)
);
return print(perform);
}
public String doGet(String url, Map<String, String> params) throws Exception {
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(url)
.contentType(MediaType.APPLICATION_FORM_URLENCODED);
if (!params.isEmpty()) {
params.forEach((key, value) -> {
requestBuilder.param(key, value);
});
}
ResultActions perform = mockMvc.perform(requestBuilder);
return print(perform);
}
public String print(ResultActions resultActions) throws Exception {
String result = resultActions.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn().getResponse().getContentAsString();
System.out.println("resultData: " + result);
return result;
}
}
Test class writing
@Import({MsgSceneServiceImpl.class, MsgSceneController.class})
public class MsgSceneControllerTest extends BaseControllerTest {
@Test
public void testCreate() throws Exception {
String url = "/v1/msg/scene/create";
List<MsgSceneParamItem> list = new ArrayList<>();
list.add(new MsgSceneParamItem("名称", "name"));
list.add(new MsgSceneParamItem("账号", "account"));
list.add(new MsgSceneParamItem("签名", "sign"));
MsgSceneCreateVO vo = new MsgSceneCreateVO();
vo.setCode("0003")
.setType(4)
.setName("创建验证")
.setTag("验证登陆")
.setRemark("备注")
.setParam(list);
String json = JsonUtils.object2Json(vo);
System.out.println("参数:" + json);
System.out.println("参数结束");
String result = doPost(url, json);
System.out.println("结果返回:");
System.out.println(result);
}
}
MsgSceneController
It needs to be injected MsgSceneServiceImpl
, so Import comes in
Record error resolution:
- Content type 'application/json' not supported, if this error is reported, check if
TestConfiguration
the class is not annotated@EnableWebMvc
, and it can be solved by adding it - Parameter passing error resolution
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class com.xxx.osp.basic.model.bo.msg.MsgSceneParamItem]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.xxx.osp.basic.model.bo.msg.MsgSceneParamItem` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
at [Source: (PushbackInputStream); line: 1, column: 78] (through reference chain: com.xxx.osp.basic.model.vo.msg.request.MsgSceneCreateVO["param"]->java.util.ArrayList[0])
Error message: The class MsgSceneParamItem
does not have a default constructor, just add a parameterless constructor, because when deserializing the parameters, the parameterless constructor is used to create an object. If the default constructor is not provided, it will be serialized fail!