springMvc+maven中整合junit

junit在运行时候需要用到log4j,但是log4j的配置文件在启动的时候需要加载得到,这就要求一开始能够找到这个log4j.properties文件,在junit中默认是从src文件目录寻找到log4j.properties文件,但是如果log4j.properties文件不在src目录下则会报如下错误:

Cannot Initialize log4j 
log4j:WARN No appenders could be found for logger `(org.springframework.test.context.junit4.SpringJUnit4ClassRunner).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

一般log4j.properties文件都会放在特定的目录下,为了查找到log4j.properties文件则可以采用如下办法:
创建一类JUnit4ClassRunner该类继承SpringJUnit4ClassRunner

public class JUnit4ClassRunner extends SpringJUnit4ClassRunner {
     static {  
            try { 
                Log4jConfigurer.initLogging("classpath:propertis/log4j.properties");    //指定log4j.properties文件位置
            } catch (FileNotFoundException ex) {  
                System.err.println("Cannot Initialize log4j");  
            }  
    }  
    public JUnit4ClassRunner(Class<?> clazz) throws InitializationError {
        super(clazz);
    }
}

然后测试类如下配置:

@RunWith(JUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:config/spring-context.xml"})  
public class TestJava {
    private Logger logger = Logger.getLogger(TestJava.class);

    @Autowired
    private TestServiceI testService;

    @Test
    public void testFindAllUsers() {
        logger.info(testService.findAllUsers().size());
    }
}

注意:如果spring版本和junit不兼容则会报如下错误:

java.lang.NoClassDefFoundError: org/junit/runners/model/MultipleFailureException
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.withAfterClasses
(SpringJUnit4ClassRunner.java:188)
    at org.junit.runners.ParentRunner.classBlock(ParentRunner.java:145)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:235)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
         Caused by: java.lang.ClassNotFoundException: org.junit.runners.model.MultipleFailureException
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 10 more

出现这种情况则可以尝试下换个版本的junit

展开阅读全文

没有更多推荐了,返回首页