java junit 使用注解引入

来源:互联网 发布:象过河软件怎么样 编辑:程序博客网 时间:2024/04/30 02:30

需求:单独测试一个连接,不想全部测试。那么首先想到 单元测试。

方法:

1.新建类:

package com.xx.test;/** *  */import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;import org.springframework.test.context.transaction.TransactionConfiguration;/** * default rollback = true * @author xxxxx * 2014-6-17 下午6:29:32 */@ContextConfiguration(locations="classpath*:spring-*.xml")@TransactionConfigurationpublic abstract class AbstractTransactionalSpringHibernateJunitTestCase extends AbstractTransactionalJUnit4SpringContextTests {}

2. 新建测试类:


package com.xxx.test;import java.io.IOException;import javax.annotation.Resource;import org.jsoup.Jsoup;import org.jsoup.nodes.Document;import com.xx.xx.web.xx.xxx.xxxCtrl;public class Test extends AbstractTransactionalSpringHibernateJunitTestCase {@Resourceprivate XxxCtrl xxxCtrl;@org.junit.Testpublic void testUrl(){String href = "xxxxx";Document doc = getDoucumentByUrl(href);System.out.println(doc);System.out.println(xxxxCtrl);xxxxCtrl.getxxxx(doc, null);//调用里面的方法}public Document getDoucumentByUrl(String url) {Document doc = null;try {doc = Jsoup.connect(url).timeout(5000).header("User-Agent", header).get();} catch (IOException e) {}return doc;}}

3. 如果报错:

java.lang.IllegalStateException: No Scope registered for scope 'request'

解决办法:

设置调用类的注解为:

@org.springframework.stereotype.Component@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)//@Scope("request")
原因 Spring 可以2种调用方法,一个单例,一个多例。

 org.springframework.context.annotation.Scope@Target(value={METHOD, TYPE})@Retention(value=RUNTIME)@DocumentedWhen used as a type-level annotation in conjunction with the Component annotation, indicates the name of a scope to use for instances of the annotated type. When used as a method-level annotation in conjunction with the Bean annotation, indicates the name of a scope to use for the instance returned from the method. In this context, scope means the lifecycle of an instance, such as singleton, prototype, and so forth. Scopes provided out of the box in Spring may be referred to using the SCOPE_* constants available in via ConfigurableBeanFactory and WebApplicationContext interfaces. To register additional custom scopes, see CustomScopeConfigurer.Since:2.5Author:Mark FisherChris BeamsSee Also:ComponentBean




0 0
原创粉丝点击