SSM框架如何進行單元測試

編寫賬號查詢的測試類

一、項目基礎

 首先這個我的項目結構,登錄註冊功能都寫的差不多了。現在開始進行單元測試。

二、編寫過程

(1)檢查項目中是否有 junit 包和 spring-test 包,Maven項目的話看看pom.xml 文件中有沒有這兩塊。

<dependency>
	<groupId>junit</groupId>
	<artifactId>junit</artifactId>
	<version>3.8.1</version>
	<scope>test</scope>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-test</artifactId>
	<version>${spring.version}</version>
</dependency>

@Test 的時候也會提醒導入。

(2)編寫父類

package com.lph.ssm.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration("src/main/resources")
@ContextConfiguration(locations = { "classpath:spring/spring-mvc.xml", "classpath:spring/spring-mybatis.xml" })
public class BaseTest {

    @Test
    public void test() {
    }
}
//spring-mvc.xml: 是前端控制器的配置文件,主要是前臺展示的各種資源向後臺請求的配置,包括各種靜態資源的請求,攔截等配置。

//spring-mybatis.xml: 是後端 spring的配置文件,當然其中還可以引用包括各種其他配置文件,如dataSource.xml,mybatis.xml等。
(3)編寫測試類
其他測試類,只要繼承BaseTest類,然後,在裏面直接只用@Test註解寫測試方法即可,如:
package com.lph.ssm.test;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.lph.ssm.pojo.LoginInfos;
import com.lph.ssm.service.LoginService;

public class LoginTest extends BaseTest {

    @Autowired
    private LoginService loginService;

    @Test
    public void load() {
        LoginInfos loginInfos = loginService.getLoginInfos("13416811314", "123");
        if (loginInfos != null) {
            System.out.println("loginInfos.getUserName()=" + loginInfos.getUserName() + ", loginInfos.getPassword()="
                    + loginInfos.getPassword());
        } else {
            System.out.println("不好意思,賬戶未註冊!");
        }
    }
}

 

參考文章:

https://www.cnblogs.com/libin6505/p/8383837.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章