CdiUnit test with Junit @Rule is impossible because of a public private field paradox

余生长醉 提交于 2019-12-06 01:45:50

问题


The following snippet is enough to reproduce my problem:

  • Either I set the thrown attribute public and get the error org.jboss.weld.exceptions.DefinitionException: WELD-000075: Normal scoped managed bean implementation class has a public field
  • Or I remove the public modifier and get the error org.junit.internal.runners.rules.ValidationError: The @Rule 'thrown' must be public.
  • I also tried to let the public modifier in place and to add the @Dependent annotation scope on the class, but got error org.jboss.weld.exceptions.DefinitionException: WELD-000046: At most one scope may be specified on [EnhancedAnnotatedTypeImpl] public @Dependent @ApplicationScoped @RunWith

I stripped out all unnecessary code, but this is quite a complex unit test with mock, service injection through CDI and some test methods thar are expected to throw an exception.

import org.jglue.cdiunit.CdiRunner;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;

@RunWith(CdiRunner.class)
public class FooBarTest {

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void test() {

    }
}

So my problem is that on one hand Weld wants all fields to not be public because it will not be able to proxify the class otherwise, and on the other hand, JUnit want Rule fields to be public because it is using reflection to access them and does not want to use the setAccessible(true) method because of the cases where the security manager is active. How to deal with that paradox?

NB: I also found a hint comments to this answer, stating that

You can also annotate a method with @Rule, so this would avoid the problem

But I could not found any example of junit test with a @Rule annotation on a method, I plan to ask a separate question about this.


回答1:


I found out how to solve the problem. For future reference, here is a snippet that works, hope this will help other people.

import org.jglue.cdiunit.CdiRunner;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;


@RunWith(CdiRunner.class)
public class FooBarTest {

    private ExpectedException thrown = ExpectedException.none();

    @Rule
    public ExpectedException getThrown() {
        return thrown;
    }

    @Test
    public void test() {
        thrown.expect(ArithmeticException.class);
        int i = 1 / 0;
    }
}


来源:https://stackoverflow.com/questions/40176003/cdiunit-test-with-junit-rule-is-impossible-because-of-a-public-private-field-pa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!