spring boot junit test


這里分三種,1、測普通方法或通過原生java API接口調用 2、基於spring依賴注入調用 3、controller層調用

需要引入依賴:默認springboot已經引入

     <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

在src/test/java下建立test類

1、測普通方法或通過原生java API接口調用

public class commonTest {

    @Test
    public void testPrint() {
        System.out.println(2222222);
    }
}

 2、基於spring依賴注入調用 內部可以通過@autowired、@Resourced等注入對象實例

@RunWith(SpringRunner.class)
@SpringBootTest
public class applicationTest {
    //注入的接口類
    @Autowired
    private TestService testService;
    @Test
    public void contextLoads() throws Exception{
        testService.print();
    }
}
public interface TestService {

    public void print()throws Exception;
}
@Service("testService")
public class TestServiceImpl implements TestService {

    @Override
    public void print() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("service print test...");
    }

}

3、 controller層調用

@SpringBootTest
public class ControllerTest {
    private MockMvc mockMvc;
    //@Before注解的表示在測試啟動的時候優先執行,一般用作資源初始化。
    //這里初始化生成controller類單例
    @Before 
    public void setUp()throws Exception{
        mockMvc=MockMvcBuilders.standaloneSetup(new TestController()).build();
    }
        @Test 
        public void controllerTest()throws Exception{
             String returnJson = mockMvc.perform(MockMvcRequestBuilders.post("/list")).andReturn().getResponse().getContentAsString();
             System.out.println(returnJson);
        }
}
@RestController
public class TestController {
    @RequestMapping(value="/list",method={RequestMethod.POST})
    public List<TestVO> getTestList() {
        List<TestVO> vos = new ArrayList<TestVO>();
        TestVO vo = new TestVO();
        vo.setAge(13);
        vo.setName("薛邵");
        vo.setSex(true);
        vo.setDate(new Date());
        vos.add(vo);
        TestVO vo1 = new TestVO();
        vo1.setAge(15);
        vo1.setName("xiaoming");
        vo1.setSex(false);
        vo1.setDate(new Date());
        vos.add(vo1);
        return vos;
    }
}


MockMvc 調用controller接口的幾個示例:

A
//get請求一個查詢/test/hhhhhhh/99,控制台打印http請求和響應信息
//print()方法,需要靜態引入import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
mockMvc.perform(MockMvcRequestBuilders.get("/test/hhhhhhh/99").accept(MediaType.APPLICATION_JSON_UTF8)).andDo(print());
打印示例如下:

 

 

 其中Body= aaaaaaaaaaaaaaaaaaaaaaaahhhhhhh99即我們預期打印的內容,也就是controller接口返回的文本

B

//通過.addExpect來判斷預期內容是否符合,如果符合控制台無信息,如果不符合,junit控制台會顯示具體錯誤信息
//.accept(MediaType.APPLICATION_JSON_UTF8)
//這句主要是設置JSON返回編碼,避免出現中文亂碼問題
mockMvc.perform(MockMvcRequestBuilders.get("/test/hhhhhhh/99").accept(MediaType.APPLICATION_JSON_UTF8)).andExpect(MockMvcResultMatchers.content().string(Matchers.containsString("hhhhhhh991")));

C
//獲取返回內容直接輸出打印
String returnJson = mockMvc.perform(MockMvcRequestBuilders.post("/testvo")).andReturn().getResponse().getContentAsString();
System.out.println(returnJson);

D
//設置參數POST提交

mockMvc.perform(MockMvcRequestBuilders.post("/v")
// .param("age", "28")
// .param("name", "aaa")
// .param("list", "[\"bb\",\"cc\"]")
// .param("card", "123456789012345678")
// .param("date", "2019-10-01 11:09:11")
// .param("weight", "99.99")
// .param("sex", "true")
//// .param("tmp", "")
//// .param("phone", "")
// .param("dicimal", "18")
// .param("email", "aaa")
);




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM