九 单元测试
1.测试service
在service中添加方法
/**
* 根据id找到对应学生
*/
public Stu findOne(Integer id) {
return sturepository.findOne(id);
}
在test文件下,创建com.boot包,创建ApplicationTest类
package com.boot;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTest {
@Test
public void contextLoads(){
}
}
创建service包,新建StuServiceTest
package com.boot.service;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.boot.entity.Stu;
@RunWith(SpringRunner.class)
@SpringBootTest
public class StuServiceTest {
@Autowired
private IStuService stuservice;
@Test
public void findOneTest(){
Stu stu= stuservice.findOne(6);
Assert.assertEquals(new Integer(24), Integer.valueOf(stu.getAge()));
}
}
在方法上run,执行该方法。
2.测试api
对stuList方法测试
新建web包,新建StuControllerTest类
package com.boot.web;
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.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class StuControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void girlList() throws Exception{
mockMvc.perform(MockMvcRequestBuilders.get("/stu")).andExpect(MockMvcResultMatchers.status().is(200));
}
}
andExpect可以一直添加。