使用maven對項目進行junit的單元測試


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

你也可以編寫基類,然后具體業務類繼承,你也可以直接懟,這里我就規范一下,先寫基類

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() {
        //在測試完成之后的業務代碼
    }
}
View Code

編寫具體測試類

寫完測試基類后,就可以開始寫真正的單元測試了,下面是一個簡單的示例:

public class HelloTest extends BaseTest {

    @Test
    public void getTicketInfo() {
        System.out.println("hello");
}
View Code

我們可以看到在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>
View Code

 

編寫測試基類

@RunWith(SpringRunner.class)
@SpringBootTest
public class BaseTest {
    @Before
    public void init() {
        
    }
    
    @After
    public void after() {
        
    }
}
View Code

 


免責聲明!

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



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