Spring Test Framework and annotation-based autowiring Problem - unit-testing

I would like to use two different implementations for a DAO with Spring's testframework.
src.main.java
.businessobjects
\-User.java
.dao
\-IUserDAO.java
.daojpa
\-UserDAO.java
.daohibernate
\-UserDAO.java
The spring testcase in:
src.test.java.base:
package base;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("/hibernate-beans.xml")
#Transactional
public abstract class SpringTestCase {}
And here is the error:
Caused by:
java.lang.IllegalStateException:
Annotation-specified bean name
'userDAO' for bean class
[jpadao.UserDAO]
conflicts with existing,
non-compatible bean definition of same
name and class
[jpaadao.UserDAO]
I have already tried to override the autowiring by using qualifiers, e.g.:
<bean class="jpaadao.UserDAO">
<qualifier value="jpaa"/>
</bean>
<bean class="jpadao.UserDAO">
<qualifier value="jpa"/>
</bean>
And then in the testcase wiring with
#Autowired
#Qualifier("jpa")
private IUserDAO userDAO;
but the error persists.
Two questions:
How can this problem be solved with annotation based configuration?
How can I run tests WITHOUT autowiring and annotations?

You're using beans without names so that Spring will try to come up with a name, this name may be based on the #Component annotation that you presumably have on your class, but it could also be the camelcased version of your the unqualified class name of your bean (in both cases they would turn out equal and that causes Spring to object).
Also, it seems you are mixing component scanning and xml configuration in a way that looks a bit odd to me.
There are many ways out of this, but most cleanly you would use only a single bean implementing the contract you're trying to fullfil. If you do need different implementations you should give them different and more discriptive names:
<bean id="jpaUserRepository" class="..JpaUserRepository"/>
This will give you more useful logging, even if the bean names are never used because you rely on auto wiring.

Do what Iwein suggested: name your implementation classes better (e.g., HibernateUserDao and JpaUserDao); or specify a unique bean name via the #Component or #Repository annotation on your UserDAO implementation classes.
You cannot currently run tests without autowiring. See this JIRA issue for details: https://jira.springsource.org/browse/SPR-6050
Regards,
Sam (author of the Spring TestContext Framework)
p.s. No, the problem you are facing is not related to SPR-4524.

You can try injecting the dependency by-name using the #Resource annotation. You will have to give names (ids) to the beans or use the default, which is the uncapitalized unqualified class name.

I've got it up and running now! However, I don't believe this is best practice. I simply excluded the path of the unwanted DAOs by writing into appContext.xml:
<context:component-scan base-package="test">
<context:exclude-filter type="regex" expression="test\.daohibernate.*"></context:exclude-filter>
</context:component-scan>
Any suggestions? Could this issue be related to http://jira.springframework.org/browse/SPR-4524 ?

Related

DryIoc Registry Class

I Like StructureMap's registry feature for helping me to group IOC Registrations together:
http://structuremap.github.io/registration/registry-dsl/
I'm using DryIOC as my Container - its working great - but I'm in a situation where my registry class needs re-organising. Is there an equivalent Registry feature in DryIOC?
As I understood the Registry feature is similar to Autofac Module, plus some syntax sugar.
Basically it allows to logically group registrations, simplifying the control.
If I am right, here is the example of how to group DryIoc registrations in kinda module, directly comparing with Autofac feature: https://bitbucket.org/dadhi/dryioc/wiki/FaqAutofacMigration#markdown-header-modules
The difference from StructureMap is explicit use of injected IRegistrator, instead of hiding it in the base class.

How to mock Kotlin class (final) using PowerMock?

I wish to know how can I mock kotlin final class with PowerMock so I can test it. I followed guide for testing Java final classes but I still got this error
Cannot subclass final class
Is there any way to do that?
With Mockito 2.1.0+ you can mock final classess as well. This feature is optional, so you have to enable it by adding Mockito extension.
To do this:
Create a file named org.mockito.plugins.MockMaker and place it under the resources/mockito-extensions directory in your test folder.
The file contains a single line: mock-maker-inline
You can find more information in Mockito documentation.
Just create interfaces for your classes. Than you can simply mock your classes using interface.

JAX/WS wsgen is not generating

I have a problem like this ; Could you please help me if you know the reason?
I m trying to generate jaxb classes for input and out types using wsgen command line utility.
The print screen you posted (and #home's comment is spot on - you should add the stacktrace not a print screen) tells you the problem.
#javax.jws.WebService annotated classes that do not belong to a package must have the #javax.jws.WebService.targetNamespace element.
You don't specify a target namespace and wsgen can't infer one because you classes are in the default package. Having classes in the default package is a frown upon practice. Put your classes under a package and try again or have the WebService.targetNamespace element set up which also gives you more control on what the tool generates.
#javax.jws.WebService the annotated classe who implements Web Service Business interface, must have a no-argument constructor otherwise wsGen tool gets such error.
Reference: Creating a Simple Web Service and Client with JAX-WS

#ManyToOne in multiple jars with Glassfish/EclipseLink

I've got two jars, dog.jar and person.jar, both packaged as ejb modules within a single ear. Dog.java is an Entity that references another Entity Person.java via a OneToMany mapping on an "owner" field. Each jar has its own persistence.xml, which reference a common persistence unit, but each persistence.xml only contains the classes contained in that jar.
Upon startup, Glassfish complains:
Exception Description: [class com.example.dog.entities.Dog] uses a non-entity [class com.example.person.entities.Person] as target entity in the relationship attribute [field owner].
It seems to work if I add the Person class to the dog jar's persistence.xml, but I don't like that at all. The Person class is already defined in the persistence.xml of the person.jar, which is in same named persistence unit, in the same ear, so it should find it at runtime! I don't want to repeat myself.
Plus, I use the handy Eclipse JPA tooling to auto-sycnhronize the class names in the persistence.xml, and when I do that it only finds the Dog.java when I run it on dog's persistence.xml. So I don't want to have to hunt down all references and manually add them to persistence.xml and worry about them getting blown away when I resynchronize.
Also I made sure I put the person ejb module before the dog ejb module in the application.xml.
This is my first foray into JPA and Java EE, so I could be doing something wrong... I drank the koolaid by reading books and articles but nobody seems to ever show a good mutli-module enterprise example...

How to override the behavior of Spring #Autowired

A little background:
I am Using Spring 2.5, and specifically Spring IOC and annotations.
I am using #Autowired in my code (the Autowiring is done by type)
and use #Component for exposing classes to the automatic wiring.
The situation described below arose while I tried to test my code.
Now to the problem:
Note: I use a different Spring Context for the Test environment.
I have a class FOO which is #Autowired but in the test context I want to use a different class of the same type MockFoo (extends FOO).
The Spring setup of course fails automatically due to multiple options for the Dependency Injection of the FOO class (both FOO and MockFOO comply to the Type check).
I am looking for a way to inject the test bean instead of the original bean.
I expected Spring to allow using the Context configuration file to override a bean injection or to order Spring not to autowire a specific bean.
BUT
All these options seem to exists only for the beans which were originally defined in the Spring Context Configuration file.
Use ReflectionTestUtils to manually set the Mock in place of the autowired dependency (for that purpose your mock must not be spring managed, so that no ambiguity exists)
I know this question is quite old but a I think an answer might still be useful for others.
Since you probably do not want to mix both Foo and MockFoo within your context, I would suggest to remove Foo from the component-scanning. This could be done for example by specifying include/exclude filters on the <context:component-scan>.
However if you are implementing unit tests, I would rather suggest not using a Spring context and just implementing "pure" unit tests by injecting mock-ups of the dependencies manually, so that you are only testing a single class. This can be achieved more easily by using a mocking framework like Mockito.
I agree with Didier. Here is an example of how you can exclude the implementations that you want to mock in your test application context.
<context:component-scan base-package="com.company" >
<context:exclude-filter type="regex" expression="com\.abc\.service\.XDaoImpl"/>
</context:component-scan>
Include this application context in your test as follows :
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations={"classpath:/applicationContext-test.xml"})
public class MyTest {....}