I have a set of junit tests for my project. When I run them with mvn test they run fine and pass.
However, when I ran them with mvn cobertura:cobertura, they failed with the following error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.anorakgirl.MyTest': Autowiring of fields failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.anorakgirl.MyService com.anorakgirl.MyTest.myService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.anorakgirl.MyService] is defined: Unsatisfied dependency of type [class com.anorakgirl.MyService]: expected at least 1 matching bean
After some googling, this is the problem. The ServiceObject was annotated with @Autowire. Spring autowires by type. I have only one class of type ‘com.anorakgirl.MyService’. So when run with junit this works fine. However, cobertura changes the type of the MyService class during Instrumentation, so Spring no longer recognises it as type MyService, and so cannot Autowire.
There are two possible answers:
The easy answer (what I did)
In your test application context add the line:
The other answer (what I read about)
Make sure the classes that you want to autowire all implement interfaces. Then autowire the interface rather than the implementation. The Cobertura class will still implement the same interface and therefore can still be autowired.
I didn’t try this as the service classes do not have interfaces and I haven’t time to add them!