springboot 学习笔记(二) 之测试用例

1.上一篇博客是初步建立了springboot。接下来我们编写测试用例来测试springboot的运行结果。

2.在 test/java 目录下建立一个测试用例类

package com.myspringboot.study;

import com.myspringboot.web.HelloController;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import static org.hamcrest.core.IsEqual.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@SpringBootTest(classes=HelloController.class)
@AutoConfigureMockMvc
public class StudyApplicationTests {

	@Test
	public void contextLoads() {
	}


	@Autowired
	private MockMvc mvc;

	@Test
	public void getHello() throws Exception {
		mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
				.andExpect(status().isOk())
				.andExpect(content().string(equalTo("hello world")));
	}

}

上面的SpringBootTest(classes=)指向的是测试的controller

而下面的getHello方法,是通过模拟请求 /hello 地址,判断他的状态和他的返回结果。

猜你喜欢

转载自my.oschina.net/u/1178126/blog/1811439