栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring如何使用注解方案测试

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring如何使用注解方案测试

 一、导入测试依赖

 在pom.xml加入junit和spring test

 
        
            org.springframework
            spring-context
            5.3.15
        
        
        
            org.springframework
            spring-test
            5.3.15
        
        
        
        
            junit
            junit
            4.13.2
            test
        
        

二、主程序

 下述都放在了com.t包下
 创建一个Hello接口:

package com.t;


public interface Hello {
    void sayHello();
}

 创建一个HelloImpl实现Hello接口:

package com.t;


import org.springframework.stereotype.Component;

@Component
public class HelloImpl implements Hello{
    @Override
    public void sayHello() {
        System.out.println("Hello Spring Test");
    }
}

 创建一个配置类 ,让上述的Hello HelloImpl放在配置类的路径或子类下。配置类一定要放在某包下,不要放在根路径

package com.t;


import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;


@Configuration
@ComponentScan
public class MyTestConfig {



}
 三、测试

 在test中和配置类路径相同下创建一个类用于测试,我创建了testSpring1类

 1、在测试类加入以下注解:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {需要测试的配置类类名.class})
 2、在测试类里创建一个方法,加上@Test`注解

 如:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {MyTestConfig.class})
public class testSpring1 {

    @Autowired
    Hello hello;

    @Test
    public void test1(){
        hello.sayHello();
    }


}

 选中有@Test方法名右键运行即可

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/984148.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号