在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类
@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方法名右键运行即可



