3、Spring中的测试

时间:2021-04-09 12:49:07   收藏:0   阅读:0

3.1、传统测试存在的问题

1、每个测试都要重新启动spring

2、测试代码在管理spring容器,应该是spring容器在管理测试代码

技术图片

3.2、Spring测试

3.2.1、Spring测试模型图

技术图片

3.2.2、操作步骤

创建一个子工程。(spring-02-test)

1、添加maven依赖。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>spring</artifactId>
        <groupId>com.luke</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>spring-02-test</artifactId>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.10.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

2、编写测试类

package com.luke.test;
import com.luke.pojo.Hello;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
//表示先启动Spring容器,把junit运行在Spring容器中
@RunWith(SpringJUnit4ClassRunner.class)
//表示从哪里加载资源文件
@ContextConfiguration("classpath:applicationContext.xml")
public class TestHello {
    //自动加载
    @Autowired
    BeanFactory beanFactory ;
    @Test
    public void test(){
        Hello hello = beanFactory.getBean("hello", Hello.class);
        hello.sayHello();
    }
}
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!