上次寫完了一個(gè)controller,這次我可以講講怎么寫一下測試,單元測試對于我們開發(fā)人員來說是一個(gè)十分重要的知識點(diǎn),所以我特地記錄一下
增加單元測試需要在pom.xml加上這個(gè),有了就不用加了
'''
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
'''

先介紹一下,測試的基本用法分為
Service層單元測試
Controller層單元測試
新斷言assertThat使用
單元測試的回滾
在寫測試類之前,先新建service類,

在建立了service類之后,再新建test類,其中我繼承了DemoTestApplicationTests是因?yàn)槲覒械脤慇RunWith(SpringRunner.class)
和@SpringBootTest,所以通過繼承的方式來實(shí)現(xiàn)

代碼為:
'''
package com.example.test.demotest.test;
import com.example.test.demotest.DemoTestApplicationTests;
import com.example.test.demotest.service.IGetService;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import static org.assertj.core.internal.bytebuddy.matcher.ElementMatchers.is;
/**
* @author qiubo
* @date 2019/1/20
*/
public class ServiceTestextends DemoTestApplicationTests {
@Autowired
? IGetServicegetService;
@Test
? ? public void test(){
Assert.assertEquals(getService.getTest(),"testService");
//Assert.assertEquals(getService.getTest(),"test");
? ? }
}
'''
運(yùn)行這個(gè)類,你會發(fā)現(xiàn)沒有問題,當(dāng)你取消掉Assert.assertEquals(getService.getTest(),"test");這句注釋,你會發(fā)現(xiàn)程序報(bào)錯(cuò),這就說明他與你期望的值并不一樣
controller的測試:
'''
package com.example.test.demotest.test;
import com.example.test.demotest.DemoTestApplicationTests;
import com.example.test.demotest.controller.TestController;
import com.example.test.demotest.service.IGetService;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
/**
* @author qiubo
* @date 2019/1/20
*/
public class ServiceTestextends DemoTestApplicationTests {
@InjectMocks
? ? private TestControllercontroller;
@Autowired
? ? IGetServicegetService;
private MockMvcmockMvc;
@Before
? ? public void setUp()throws Exception {
this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
MockitoAnnotations.initMocks(this);
}
@Test
? ? public void test(){
Assert.assertEquals(getService.getTest(),"testService");
//Assert.assertEquals(getService.getTest(),"test");
? ? }
@Test
? ? public void testController()throws Exception {
MvcResult mvcResult =this.mockMvc.perform(MockMvcRequestBuilders.get("/test"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string("test"))
.andReturn();
System.out.println(mvcResult.getResponse().getContentAsString());
}
}
'''

剩下的回滾和斷言可以看這個(gè)網(wǎng)址,它上面介紹的非常好
http://tengj.top/2017/12/28/springboot12/