Spring中的單元測試
需要引入依賴
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<!-- 表示開發的時候引入,發布的時候不會加載此包 -->
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.0.2.RELEASE</version>
<scope>test</scope>
</dependency>
你也可以編寫基類,然后具體業務類繼承,你也可以直接懟,這里我就規范一下,先寫基類
BaseTest.java如下,其中@Before和@After注解都是junit提供的,其含義寫在代碼的注釋中了:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:spring-mvc.xml","classpath:spring-mybatis.xml"}) public class BaseTest { @Before public void init() { //在運行測試之前的業務代碼 } @After public void after() { //在測試完成之后的業務代碼 } }
編寫具體測試類
寫完測試基類后,就可以開始寫真正的單元測試了,下面是一個簡單的示例:
public class HelloTest extends BaseTest { @Test public void getTicketInfo() { System.out.println("hello"); }
我們可以看到在IDEA中可以直接對單元測試的某個方法進行運行,不用編譯項目和啟動服務器就可以達到對業務代碼的功能測試,可見其便利程度。
SpringBoot中的單元測試
SpringBoot中使用Junit和SpringMVC基本類似,只需要改動一些配置即可。
加入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<version>1.5.2.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.7.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
編寫測試基類
@RunWith(SpringRunner.class) @SpringBootTest public class BaseTest { @Before public void init() { } @After public void after() { } }
