Spring框架下的单元测试
一、使用spring中对Junit框架的整合功能
除了junit4和spring的jar包,还需要spring-test.jar。引入如下依赖:
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.2.0.RELEASE</version> </dependency>
@ContextConfiguration需要配上spring的配置文件,这样就可以在测试类中使用注解简单的注入需要的bean了。简单高效。
@ContextConfiguration({"classpath:applicationContext.xml"}) @RunWith(SpringJUnit4ClassRunner.class) public class TestCase { @Autowired private TopProducer topProducer; private String topic = "lilixin"; @Test public void testCase(){ System.out.println("##############################"); topProducer.send(topic,"this ia a kafka test msg"); System.out.println("##############################"); } }
二、手动加载spring的配置文件,并启动spring容器
public class TestCase { public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); TopProducer topProducer = (TopProducer)context.getBean("topProducer"); topProducer.send("lilixin", "this ia a kafka test msg"); } }
运行这两种测试方法,EclipseIDE下都只需要Ctrl+F11。