SpringMVC 之MockMVC注釋 詳解
- 2020 年 4 月 7 日
- 筆記
SpringMVC的 Mockmvc的優勢:
所謂的Mock測試,就像servletAPI中的HttpServletRequest對象是Tomcat容器生成的。我們無法手動的new出來,於是就有了所謂的Mock測試
對模塊進行集成測試時,希望能夠通過輸入URL對Controller進行測試,如果通過啟動服務器,建立http client進行測試,這樣會使得測試變得很麻煩,比如啟動速度慢,測試驗證不方便,依賴網絡環境等,這樣會導致測試無法進行,為了可以對Controller進行測試,可以通過引入MockMVC進行解決。
pom.xml 依賴
<!-- spring-test --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring-framework.version}</version> <scope>test</scope> </dependency> <!-- junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency>
常用的注釋:
@RunWith(SpringJUnit4ClassRunner.class)
使用Spring-Test框架, 在使用所有注釋前必須使用 @RunWithSpringJUnit4ClassRunner.class),讓spring test 運行於Spring測試環境, 通俗的理解就是指定測試類使用某個運行器.
@WebAppConfiguration
使用這個注釋會在執行單元測試的時候真實的啟動一個web服務,然後開始調用Controller的Rest API,待單元測試執行完後再將web服務停止.
@ContextConfiguration
指定需要加載的spring配置文件的地址, 可以有多種方式. 如果有多個配置文件,可以用括號括起來,controller,component等都是使用註解,需要註解指定spring的配置文件,掃描相應的配置,將類初始化等。
@TransactionConfiguration(transactionManager="transactionManager",defaultRollback=true)
配置事務的回滾 ,對數據庫的增刪改都會回滾,便於測試用例的循環利用
@Transactional
非必須,是和@TestExecutionListeners中的TransactionalTestExecutionListener.class配合使用,用於保證插入的數據庫中的測試數據,在測試完後,事務回滾,將插入的數據刪除,保證數據庫的乾淨。如果沒有顯示的指定@Transactional,那麼插入到數據庫中的數據就是真實數據。
@Mock
MockMvc模擬MVC對象,通過MockMvcBuilders.webAppContextSetup(this.wac).build()進行初始化
@InjectMocks
需要將Mock對象注入的對象, 可以是被測的Controller
@Before
在每個Test方法之前運行的方法,一般用來初始化方法
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
@Test
執行測試
@Autowired
為Spring提供的註解,需要導入包org.springframework.beans.factory.annotation.Autowired;按照類型(byType)注入.默認情況下它要求依賴對象必須存在
@After
在每個測試方法後執行,在方法執行完成後要做的事情
實際運用:
import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.context.WebApplicationContext; //這個必須使用junit4.9以上才有 @RunWith(SpringJUnit4ClassRunner.class) //單元測試的時候真實的開啟一個web服務 @WebAppConfiguration //配置事務的回滾,對數據庫的增刪改都會回滾,便於測試用例的循環利用 @TransactionConfiguration(transactionManager="transactionManager",defaultRollback=true) @Transactional //指定需要加載的spring配置文件的地址, 可以有多種方式. 如果有多個配置文件 @ContextConfiguration(locations = {"classpath:spring.xml","classpath:spring-hibernate.xml"}) public class ControllerTest { MockMvc mockMvc; @Autowired //spring 自動注入 WebApplicationContext wac; @Autowired MyWebConfig myWebConfig=new MyWebConfig(); @Before //每次Test方法之前運行的方法,常用於初始化操作 public void setUp(){ System.out.println("----------Before----------"); DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac); //mockMvc= MockMvcBuilders.standaloneSetup(myWebConfig).build(); mockMvc = builder.build(); } @Test public void testUserController() throws Exception { this.mockMvc.perform(get("/deviceevent/list") // .accept(MediaType.parseMediaType("text/html;charset=UTF-8"))) .andExpect(status().isOk()) // 驗證status code .andExpect(model().size(1)) // } @After public void testAfter(){ System.out.println("-----------After-------------- "); } }
為什麼要做事務回滾?
在寫單元測試的時候,一般是對數據庫進行增刪改查的操作,這個時候,如果之前刪除了某條記錄,自然後面的程序就找不到這條記錄,所以可以通過配置spring的事務管理或者測試框架來回滾,減少工作量,同時也保證每一次測試的數據都是乾淨的。
測試是保證軟件質量的關鍵, mock是為了測試Web項目不需要啟動web server等服務項目,我們只需要一些Servlet相關的模擬對象,比如:MockMVC,MockHttpServletRequest,MockHttpServletResponse,MockHttpSession等。在Spring里,我們使用@WebAppConfiguration指定加載的ApplicationContext是一個WebAppConfiguration即可對某一模塊進行單獨測試.