【Spring學習】在Spring+Maven環境中使用Junit Test


在Spring+Maven環境中使用Junit Test

前言

以前我是很討厭寫測試代碼的,總覺得測試用例是測試人員寫的,現在想想自己真是Too yuong too simple,接觸開發多了之后發現在開發中需要不斷通過測試來發現某些路子的可行性,如果不寫測試代碼直接一股腦寫下去,很可能代碼寫完了一運行發現到處都是坑。下面總結一下在SpringMVC和SpringBoot環境中的單元測試(Junit Test)的搭建和使用。

SpringMVC中的單元測試

加入依賴包

首先需要在pom.xml中加入junit依賴,其中scope限定了junit包的使用范圍是test環境:

<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>

下圖是我在IntelliJ IDEA中的項目包的架構,我們需要在test包下進行單元測試編寫。

編寫測試基類

由於我們在單元測試中可能需要對SpringMVC中的service、dao層進行調用,但是我們又知道在Spring中對象的創建時交給容器的,不需要我們手動創建、實例化對象,那么就需要引入配置文件進行上下文的初始化。所以為了避免每次寫一個測試類都要進行相關的配置操作,我們直接寫一個父類,然后每個測試類繼承該類就可以達到簡化的目的了。

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() {
        
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM