Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weld (CDI): where do I put my test-only beans.xml that configures <alternatives>?

My webapp has a non-empty production beans.xml under src/main/resources/META-INF. Now, for my tests, I need to swap out 1 bean with an alternative.

Where do I put this test beans.xml which contains just this and nothing more?

<?xml version="1.0" encoding="UTF-8"?>
<beans ...>
  <alternatives>
    <class>...MyTestReplacement</class>
  </alternatives>
</beans>

I tried under src/test/resources/META-INF but that is ignored. I am using arquillian and my test classpath is added to the ShrinkWrap.

like image 669
Geoffrey De Smet Avatar asked Oct 20 '25 06:10

Geoffrey De Smet


2 Answers

Even though it's already accepted, ill post you the solution I found. I had the same problem, and using @Specializes was no option for me, because I had many mocks with several methods, thus create for each one a class was a bit overkill....

So in my test I have a ResourceMock:

@Produces
@Alternative
public IResource createResource() {
    Resource resource = mock(Resource.class);
    when(resource.getLocalized(anyString())).then(AdditionalAnswers.returnsFirstArg());
    return resource;
}

With the following ShrinkWrap I was able to load those @Alternative bean only during the test: (no beans.xml in the test dir needed!)

return ShrinkWrap
            .create(JavaArchive.class)
            .addPackages(true, "some.package.with.classes")
            .addAsManifestResource(
                    new StringAsset(
                            "<alternatives><class>my.testclass.with.alternatives</class></alternatives>"),
                    "beans.xml");

And that's it.

like image 70
bravenoob Avatar answered Oct 21 '25 21:10

bravenoob


Don't use @Alternative, but use @Specializes. Just put the @Specializes bean only in your test classpath and it will automatically replace the real bean. No need to mess around with beans.xml.

like image 35
Geoffrey De Smet Avatar answered Oct 21 '25 21:10

Geoffrey De Smet