springboot进行mock测试

1、使用spring

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class PersonControllerTest2 {

    @Autowired
    private WebApplicationContext context;

    private MockMvc mockMvc;
    
 	@Before
  	public void setupMockMvc() {
        mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
    }

	@Test
    public void getHello() throws Exception {
       mockMvc.perform(post("/person/selectById").param("id","1").contentType(MediaType.APPLICATION_JSON_UTF8).accept(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(status().isOk()).andDo(print());
    }
 }

2、mock:默认提供一个模拟的web环境,不会启动内嵌的服务器,如果想启动内嵌web服务,可以使用@SpringBootTest的webEnviroment特性:
@SpringBootTest(classes = Application.class,webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
当WebEnvironment.RANDOM_PORT或者WebEnvironment.DEFINED_PORT时,都会提供一个真实的web环境,只不过前者是随机端口,而后者是默认端口

指定了SpringBootTest的webEnvironment 属性的同时,会为我们自动装配一个TestRestTemplate类型的bean来辅助我们发送请求

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class,webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class PersonControllerTest {
	@Autowired
    private TestRestTemplate restTemplate;
    
	@Test
    public void getHello2(){
    	MultiValueMap map= new LinkedMultiValueMap();
        multiValueMap.add("id","1");
        String response = restTemplate.postForObject("/api/hello/say",map,String.class);
        Assertions.assertThat(response).contains("hello");
    }
 }

你可能感兴趣的:(JAVA-EE,Spring)