我使用Eclipse,Maven,Spring,Hibernate和Struts开发了一个关于Eclipse的项目.我们有2个应用程序:
包含所有bean(服务)和Web以及操作视图等的核心.
我对服务进行了JUnit测试,并决定尝试对操作进行一些测试.这是我要执行的操作的一个示例:
行动
@Action(value = "/modif/register")
@ResultPath("...")
public class A{
@Autowired
private ExampleService exampleService;
public String execute(){
Example = exampleService.find(...);
...
...
}
}
测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class)
public class ATest extends StrutsSpringTestCase {
@Before
public void setUp(){
try {
super.setUp();
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testExecute() throws Exception{
request.setParameter(...);
//filling up the request
ActionProxy proxy = super.getActionProxy("/modif/register");
A register = (A) proxy.getAction();
String result = proxy.execute();
}
}
设定档
@Configuration
@ComponentScan(basePackages = {"web","core"} )
public class Config {
//configuration
}
每次尝试启动此测试时,都会在ActionProxy proxy = super.getActionProxy(“ / modif / register”);的行上收到此错误.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘web.action.A’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public core.service.ExampleService web.action.A.exampleService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [core.service.ExampleService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
无论我调用哪个夹心豆,我都会遇到此错误.它们都可以在核心应用程序中运行,也可以在我的Action中运行,我什至可以在测试中直接调用它们而不会出现任何错误,但是每次尝试启动测试时都会失败.
有谁知道有什么可能引发此异常?
解决方法:
因为您的测试上下文中没有ExampleService bean,所以引发BeanCreationException.之所以会发生这种情况,是因为没有为操作的测试加载正确的上下文.
由于您使用的是JUnit 4,因此应该扩展StrutsSpringJUnit4TestCase类而不是StrutsSpringTestCase,该类将在@RunWith(SpringJUnit4ClassRunner.class)和上下文加载中发挥更好的作用.