Suppose I have a stateless bean:

@Stateless(name = "fooBean")
@LocalBean
public class Foo {
...
}

I want to create a mock for testing (with CDI)

@Alternative @Specializes
public class FooMock extends Foo {
...
}

I register the mock in beans.xml, and when I run it with OpenEJB, I get the following exception:

...
Caused by: javax.naming.NameAlreadyBoundException:
openejb/Deployment/fooBean/com.company.Foo!LocalBeanHome

It seems to me that the container creates an interface for Foo because of @LocalBean which is now implemented by FooMock, too. OpenEJB tries to bind the two classes with the with same name of same generated interface, which is not possible.

Of course, if I comment out @Stateless and @LocalBean in Foo class, it works fine.

Any idea or suggestion to solve this?

有帮助吗?

解决方案

Rather do something like:

@Local
public interface Foo {
...
}

@Stateless
public class FooBean implements Foo {
...
}

Then make your mock.

@Alternative
@Specializes
public class FooMock implements Foo {
...
}

However I recommend you take a look at Arquillian it will make your testing so much easier without the need for @Alternative and special beans.xml entries for tests.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top