简体   繁体   English

@Autowired注释无法在JUnit类中注入bean

[英]@Autowired annotation not able to inject bean in JUnit class

my test class: 我的测试课:

public class myTest extends TestCase{
@Autowired
BeanClass beanObject
public void beanTest()
{
Classdata data = beanObject.getMethod();
}
}

I am getting a null pointer exception at line: 我在行上得到一个空指针异常:

Classdata data = beanObject.getMethod();

the beanObject.getMethod(); beanObject.getMethod(); precisely gives nullpointer exception 精确给出nullpointer异常

How should i make possible the autowiring of the field beanObject in my Junit class so that i can use the methods from the "BeanClass" class? 如何使Junit类中的beanObject字段自动装配成为可能,以便可以使用“ BeanClass”类中的方法?


Copied from Comments: 从评论中复制:

in plain terms.. beanClass is an interface which has certain methods.. i have tagged that beanClass with @Service("beanObject") annotation..that banClass is implemented by beanClassImpl class which has the method implementations.. i need to use those implementations in my testClass to get the data to be compared.. for that i am doing @Autowired beanClass beanObject in my testClass.. mi going terribly wrong somewhere? 用简单的术语来说.. beanClass是具有某些方法的接口..我用@Service("beanObject")批注标记了该beanClass。.banClass由具有方法实现的beanClassImpl类实现。.我需要使用那些方法我的testClass中的实现以获取要比较的数据..为此,我在我的testClass中执行@Autowired beanClass beanObject .. mi某处发生了严重错误?

You probably need to decorate your tests with these annotations: 您可能需要使用以下注释来修饰测试:

@ContextConfiguration(locations = {/* your xml locations here */})
@RunWith(SpringJUnit4ClassRunner.class)

Or, if you use JUnit 3.x, you should extend from AbstractJUnit38SpringContextTests 或者,如果您使用JUnit 3.x,则应从AbstractJUnit38SpringContextTests扩展

Reference: TestContext support classes 参考: TestContext支持类

Update: The problem seems to be that the context file can't be found (see discussion in comments). 更新:问题似乎是找不到上下文文件(请参阅注释中的讨论)。

in plain terms.. beanClass is an interface which has certain methods.. i have tagged that beanClass with @Service("beanObject") annotation..that banClass is implemented by beanClassImpl class which has the method implementations.. i need to use those implementations in my testClass to get the data to be compared.. for that i am doing @Autowired beanClass beanObject in my testClass.. mi going terribly wrong somewhere? 用简单的术语来说.. beanClass是具有某些方法的接口..我用@Service(“ beanObject”)批注标记了该beanClass。.banClass由具有方法实现的beanClassImpl类实现。.我需要使用那些方法我的testClass中的实现以获取要比较的数据..为此,我在我的testClass中执行@Autowired beanClass beanObject .. mi某处发生了严重错误?

More Updates: 更多更新:

Don't annotate the interface, annotate the implementing class. 不要注释接口,不要注释实现类。 Annotating the interface with @Service has no effect! @Service注释接口无效!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM