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

发布了81 篇原创文章 · 获赞 9 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Alone_in_/article/details/103086217