Shiro 集成測試

2021-06-21 14:08 更新

既然我們已經(jīng)介紹了單元測試設(shè)置,那么讓我們來談?wù)劶蓽y試。集成測試是跨 API 邊界測試實(shí)現(xiàn)。例如,在調(diào)用實(shí)現(xiàn) B 時(shí)測試實(shí)現(xiàn) A 是否有效,而實(shí)現(xiàn) B 則按預(yù)期進(jìn)行測試。

您也可以在 Shiro 中輕松執(zhí)行集成測試。 Shiro 的?SecurityManager?實(shí)例及其包裝的東西(例如 Realms 和 SessionManager 等)都是非常輕量級的 POJO,它們使用的內(nèi)存很少。這意味著您可以為執(zhí)行的每個(gè)測試類創(chuàng)建和拆除?SecurityManager?實(shí)例。當(dāng)您的集成測試運(yùn)行時(shí),它們將使用“真實(shí)” ?SecurityManager?和?Subject?實(shí)例,就像您的應(yīng)用程序?qū)⒃谶\(yùn)行時(shí)使用一樣。

集成測試實(shí)例

下面的示例代碼看起來與上面的單元測試示例幾乎相同,但是三步過程略有不同:

  • 現(xiàn)在有一個(gè)步驟“ 0”,它設(shè)置了一個(gè)“真實(shí)的” SecurityManager 實(shí)例。
  • 現(xiàn)在,第 1 步使用?Subject.Builder?構(gòu)造一個(gè)“真實(shí)”主題實(shí)例,并將其綁定到線程。

線程綁定和取消綁定(步驟 2 和 3)的功能與單元測試示例相同。

import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;

public class ExampleShiroIntegrationTest extends AbstractShiroTest {

    @BeforeClass
    public static void beforeClass() {
        //0.  Build and set the SecurityManager used to build Subject instances used in your tests
        //    This typically only needs to be done once per class if your shiro.ini doesn't change,
        //    otherwise, you'll need to do this logic in each test that is different
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:test.shiro.ini");
        setSecurityManager(factory.getInstance());
    }

    @Test
    public void testSimple() {
        //1.  Build the Subject instance for the test to run:
        Subject subjectUnderTest = new Subject.Builder(getSecurityManager()).buildSubject();

        //2. Bind the subject to the current thread:
        setSubject(subjectUnderTest);

        //perform test logic here.  Any call to
        //SecurityUtils.getSubject() directly (or nested in the
        //call stack) will work properly.
    }

    @AfterClass
    public void tearDownSubject() {
        //3. Unbind the subject from the current thread:
        clearSubject();
    }
}

如您所見,實(shí)例?SecurityManager?的具體實(shí)現(xiàn)已實(shí)例化,并可以通過?setSecurityManager?方法在其余的測試中訪問。然后,稍后通過?getSecurityManager()?方法使用?Subject.Builder?時(shí),測試方法可以使用此?SecurityManager?。

還要注意,?SecurityManager?實(shí)例是通過?@BeforeClass?設(shè)置方法設(shè)置的,這對于大多數(shù)測試類來說是相當(dāng)普遍的做法。但是,如果愿意,您可以創(chuàng)建一個(gè)新的?SecurityManager?實(shí)例,并通過任何測試方法隨時(shí)通過?setSecurityManager?對其進(jìn)行設(shè)置-例如,您可以根據(jù)測試要求引用兩個(gè)不同的.ini 文件來構(gòu)建新的?SecurityManager?。

最后,就像單元測試示例一樣,?AbstractShiroTest?超級類將通過其?@AfterClass tearDownShiro()?方法清除所有 Shiro 構(gòu)件(所有剩余的?SecurityManager?和?Subject?實(shí)例),以確保線程“干凈”以供下一個(gè)測試類運(yùn)行。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號