簡體   English   中英

由於公共私人領域的矛盾,使用Junit @Rule的CdiUnit測試是不可能的

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

以下代碼段足以重現我的問題:

  • 我將thrown屬性設置為public並獲取錯誤org.jboss.weld.exceptions.DefinitionException: WELD-000075: Normal scoped managed bean implementation class has a public field
  • 或者我刪除public修飾符並獲取錯誤org.junit.internal.runners.rules.ValidationError: The @Rule 'thrown' must be public.
  • 我還試圖讓public修飾符到位並在類上添加@Dependent注釋作用域,但是得到錯誤org.jboss.weld.exceptions.DefinitionException: WELD-000046: At most one scope may be specified on [EnhancedAnnotatedTypeImpl] public @Dependent @ApplicationScoped @RunWith

我刪除了所有不必要的代碼,但這是一個非常復雜的單元測試,通過CDI進行模擬,服務注入,並且一些測試方法預計會拋出異常。

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() {

    }
}

所以我的問題是,一方面Weld希望所有字段都不公開,因為否則它將無法代理該類,另一方面,JUnit希望規則字段是公共的,因為它使用反射來訪問它們由於安全管理器處於活動狀態,因此不希望使用setAccessible(true)方法。 如何處理這個悖論?

注意:我也發現了對這個答案的暗示評論,並說明了這一點

您還可以使用@Rule注釋方法,這樣可以避免此問題

但我找不到任何關於方法的@Rule注釋的junit測試的例子,我打算問一個單獨的問題。

我發現了如何解決這個問題。 為了將來參考,這是一個有用的片段,希望這將有助於其他人。

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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM