spring入门级错误:Juint测试中的错误

来源:互联网 发布:朗诵录音软件 编辑:程序博客网 时间:2024/05/22 12:54

将经典的Hello World程序改成spring版,对输出“Hello World”的方法进行Junit测试时,出现了一个这样的Error:


org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [beans.xml]; nested exception is java.io.FileNotFoundException:class path resource [beans.xml] cannot be opened because it does not exist


看最后的错误原因可知:找不到beans.xml,这个原因分为如下可能:

1.创建spring容器时,类路径填写错误使用正确的路径书写规范)

2.配置文件名书写错误要仔细核对配置文件名称这是我犯的粗心错误,写成了bean.xml


Junit测试除了spring的包还需要

1.commoms-logging.jar

2.Library中加入Junit相关包:项目右键--->Build Path--->Add Libraries--->Junit--->点next选择Junit版本--->finsh


这里是主要的代码:

beans.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:p="http://www.springframework.org/schema/p"    xmlns:aop="http://springframework.org/schema/aop"    xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd        http://www.springframework.org/schema/aop        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">    <bean id="helloworld" class="com.jike.helloworld.HelloWorld">    </bean></beans>


HelloWorld.java(待测试类)

package com.jike.helloworld;public class HelloWorld {public void say(){System.out.println("Hello World");}}

HelloWorldTest.java(测试类)

package com.jike.helloworldTest;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.jike.helloworld.HelloWorld;//测试用例public class HelloWorldTest {        //待测试的方法,注意:@Test不要删除       @Testpublic void testSay() {ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");HelloWorld hello = (HelloWorld) context.getBean("helloworld");hello.say();}}

这里待测试类创建:相应的package下---->new--->Junit Test Case

                                 测试时只选中要测试方法名即可,右键--->run---->Junit Test


结果如下:

五月 16, 2017 6:46:00 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@6073f712: startup date [Tue May 16 18:46:00 CST 2017]; root of context hierarchy五月 16, 2017 6:46:00 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions信息: Loading XML bean definitions from class path resource [bean.xml]五月 16, 2017 6:46:00 下午 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@239963d8: defining beans [helloworld]; root of factory hierarchyHello World




原创粉丝点击