日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

junit 测试mvc_Spring MVC控制器JUnit测试

發布時間:2023/12/3 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 junit 测试mvc_Spring MVC控制器JUnit测试 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

junit 測試mvc

JUnit測試Spring MVC控制器并非易事 。 但是最近,一個新項目 (即將在Spring推出)提供了新的工具來簡化此工作。 這篇文章說明了如何通過JUnit測試來測試一個簡單的控制器。

該代碼是JUnit Testing Spring Service和DAO(帶有內存數據庫)中使用的代碼的變體。 可以從Spring-MVC-JUnit-Testing目錄中的Gihut獲得。

測試配置類

這些與Service和DAO測試所需的相同。

控制者

我們的控制器:

@Controller public class MyController {@Autowiredprivate MyService myService;@RequestMapping(value = '/')public String home(Model model) {return 'index';}@RequestMapping(value = '/roundtrip')public String persistenceStatus(Model model) {MilliTimeItem retr = myService.createAndRetrieve();model.addAttribute('RoundTrip', retr);return 'roundtrip';}}


控制器測試

下面創建一個MockMvc實例來測試模擬的用戶請求:

@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes={ JpaTestConfig.class, TestConfig.class }) public class MyControllerTest {private MockMvc mockMvc;@Beforepublic void setup() {mockMvc = MockMvcBuilders.annotationConfigSetup(JpaTestConfig.class, TestConfig.class).build();}@Testpublic void testHome() throws Exception {mockMvc.perform(get('/')).andExpect(status().isOk()).andExpect(forwardedUrl('WEB-INF/pages/index.jsp'));}@Testpublic void testPersistenceStatus() throws Exception {mockMvc.perform(get('/roundtrip')).andExpect(status().isOk()).andExpect(forwardedUrl('WEB-INF/pages/roundtrip.jsp')).andExpect(model().attributeExists('RoundTrip'));}}

/請求測試返回的狀態以及到JSP頁面的URL映射。 / roundtrip請求確保返回的模型確實包含Roundtrip屬性。

依存關系

Spring MVC測試工件尚無法從maven的中央存儲庫中獲得。 它應該從另一個存儲庫獲得:

<repositories><repository><id>spring.test-mvc</id><url>http://repo.springsource.org/libs-milestone</url></repository></repositories>

所需的依賴項是:

<dependency><groupId>org.springframework</groupId><artifactId>spring-test-mvc</artifactId><version>1.0.0.M1</version><scope>test</scope> </dependency> <dependency><groupId>org.hamcrest</groupId><artifactId>hamcrest-library</artifactId><version>1.3</version><scope>test</scope> </dependency>

更多春天相關的帖子在這里 。

參考: 技術說明博客上的JCG合作伙伴 Jerome Versrynge提供的Spring MVC Controller JUnit Testing 。


翻譯自: https://www.javacodegeeks.com/2012/10/spring-mvc-controller-junit-testing.html

junit 測試mvc

總結

以上是生活随笔為你收集整理的junit 测试mvc_Spring MVC控制器JUnit测试的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。