java-junit4+spring 集成单元测试

来源:互联网 发布:药品进销存软件 编辑:程序博客网 时间:2024/05/21 19:29
java-junit4+spring 集成单元测试


一、吐槽:版本兼容坑死人 !!!
有问题的版本搭配:junit 4.8.3+ spring 4.3.7,只要测试类上加了 @RunWith(SpringJUnit4ClassRunner.class)  注解
运行就报:
No tests found matching [{ExactMatcher:fDisplayName=xxxx], {ExactMatcher:fDisplayName=xxxx


查到的解决办法:第 2 点解决了我的问题,测试方法需要 static 修饰????
1.测试方法上没有@Test
2.测试方法 static 修饰
3.测试方法有返回值
4.测试方法存在参数


这个问题改了,继续报错。。。。 最后想是不是版本兼容问题呢。
看看 SpringJUnit4ClassRunner 类的注释,如下:写着需要 JUnit 4.12 or higher (我都 4.8.3 了那道不支持???)
NOTE: As of Spring Framework 4.3, this class requires JUnit 4.12 or higher.


算了还是改为低版本吧:把 maven 引用改为 JUnit 4.12,编译运行 .... 居然 ok 了 !!!!


二、junit4+spring 集成单元测试,测试用例
环境:
JUnit 4.12
spring 4.3.8.RELEASE


2 需要两个文件
2.1.新建一个测试类
2.2.平级建一个spring.xml 




2.1.新建一个测试类
package com.demo;import static org.junit.Assert.*;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;import com.fasterxml.jackson.annotation.JsonFormat.Value;import me.grass.coder.Debug;/** ** @author xxj */@RunWith(SpringJUnit4ClassRunner.class)  @ContextConfiguration(locations={"classpath:com/demo/spring.xml"})public class myTest {@AutowiredBeanTest _bt;@Testpublic void testSpring() {_bt.getName();Debug.print(myTest.class.getResource("/"));assertTrue(1==1);}public static class BeanTest{public void getName(){Debug.print(BeanTest.class.getName());}}}






2.2.平级建一个spring.xml 
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://code.alibabatech.com/schema/dubbo          http://code.alibabatech.com/schema/dubbo/dubbo.xsd">    <!-- 注册一个 bean -->    <bean id="beanTest" class="com.demo.myTest.BeanTest" /> </beans>



3.运行 testSpring() 测试方法,测试成功!


4.注意 locations={"classpath:com/demo/spring.xml" 中的 classpath 占位符 
根据 Java Biuld Path 配置的 output folder 不同, classpath 占位符定位的目录也不一样!!!
测试一般指向:target/test-classes
0 0