天天看點

在Spring MVC Web應用程式中添加社交登入:單元測試

Spring Social 1.0具有spring-social-test子產品,該子產品為測試Connect實作和API綁定提供支援。 該子產品已從Spring Social 1.1.0中删除,并由 Spring MVC Test架構替換。

問題在于,實際上沒有有關為使用Spring Social 1.1.0的應用程式編寫單元測試的資訊。

這篇部落格文章解決了這個問題 。

在此部落格文章中,我們将學習如何為示例應用程式的注冊功能編寫單元測試,該功能是在本Spring Social教程的前面部分中建立的。

注意:如果您尚未閱讀Spring Social教程的先前部分,建議您在閱讀此部落格文章之前先閱讀它們。 以下描述了此部落格文章的前提條件:

  • 在Spring MVC Web應用程式中添加社交登入:配置描述了如何配置示例應用程式的應用程式上下文。
  • 在Spring MVC Web應用程式中添加社交登入:注冊和登入介紹了如何向示例應用程式添加注冊和登入功能。
  • Spring MVC測試教程描述了如何使用Spring MVC Test架構編寫單元測試和內建測試。

讓我們從發現如何使用Maven獲得所需的測試标準開始。

使用Maven擷取所需的依賴關系

我們可以通過在POM檔案中聲明以下依賴關系來獲得所需的測試依賴關系:

  • FEST聲明(1.4版)。 FEST-Assert是一個提供流暢接口以編寫斷言的庫。
  • hamcrest-all(1.4版)。 我們使用Hamcrest比對器在單元測試中編寫斷言。
  • JUnit (版本4.11)。 我們還需要排除hamcrest-core,因為我們已經添加了hamcrest-all依賴項。
  • 全模拟(版本1.9.5)。 我們使用Mockito作為我們的模拟庫。
  • Catch-Exception(版本1.2.0)。 catch-exception庫可幫助我們在不終止測試方法執行的情況下捕獲異常,并使捕獲的異常可用于進一步分析。 由于我們已經添加了“ mockito-all”依賴性,是以需要排除“ mockito-core”依賴性。
  • Spring測試(版本3.2.4.RELEASE)。 Spring Test Framework是一個架構,可以為基于Spring的應用程式編寫測試。

pom.xml檔案的相關部分如下所示:

<dependency>
    <groupId>org.easytesting</groupId>
    <artifactId>fest-assert</artifactId>
    <version>1.4</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-all</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <artifactId>hamcrest-core</artifactId>
            <groupId>org.hamcrest</groupId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-all</artifactId>
    <version>1.9.5</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>com.googlecode.catch-exception</groupId>
    <artifactId>catch-exception</artifactId>
    <version>1.2.0</version>
    <exclusions>
        <exclusion>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>3.2.4.RELEASE</version>
    <scope>test</scope>
</dependency>
           

讓我們動起來,快速浏覽一下Spring Social的内部。

展望Spring社交網絡

我們可能在本教程的第二部分中還記得過 , RegistrationController類負責呈現系統資料庫單并處理系統資料庫單的表單送出。 它使用ProviderSignInUtils類有兩個目的:

  1. 呈現系統資料庫單時,如果使用者正在使用社交登入建立新的使用者帳戶,則RegistrationController類會預先填充表單字段。表單對象是使用所用SaaS API提供程式提供的資訊來預先填充的。 此資訊存儲到Connection對象。 控制器類通過調用ProviderSignInUtils類的靜态getConnection()方法來擷取Connection對象。
  2. 建立新使用者帳戶後,如果使用者帳戶是使用社交登入建立的,則RegistrationConnection類會将Connection對象保留在資料庫中。控制器類通過調用ProviderSignInUtils類的handlePostSignUp()方法來實作此目的 。

如果我們想了解ProviderSignInUtils類的作用,請看一下其源代碼。 ProviderSignInUtils類的源代碼如下所示:

package org.springframework.social.connect.web;

import org.springframework.social.connect.Connection;
import org.springframework.web.context.request.RequestAttributes;

public class ProviderSignInUtils {
   
    public static Connection<?> getConnection(RequestAttributes request) {
        ProviderSignInAttempt signInAttempt = getProviderUserSignInAttempt(request);
        return signInAttempt != null ? signInAttempt.getConnection() : null;
    }

    public static void handlePostSignUp(String userId, RequestAttributes request) {
        ProviderSignInAttempt signInAttempt = getProviderUserSignInAttempt(request);
        if (signInAttempt != null) {
            signInAttempt.addConnection(userId);
            request.removeAttribute(ProviderSignInAttempt.SESSION_ATTRIBUTE, RequestAttributes.SCOPE_SESSION);
        }      
    }
   
    private static ProviderSignInAttempt getProviderUserSignInAttempt(RequestAttributes request) {
        return (ProviderSignInAttempt) request.getAttribute(ProviderSignInAttempt.SESSION_ATTRIBUTE, RequestAttributes.SCOPE_SESSION);
    }
}
           

我們可以從ProviderSignInUtils類的源代碼中看到兩件事:

  1. getConnection()方法從會話中擷取ProviderSignInAttempt對象。 如果擷取的對象為null,則傳回null。 否則,它将調用ProviderSignInAttempt類的getConnection()方法并傳回Connection對象。
  2. handlePostSignUp()方法從會話中擷取ProviderSignInAttempt對象。 如果找到該對象,它将調用ProviderSignInAttempt類的addConnection()方法,并從會話中删除找到的ProviderSignInAttempt對象。

顯然,為了為RegistrationController類編寫單元測試,我們必須找出一種建立ProviderSignInAttempt對象并将建立的對象設定為session的方法。

讓我們找出這是如何完成的。

建立測試雙打

如我們所知,如果要為RegistrationController類編寫單元測試,則必須找到一種建立ProviderSignInAttempt對象的方法。 本節介紹如何通過使用測試雙打來實作此目标。

讓我們繼續前進,了解如何在單元測試中建立ProviderSignInAttempt對象。

建立ProviderSignInAttempt對象

如果我們想了解如何建立ProviderSignInAttempt對象,則必須仔細檢視其源代碼。 ProviderSignInAttempt類的源代碼如下所示:

package org.springframework.social.connect.web;

import java.io.Serializable;

import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionData;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.DuplicateConnectionException;
import org.springframework.social.connect.UsersConnectionRepository;

@SuppressWarnings("serial")
public class ProviderSignInAttempt implements Serializable {

    public static final String SESSION_ATTRIBUTE = ProviderSignInAttempt.class.getName();

    private final ConnectionData connectionData;
   
    private final ConnectionFactoryLocator connectionFactoryLocator;
   
    private final UsersConnectionRepository connectionRepository;
       
    public ProviderSignInAttempt(Connection<?> connection, ConnectionFactoryLocator connectionFactoryLocator, UsersConnectionRepository connectionRepository) {
        this.connectionData = connection.createData();
        this.connectionFactoryLocator = connectionFactoryLocator;
        this.connectionRepository = connectionRepository;      
    }
       
    public Connection<?> getConnection() {
        return connectionFactoryLocator.getConnectionFactory(connectionData.getProviderId()).createConnection(connectionData);
    }

    void addConnection(String userId) {
        connectionRepository.createConnectionRepository(userId).addConnection(getConnection());
    }
}
           

如我們所見, ProviderSignInAttempt類具有三個依賴關系,如下所示:

  • Connection接口表示與使用的SaaS API提供程式的連接配接。
  • ConnectionFactoryLocator接口指定查找ConnectionFactory對象所需的方法。
  • UsersConnectionRepository接口聲明用于管理使用者與SaaS API提供程式之間的連接配接的方法。

首先想到的是模拟這些依賴關系。 盡管這似乎是一個好主意,但是這種方法有兩個問題:

  1. 在編寫的每個測試中,我們都必須配置模拟對象的行為。 這意味着我們的測試将更難了解。
  2. 我們正在将Spring Social的實作細節洩漏到我們的測試中。 這将使我們的測試難以維護,因為如果實施Spring Social更改,我們的測試可能會被破壞。

顯然,模拟并不是解決此問題的最佳解決方案。 我們必須記住,即使模拟是一種有價值且友善的測試工具, 我們也不應過度使用它 。

這就産生了一個新問題:

如果無法進行模拟,那麼什麼才是正确的工具?

這個問題的答案可以從Martin Fowler的一篇文章中找到。 在本文中,馬丁·福勒(Martin Fowler)指定了一個稱為存根的測試雙精度,如下所示:

存根提供對測試過程中進行的呼叫的固定答複,通常通常根本不響應為測試程式設計的内容。 存根還可以記錄有關呼叫的資訊,例如,電子郵件網關存根可以記住“已發送”的消息,或者僅記住“已發送”的消息數量。

使用存根非常有意義,因為我們對兩件事感興趣:

  1. 我們需要能夠配置存根傳回的Connection <?>對象。
  2. 建立新的使用者帳戶後,我們需要驗證連接配接是否與資料庫保持一緻。

我們可以按照以下步驟建立一個實作這些目标的存根:

  1. 建立一個TestProviderSignInAttempt類,該類擴充了ProviderSignInAttempt類。
  2. 将私有連接配接字段添加到該類,并将添加的字段的類型設定為Connection <?> 。 該字段包含對使用者和SaaS API提供程式之間的連接配接的引用。
  3. 将私有連接配接字段添加到該類,并将添加到的字段的類型設定為Set <String> 。 該字段包含持久連接配接的使用者辨別。
  4. 向建立的類添加一個将Connection <?>對象作為構造函數參數的構造函數。 通過執行以下步驟來實作構造函數:
    1. 調用ProviderSignInAttempt類的構造函數,并将Connection <?>對象作為構造函數參數傳遞。 将其他構造函數參數的值設定為null 。
    2. 将作為構造函數參數提供的Connection <?>對象設定為connection字段。
  5. 重寫ProviderSignInAttempt類的getConnection()方法,并通過将存儲的對象傳回到連接配接字段來實作它。
  6. 重寫ProviderSignInAttempt類的addConnection(String userId)方法,并通過将作為方法參數給出的使用者ID添加到連接配接集中來實作它。
  7. 将公共getConnections()方法添加到建立的類中,并通過傳回連接配接集來實作它。

TestProviderSignInAttempt的源代碼如下所示:

package org.springframework.social.connect.web;

import org.springframework.social.connect.Connection;

import java.util.HashSet;
import java.util.Set;

public class TestProviderSignInAttempt extends ProviderSignInAttempt {

    private Connection<?> connection;

    private Set<String> connections = new HashSet<>();

    public TestProviderSignInAttempt(Connection<?> connection) {
        super(connection, null, null);
        this.connection = connection;
    }

    @Override
    public Connection<?> getConnection() {
        return connection;
    }

    @Override
    void addConnection(String userId) {
        connections.add(userId);
    }

    public Set<String> getConnections() {
        return connections;
    }
}
           

讓我們繼續前進,找出如何建立用于單元測試的Connection <?>類。

建立連接配接類

建立的連接配接類是一個存根類,它模拟“真實”連接配接類的行為,但是它沒有實作與OAuth1和OAuth2連接配接關聯的任何邏輯。 同樣,此類必須實作Connection接口。

我們可以按照以下步驟建立此存根類:

  1. 建立一個TestConnection類,該類擴充了AbstractConnection類。 AbstractConnection類是基類,它定義了所有連接配接實作共享的狀态和行為。
  2. 将connectionData字段添加到建立的類。 将字段的類型設定為ConnectionData 。 ConnectionData是一個資料傳輸對象,其中包含與使用的SaaS API提供程式的連接配接的内部狀态。
  3. 将userProfile字段添加到建立的類。 将字段的類型設定為UserProfile 。 此類表示所使用的SaaS API提供程式的使用者配置檔案,并且包含在不同服務提供程式之間共享的資訊。
  4. 建立一個将ConnectionData和UserProfile對象作為構造函數參數的構造函數,并按照以下步驟實作它:
    1. 調用AbstractConnection類的構造函數,并将ConnectionData對象作為第一個構造函數參數傳遞。 将第二個構造函數參數設定為null 。
    2. 設定connectionData字段的值。
    3. 設定userProfile字段的值。
  5. 重寫AbstractConnection類的fetchUserProfile()方法,并通過将存儲的對象傳回到userProfile字段來實作它。
  6. 重寫AbstractConnection類的getAPI()方法,并通過傳回null來實作它。
  7. 重寫AbstractConnection類的createData()方法,并通過将存儲的對象傳回到connectionData字段來實作它。

TestConnection類的源代碼如下所示:

package org.springframework.social.connect.support;

import org.springframework.social.connect.ConnectionData;
import org.springframework.social.connect.UserProfile;

public class TestConnection extends AbstractConnection {

    private ConnectionData connectionData;

    private UserProfile userProfile;

    public TestConnection(ConnectionData connectionData, UserProfile userProfile) {
        super(connectionData, null);
        this.connectionData = connectionData;
        this.userProfile = userProfile;
    }

    @Override
    public UserProfile fetchUserProfile() {
        return userProfile;
    }

    @Override
    public Object getApi() {
        return null;
    }

    @Override
    public ConnectionData createData() {
        return connectionData;
    }
}
           

讓我們繼續前進,弄清楚如何在單元測試中建立這些測試雙打。

建立建構器類

現在,我們為單元測試創​​建了存根類。 我們的最後一步是弄清楚如何使用這些類建立TestProviderSignInAttempt對象。

至此,我們知道

  1. TestProviderSignInAttempt類的構造函數将Connection對象作為構造函數參數。
  2. TestConnection類的構造函數将ConnectionData和UserProfile對象用作構造函數參數。

這意味着我們可以按照以下步驟建立新的TestProviderSignInAttempt對象:

  1. 建立一個新的ConnectionData對象。 ConnectionData類具有單個構造函數,該構造函數将必填字段用作構造函數參數。
  2. 建立一個新的UserProfile對象。 我們可以使用UserProfileBuilder類建立新的UserProfile對象。
  3. 建立一個新的TestConnection對象,并将建立的ConnectionData和UserProfile對象作為構造函數參數傳遞。
  4. 建立一個新的TestProviderSignInAttempt對象,并将建立的TestConnectionConnection對象作為構造函數參數傳遞。

建立一個新的TestProviderSignInAttempt對象的源代碼如下所示:

ConnectionData connectionData = new ConnectionData("providerId",
                 "providerUserId",
                 "displayName",
                 "profileUrl",
                 "imageUrl",
                 "accessToken",
                 "secret",
                 "refreshToken",
                 1000L);
 
 UserProfile userProfile = userProfileBuilder
                .setEmail("email")
                .setFirstName("firstName")
                .setLastName("lastName")
                .build();
               
TestConnection connection = new TestConnection(connectionData, userProfile);
TestProviderSignInAttempt signIn = new TestProviderSignInAttempt(connection);
           

好消息是,我們現在知道如何在測試中建立TestProviderSignInAttempt對象。 壞消息是我們無法在測試中使用此代碼。

我們必須記住,我們并不是為了確定我們的代碼按預期工作而編寫單元測試。 每個測試用例還應該揭示我們的代碼在特定情況下的行為。 如果我們通過将此代碼添加到每個測試用例中來建立TestProviderSignInAttempt ,那麼我們将過于強調建立測試用例所需的對象。 這意味着很難了解測試用例,并且丢失了測試用例的“本質”。

相反,我們将建立一個測試資料建構器類,該類提供了用于建立TestProviderSignInAttempt對象的流利的API。 我們可以按照以下步驟建立此類:

  1. 建立一個名為TestProviderSignInAttemptBuilder的類。
  2. 将建立新的ConnectionData和UserProfile對象所需的所有字段添加到TestProviderSignInAttemptBuilder類。
  3. 添加用于設定所添加字段的字段值的方法。 通過執行以下步驟來實作每種方法:
    1. 将作為方法參數給出的值設定為正确的字段。
    2. 傳回對TestProviderSignInAttemptBuilder對象的引用。
  4. 将connectionData()和userProfile()方法添加到TestProviderSignInAttemptBuilder類。 這些方法僅傳回對TestProviderSignInAttemptBuilder對象的引用,其目的是使我們的API更具可讀性。
  5. 将build()方法添加到測試資料建構器類。 這将按照前面介紹的步驟建立TestProviderSignInAttempt對象,并傳回建立的對象。

TestProviderSignInAttemptBuilder類的源代碼如下所示:

package org.springframework.social.connect.support;

import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionData;
import org.springframework.social.connect.UserProfile;
import org.springframework.social.connect.UserProfileBuilder;
import org.springframework.social.connect.web.TestProviderSignInAttempt;

public class TestProviderSignInAttemptBuilder {

    private String accessToken;

    private String displayName;

    private String email;

    private Long expireTime;

    private String firstName;

    private String imageUrl;

    private String lastName;

    private String profileUrl;

    private String providerId;

    private String providerUserId;

    private String refreshToken;

    private String secret;

    public TestProviderSignInAttemptBuilder() {

    }

    public TestProviderSignInAttemptBuilder accessToken(String accessToken) {
        this.accessToken = accessToken;
        return this;
    }

    public TestProviderSignInAttemptBuilder connectionData() {
        return this;
    }

    public TestProviderSignInAttemptBuilder displayName(String displayName) {
        this.displayName = displayName;
        return this;
    }

    public TestProviderSignInAttemptBuilder email(String email) {
        this.email = email;
        return this;
    }

    public TestProviderSignInAttemptBuilder expireTime(Long expireTime) {
        this.expireTime = expireTime;
        return this;
    }

    public TestProviderSignInAttemptBuilder firstName(String firstName) {
        this.firstName = firstName;
        return this;
    }

    public TestProviderSignInAttemptBuilder imageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
        return this;
    }

    public TestProviderSignInAttemptBuilder lastName(String lastName) {
        this.lastName = lastName;
        return this;
    }

    public TestProviderSignInAttemptBuilder profileUrl(String profileUrl) {
        this.profileUrl = profileUrl;
        return this;
    }

    public TestProviderSignInAttemptBuilder providerId(String providerId) {
        this.providerId = providerId;
        return this;
    }

    public TestProviderSignInAttemptBuilder providerUserId(String providerUserId) {
        this.providerUserId = providerUserId;
        return this;
    }

    public TestProviderSignInAttemptBuilder refreshToken(String refreshToken) {
        this.refreshToken = refreshToken;
        return this;
    }

    public TestProviderSignInAttemptBuilder secret(String secret) {
        this.secret = secret;
        return this;
    }

    public TestProviderSignInAttemptBuilder userProfile() {
        return this;
    }

    public TestProviderSignInAttempt build() {
        ConnectionData connectionData = new ConnectionData(providerId,
                providerUserId,
                displayName,
                profileUrl,
                imageUrl,
                accessToken,
                secret,
                refreshToken,
                expireTime);

        UserProfile userProfile = new UserProfileBuilder()
                .setEmail(email)
                .setFirstName(firstName)
                .setLastName(lastName)
                .build();

        Connection connection = new TestConnection(connectionData, userProfile);

        return new TestProviderSignInAttempt(connection);
    }
}
           

注意:在為RegistrationController類編寫單元測試時,不需要調用此建構器類的所有方法。 我添加這些字段的主要原因是,當我們為示例應用程式編寫內建測試時,它們将非常有用。

現在,建立新的TestProviderSignInAttempt對象的代碼更加整潔,可讀性更好:

TestProviderSignInAttempt socialSignIn = new TestProviderSignInAttemptBuilder()
                .connectionData()
                    .providerId("twitter")
                .userProfile()
                    .email("email")
                    .firstName("firstName")
                    .lastName("lastName")
                .build();
           

讓我們繼續前進,了解如何使用自定義FEST-Assert斷言清理單元測試。

建立自定義斷言

我們可以通過将标準JUnit斷言替換為自定義FEST-Assert斷言來清理單元測試。 我們必須建立以下三個自定義斷言類:

  • 第一個斷言類用于為ExampleUserDetails對象編寫斷言。 ExampleUserDetails類包含已登入使用者的資訊,該資訊存儲在應用程式的SecurityContext中。 換句話說,此類提供的斷言用于驗證登入使用者的資訊是否正确。
  • 第二個斷言類用于為SecurityContext對象編寫斷言。 此類用于為其資訊存儲到SecurityContext的使用者寫斷言。
  • 第三個斷言類用于為TestProviderSignInAttempt對象編寫斷言。 此斷言類用于驗證是否通過使用TestProviderSignInAttempt對象建立了與SaaS API提供程式的連接配接。

注意:如果您不熟悉FEST-Assert,則應閱讀我的部落格文章,其中解釋了如何使用FEST-Assert建立自定義斷言 ,以及為什麼要考慮這樣做。

讓我們繼續。

建立ExampleUserDetailsAssert類

通過執行以下步驟,我們可以實作第一個自定義斷言類:

  1. 建立一個ExampleUserDetailsAssert類,該類擴充了GenericAssert類。 提供以下類型參數:
    1. 第一個類型參數是自定義斷言的類型。 将此類型參數的值設定為ExampleUserDetailsAssert 。
    2. 第二個類型參數是實際值對象的類型。 将此類型參數的值設定為ExampleUserDetails。
  2. 向建立的類添加一個私有構造函數。 此構造函數将ExampleUserDetails對象作為構造函數參數。 通過調用超類的構造函數并将以下對象作為構造函數參數傳遞來實作控制器:
    1. 第一個構造函數參數是一個Class對象,它指定自定義斷言類的類型。 将此構造函數參數的值設定為ExampleUserDetailsAssert.class 。
    2. 第二個構造函數參數是實際值對象。 将作為構造函數參數給出的對象傳遞給超類的構造函數。
  3. 将靜态assertThat()方法添加到建立的類。 此方法将ExampleUserDetails對象作為方法參數。 通過建立一個新的ExampleUserDetailsAssert對象來實作此方法。
  4. 将hasFirstName()方法添加到ExampleUserDetailsAssert類。 此方法将String對象作為方法參數,并傳回ExampleUserDetailsAssert對象。 我們可以通過執行以下步驟來實作此方法:
    1. 通過調用GenericAssert類的isNotNull()方法,確定實際的ExampleUserDetails對象不為null。
    2. 驗證明際的名字是否等于作為方法參數給出的期望的名字。
    3. 傳回對ExampleUserDetailsAssert對象的引用。
  5. 将一個hasId()方法添加到ExampleUserDetailsAssert類。 此方法将Long對象作為方法參數,并傳回ExampleUserDetailsAssert對象。 我們可以通過執行以下步驟來實作此方法:
    1. 通過調用GenericAssert類的isNotNull()方法,確定實際的ExampleUserDetails對象不為null。
    2. 驗證明際ID是否等于作為方法參數給出的預期ID。
    3. 傳回對ExampleUserDetailsAssert對象的引用。
  6. 将hasLastName()方法添加到ExampleUserDetailsAssert類。 此方法将String對象作為方法參數,并傳回ExampleUserDetailsAssert對象。 我們可以通過執行以下步驟來實作此方法:
    1. 通過調用GenericAssert類的isNotNull()方法,確定實際的ExampleUserDetails對象不為null。
    2. 驗證明際的姓氏是否等于作為方法參數給出的期望的姓氏。
    3. 傳回對ExampleUserDetailsAssert對象的引用。
  7. 将hasPassword()方法添加到ExampleUserDetailsAssert類。 此方法将String對象作為方法參數,并傳回ExampleUserDetailsAssert對象。 我們可以通過執行以下步驟來實作此方法:
    1. 通過調用GenericAssert類的isNotNull()方法,確定實際的ExampleUserDetails對象不為null。
    2. 驗證明際密碼是否等于作為方法參數給出的預期密碼。
    3. 傳回對ExampleUserDetailsAssert對象的引用。
  8. 将一個hasUsername()方法添加到ExampleUserDetailsAssert類。 此方法将String對象作為方法參數,并傳回ExampleUserDetailsAssert對象。 我們可以通過執行以下步驟來實作此方法:
    1. 通過調用GenericAssert類的isNotNull()方法,確定實際的ExampleUserDetails對象不為null。
    2. 驗證明際使用者名是否等于作為方法參數給出的預期使用者名。
    3. 傳回對ExampleUserDetailsAssert對象的引用。
  9. 将isActive()方法添加到ExampleUserDetailsAssert類。 此方法不帶方法參數,它傳回ExampleUserDetailsAssert對象。
    1. 通過調用GenericAssert類的isNotNull()方法,確定實際的ExampleUserDetails對象不為null。
    2. 驗證其資訊存儲在ExampleUserDetails對象中的使用者是否處于活動狀态。
    3. 傳回對ExampleUserDetailsAssert對象的引用。
  10. 将isRegisteredUser()方法添加到ExampleUserDetailsAssert類。 此方法不帶方法參數,它傳回ExampleUserDetailsAssert對象。
    1. 通過調用GenericAssert類的isNotNull()方法,確定實際的ExampleUserDetails對象不為null。
    2. 驗證其資訊存儲在ExampleUserDetails對象中的使用者是注冊使用者。
    3. 傳回對ExampleUserDetailsAssert對象的引用。
  11. 将isRegisteredByUsingFormRegistration()方法添加到ExampleUserDetailsAssert類。 此方法傳回ExampleUserDetailsAssert對象。 我們可以通過執行以下步驟來實作此方法:
    1. 通過調用GenericAssert類的isNotNull()方法,確定實際的ExampleUserDetails對象不為null。
    2. 驗證socialSignInProvider字段的值為空。
    3. 傳回對ExampleUserDetailsAssert對象的引用。
  12. 将isSignedInByUsingSocialSignInProvider()方法添加到ExampleUserDetailsAssert類。 此方法将SocialMediaService枚舉作為方法參數,并傳回ExampleUserDetailsAssert對象。 我們可以通過執行以下步驟來實作此方法:
    1. 通過調用GenericAssert類的isNotNull()方法,確定實際的ExampleUserDetails對象不為null。
    2. 驗證socialSignInProvider的值等于作為方法參數給出的預期的SocialMediaService枚舉。
    3. 傳回對ExampleUserDetailsAssert對象的引用。

ExampleUserDetailsAssert類的源代碼如下所示:

import org.fest.assertions.Assertions;
import org.fest.assertions.GenericAssert;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;

public class ExampleUserDetailsAssert extends GenericAssert<ExampleUserDetailsAssert, ExampleUserDetails> {

    private ExampleUserDetailsAssert(ExampleUserDetails actual) {
        super(ExampleUserDetailsAssert.class, actual);
    }

    public static ExampleUserDetailsAssert assertThat(ExampleUserDetails actual) {
        return new ExampleUserDetailsAssert(actual);
    }

    public ExampleUserDetailsAssert hasFirstName(String firstName) {
        isNotNull();

        String errorMessage = String.format(
                "Expected first name to be <%s> but was <%s>",
                firstName,
                actual.getFirstName()
        );

        Assertions.assertThat(actual.getFirstName())
                .overridingErrorMessage(errorMessage)
                .isEqualTo(firstName);

        return this;
    }

    public ExampleUserDetailsAssert hasId(Long id) {
        isNotNull();

        String errorMessage = String.format(
                "Expected id to be <%d> but was <%d>",
                id,
                actual.getId()
        );

        Assertions.assertThat(actual.getId())
                .overridingErrorMessage(errorMessage)
                .isEqualTo(id);

        return this;
    }

    public ExampleUserDetailsAssert hasLastName(String lastName) {
        isNotNull();

        String errorMessage = String.format(
                "Expected last name to be <%s> but was <%s>",
                lastName,
                actual.getLastName()
        );

        Assertions.assertThat(actual.getLastName())
                .overridingErrorMessage(errorMessage)
                .isEqualTo(lastName);

        return this;
    }

    public ExampleUserDetailsAssert hasPassword(String password) {
        isNotNull();

        String errorMessage = String.format(
                "Expected password to be <%s> but was <%s>",
                password,
                actual.getPassword()
        );

        Assertions.assertThat(actual.getPassword())
                .overridingErrorMessage(errorMessage)
                .isEqualTo(password);

        return this;
    }

    public ExampleUserDetailsAssert hasUsername(String username) {
        isNotNull();

        String errorMessage = String.format(
                "Expected username to be <%s> but was <%s>",
                username,
                actual.getUsername()
        );

        Assertions.assertThat(actual.getUsername())
                .overridingErrorMessage(errorMessage)
                .isEqualTo(username);

        return this;
    }

    public ExampleUserDetailsAssert isActive() {
        isNotNull();

        String expirationErrorMessage = "Expected account to be non expired but it was expired";
        Assertions.assertThat(actual.isAccountNonExpired())
                .overridingErrorMessage(expirationErrorMessage)
                .isTrue();

        String lockedErrorMessage = "Expected account to be non locked but it was locked";
        Assertions.assertThat(actual.isAccountNonLocked())
                .overridingErrorMessage(lockedErrorMessage)
                .isTrue();

        String credentialsExpirationErrorMessage = "Expected credentials to be non expired but they were expired";
        Assertions.assertThat(actual.isCredentialsNonExpired())
                .overridingErrorMessage(credentialsExpirationErrorMessage)
                .isTrue();

        String enabledErrorMessage = "Expected account to be enabled but it was not";
        Assertions.assertThat(actual.isEnabled())
                .overridingErrorMessage(enabledErrorMessage)
                .isTrue();

        return this;
    }

    public ExampleUserDetailsAssert isRegisteredUser() {
        isNotNull();

        String errorMessage = String.format(
                "Expected role to be <ROLE_USER> but was <%s>",
                actual.getRole()
        );

        Assertions.assertThat(actual.getRole())
                .overridingErrorMessage(errorMessage)
                .isEqualTo(Role.ROLE_USER);

        Collection<? extends GrantedAuthority> authorities = actual.getAuthorities();

        String authoritiesCountMessage = String.format(
                "Expected <1> granted authority but found <%d>",
                authorities.size()
        );

        Assertions.assertThat(authorities.size())
                .overridingErrorMessage(authoritiesCountMessage)
                .isEqualTo(1);

        GrantedAuthority authority = authorities.iterator().next();

        String authorityErrorMessage = String.format(
                "Expected authority to be <ROLE_USER> but was <%s>",
                authority.getAuthority()
        );

        Assertions.assertThat(authority.getAuthority())
                .overridingErrorMessage(authorityErrorMessage)
                .isEqualTo(Role.ROLE_USER.name());

        return this;
    }

    public ExampleUserDetailsAssert isRegisteredByUsingFormRegistration() {
        isNotNull();

        String errorMessage = String.format(
                "Expected socialSignInProvider to be <null> but was <%s>",
                actual.getSocialSignInProvider()
        );

        Assertions.assertThat(actual.getSocialSignInProvider())
                .overridingErrorMessage(errorMessage)
                .isNull();

        return this;
    }

    public ExampleUserDetailsAssert isSignedInByUsingSocialSignInProvider(SocialMediaService socialSignInProvider) {
        isNotNull();

        String errorMessage = String.format(
                "Expected socialSignInProvider to be <%s> but was <%s>",
                socialSignInProvider,
                actual.getSocialSignInProvider()
        );

        Assertions.assertThat(actual.getSocialSignInProvider())
                .overridingErrorMessage(errorMessage)
                .isEqualTo(socialSignInProvider);

        return this;
    }
}
           

建立SecurityContextAssert類

我們可以按照以下步驟建立第二個客戶斷言類:

  1. 建立一個SecurityContextAssert類,該類擴充了GenericAssert類。 提供以下類型參數:
    1. 第一個類型參數是自定義斷言的類型。 将此類型參數的值設定為SecurityContextAssert 。
    2. 第二個類型參數是實際值對象的類型。 将此類型參數的值設定為SecurityContext 。
  2. 向建立的類添加一個私有構造函數。 該構造函數将SecurityContext對象作為構造函數參數。 通過調用超類的構造函數并将以下對象作為構造函數參數傳遞來實作控制器:
    1. 第一個構造函數參數是一個Class對象,它指定自定義斷言類的類型。 将此構造函數參數的值設定為SecurityContextAssert.class 。
    2. 第二個構造函數參數是實際值對象。 将作為構造函數參數給出的對象傳遞給超類的構造函數。
  3. 将靜态assertThat()方法添加到建立的類。 此方法将SecurityContext對象作為方法參數。 通過建立一個新的SecurityContextAssert對象來實作此方法。
  4. 将userIsAnonymous()方法添加到SecurityContextAssert類,并通過以下步驟實作它:
    1. 通過調用GenericAssert類的isNotNull()方法,確定實際的SecurityContext對象不為null。
    2. 從SecurityContext擷取Authentication對象,并確定它為null 。
    3. 傳回對SecurityContextAssert對象的引用。
  5. 将一個loggingInUserIs()方法添加到SecurityContextAssert類。 此方法将User對象作為方法參數,并傳回SecurityContextAssert對象。 我們可以通過執行以下步驟來實作此方法:
    1. 通過調用GenericAssert類的isNotNull()方法,確定實際的SecurityContext對象不為null。
    2. 從SecurityContext擷取ExampleUserDetails對象,并確定它不為null。
    3. 確定ExampleUserDetails對象的資訊與User對象的資訊相等。
    4. 傳回對SecurityContextAssert對象的引用。
  6. 将一個loggingInUserHasPassword()方法添加到SecurityContextAssert類。 此方法将String對象作為方法參數,并傳回SecurityContextAssert對象。 我們可以通過執行以下步驟來實作此方法:
    1. 通過調用GenericAssert類的isNotNull()方法,確定實際的SecurityContext對象不為null。
    2. 從SecurityContext擷取ExampleUserDetails對象,并確定它不為null。
    3. 確定ExampleUserDetails對象的密碼字段等于作為方法參數給出的密碼。
    4. 傳回對SecurityContextAssert對象的引用。
  7. 将一個loggingInUserIsRegisteredByUsingNormalRegistration()方法添加到SecurityContextAssert類,并通過以下步驟實作它:
    1. 通過調用GenericAssert類的isNotNull()方法,確定實際的SecurityContext對象不為null。
    2. 從SecurityContext擷取ExampleUserDetails對象,并確定它不為null。
    3. 確定使用普通注冊建立使用者帳戶。
    4. 傳回對SecurityContextAssert對象的引用。
  8. 将一個loggingInUserIsSignedInByUsingSocialProvider()方法添加到SecurityContextAssert類。 此方法将SocialMediaService枚舉作為方法參數,并傳回SecurityContextAssert對象。 我們可以通過執行以下步驟來實作此方法:
    1. 通過調用GenericAssert類的isNotNull()方法,確定實際的SecurityContext對象不為null。
    2. 從SecurityContext擷取ExampleUserDetails對象,并確定它不為null。
    3. 確定通過使用作為方法參數給出的SociaMediaService建立使用者帳戶。
    4. 傳回對SecurityContextAssert對象的引用。

SecurityContextAssert類的源代碼如下所示:

import org.fest.assertions.Assertions;
import org.fest.assertions.GenericAssert;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;

public class SecurityContextAssert extends GenericAssert<SecurityContextAssert, SecurityContext> {

    private SecurityContextAssert(SecurityContext actual) {
        super(SecurityContextAssert.class, actual);
    }

    public static SecurityContextAssert assertThat(SecurityContext actual) {
        return new SecurityContextAssert(actual);
    }

    public SecurityContextAssert userIsAnonymous() {
        isNotNull();

        Authentication authentication = actual.getAuthentication();

        String errorMessage = String.format("Expected authentication to be <null> but was <%s>.", authentication);
        Assertions.assertThat(authentication)
                .overridingErrorMessage(errorMessage)
                .isNull();

        return this;
    }

    public SecurityContextAssert loggedInUserIs(User user) {
        isNotNull();

        ExampleUserDetails loggedIn = (ExampleUserDetails) actual.getAuthentication().getPrincipal();

        String errorMessage = String.format("Expected logged in user to be <%s> but was <null>", user);
        Assertions.assertThat(loggedIn)
                .overridingErrorMessage(errorMessage)
                .isNotNull();

        ExampleUserDetailsAssert.assertThat(loggedIn)
                .hasFirstName(user.getFirstName())
                .hasId(user.getId())
                .hasLastName(user.getLastName())
                .hasUsername(user.getEmail())
                .isActive()
                .isRegisteredUser();

        return this;
    }

    public SecurityContextAssert loggedInUserHasPassword(String password) {
        isNotNull();

        ExampleUserDetails loggedIn = (ExampleUserDetails) actual.getAuthentication().getPrincipal();

        String errorMessage = String.format("Expected logged in user to be <not null> but was <null>");
        Assertions.assertThat(loggedIn)
                .overridingErrorMessage(errorMessage)
                .isNotNull();

        ExampleUserDetailsAssert.assertThat(loggedIn)
                .hasPassword(password);

        return this;
    }

    public SecurityContextAssert loggedInUserIsRegisteredByUsingNormalRegistration() {
        isNotNull();

        ExampleUserDetails loggedIn = (ExampleUserDetails) actual.getAuthentication().getPrincipal();

        String errorMessage = String.format("Expected logged in user to be <not null> but was <null>");
        Assertions.assertThat(loggedIn)
                .overridingErrorMessage(errorMessage)
                .isNotNull();

        ExampleUserDetailsAssert.assertThat(loggedIn)
                .isRegisteredByUsingFormRegistration();

        return this;
    }

    public SecurityContextAssert loggedInUserIsSignedInByUsingSocialProvider(SocialMediaService signInProvider) {
        isNotNull();

        ExampleUserDetails loggedIn = (ExampleUserDetails) actual.getAuthentication().getPrincipal();

        String errorMessage = String.format("Expected logged in user to be <not null> but was <null>");
        Assertions.assertThat(loggedIn)
                .overridingErrorMessage(errorMessage)
                .isNotNull();

        ExampleUserDetailsAssert.assertThat(loggedIn)
                .hasPassword("SocialUser")
                .isSignedInByUsingSocialSignInProvider(signInProvider);

        return this;
    }
}
           

建立TestProviderSignInAttemptAssert類

我們可以按照以下步驟建立第三個自定義斷言類:

  1. 建立一個TestProviderSignInAttemptAssert類,該類擴充了GenericAssert類。 提供以下類型參數:
    1. 第一個類型參數是自定義斷言的類型。 将此類型參數的值設定為TestProviderSignInAttemptAssert 。
    2. 第二個類型參數是實際值對象的類型。 将此類型參數的值設定為TestProviderSignInAttempt 。
  2. 向建立的類添加一個私有構造函數。 此構造函數将TestProviderSignInAttempt對象作為構造函數參數。 通過調用超類的構造函數并将以下對象作為構造函數參數傳遞來實作控制器:
    1. 第一個構造函數參數是一個Class對象,它指定自定義斷言類的類型。 将此構造函數參數的值設定為TestProviderSignInAttemptAssert.class 。
    2. 第二個構造函數參數是實際值對象。 将作為構造函數參數給出的對象傳遞給超類的構造函數。
  3. 将靜态assertThatSignIn()方法添加到建立的類。 此方法将TestProviderSignInAttempt對象作為方法參數。 通過建立一個新的TestProviderSignInAttemptAssert對象來實作此方法。
  4. 向建立的類添加一個createdNoConnections()方法。 此方法不帶方法參數,并且傳回對TestProviderSignInAttemptAssert對象的引用。 我們可以通過執行以下步驟來實作此方法:
    1. 通過調用GenericAssert類的isNotNull()方法,確定實際的TestProviderSignInAttempt對象不為null。
    2. 確定實際的TestProviderSignInAttempt對象未建立任何連接配接。
    3. 傳回對TestProviderSignInAttemptAssert對象的引用。
  5. 向建立的類中添加一個createdConnectionForUserId()方法。 此方法将String對象作為方法參數,并傳回對TestProviderSignInAttempt對象的引用。 我們可以通過執行以下步驟來實作此方法:
    1. 通過調用GenericAssert類的isNotNull()方法,確定實際的TestProviderSignInAttempt對象不為null。
    2. 確定為使用者ID為方法參數的使用者建立了連接配接。
    3. 傳回對TestProviderSignInAttemptAssert對象的引用。

TestProviderSignInAttemptAssert類的源代碼如下所示:

import org.fest.assertions.Assertions;
import org.fest.assertions.GenericAssert;
import org.springframework.social.connect.web.TestProviderSignInAttempt;

public class TestProviderSignInAttemptAssert extends GenericAssert<TestProviderSignInAttemptAssert, TestProviderSignInAttempt> {

    private TestProviderSignInAttemptAssert(TestProviderSignInAttempt actual) {
        super(TestProviderSignInAttemptAssert.class, actual);
    }

    public static TestProviderSignInAttemptAssert assertThatSignIn(TestProviderSignInAttempt actual) {
        return new TestProviderSignInAttemptAssert(actual);
    }

    public TestProviderSignInAttemptAssert createdNoConnections() {
        isNotNull();

        String error = String.format(
                "Expected that no connections were created but found <%d> connection",
                actual.getConnections().size()
        );
        Assertions.assertThat(actual.getConnections())
                .overridingErrorMessage(error)
                .isEmpty();

        return this;
    }

    public TestProviderSignInAttemptAssert createdConnectionForUserId(String userId) {
        isNotNull();

        String error = String.format(
                "Expected that connection was created for user id <%s> but found none.",
                userId
        );

        Assertions.assertThat(actual.getConnections())
                .overridingErrorMessage(error)
                .contains(userId);

        return this;
    }
}
           

讓我們繼續并開始為RegistrationController類編寫一些單元測試。

寫作單元測試

現在,我們已經完成準備工作,并準備為注冊功能編寫單元測試。 我們必須為以下控制器方法編寫單元測試:

  • 第一種控制器方法呈現注冊頁面。
  • 第二種控制器方法處理系統資料庫格的送出。

在開始編寫單元測試之前,我們必須對其進行配置。 讓我們找出這是如何完成的。

注意:我們的單元測試使用Spring MVC測試架構。 如果您不熟悉它,建議您看一下我的Spring MVC Test教程 。

配置我們的單元測試

我們的示例應用程式的應用程式上下文配置以易于編寫Web層的單元測試的方式進行設計。 這些設計原理如下所述:

  • 應用程式上下文配置分為幾個配置類,每個類都配置了應用程式的特定部分(Web,安全性,社交性和持久性)。
  • 我們的應用程式上下文配置有一個“主”配置類,該類配置一些“通用” bean并導入其他配置類。 該配置類還為服務層配置元件掃描。

當我們遵循這些原則配置應用程式上下文時,很容易為我們的單元測試創​​建應用程式上下文配置。 我們可以通過重用配置示例應用程式的Web層的應用程式上下文配置類并為單元測試創​​建一個新的應用程式上下文配置類來做到這一點。

通過執行以下步驟,我們可以為單元測試創​​建應用程式上下文配置類:

  1. 建立一個名為UnitTestContext的類。
  2. 用@Configuration注釋對建立的類進行注釋。
  3. 向建立的類中添加messageSource()方法,并使用@Bean注釋對方法進行注釋。 通過執行以下步驟配置MessageSource bean:
    1. 建立一個新的ResourceBundleMessageSource對象。
    2. 設定消息檔案的基本名稱,并確定如果未找到消息,則傳回其代碼。
    3. 傳回建立的對象。
  4. 将userService()方法添加到建立的類中,并使用@Bean注釋對該方法進行注釋。 通過執行以下步驟配置UserService模拟對象:
    1. 調用Mockito類的靜态嘲笑()方法,并将UserService.class作為方法參數傳遞。
    2. 傳回建立的對象。

UnitTestContext類的源代碼如下所示:

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;

import static org.mockito.Mockito.mock;

@Configuration
public class UnitTestContext {

    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();

        messageSource.setBasename("i18n/messages");
        messageSource.setUseCodeAsDefaultMessage(true);

        return messageSource;
    }

    @Bean
    public UserService userService() {
        return mock(UserService.class);
    }
}
           

接下來要做的是配置單元測試。 我們可以按照以下步驟進行操作:

  1. 使用@RunWith注釋對測試類進行注釋,并確定通過使用SpringUnit4ClassRunner執行我們的測試。
  2. 使用@ContextConfiguration批注對類進行批注,并確定使用正确的配置類。 在我們的例子中,正确的配置類是: WebAppContext和UnitTestContext 。
  3. 用@WebAppConfiguration批注對類進行批注。 此批注確定加載的應用程式上下文是WebApplicationContext 。
  4. 将MockMvc字段添加到測試類。
  5. 将WebApplicationContext字段添加到類中,并使用@Autowired批注對其進行批注。
  6. 将UserService字段添加到測試類,并使用@Autowired批注對其進行批注。
  7. 将setUp()方法添加到測試類,并使用@Before注釋對方法進行注釋。 這樣可以確定在每個測試方法之前調用該方法。 通過執行以下步驟來實作此方法:
    1. 通過調用Mockito類的靜态reset()方法并将經過重置的模拟作為方法參數傳遞來重置UserService模拟。
    2. 通過使用MockMvcBuilders類建立一個新的MockMvc對象。
    3. 運作我們的測試時,請確定從SecurityContext中沒有找到Authentication對象。 我們可以按照以下步驟進行操作:
      1. 通過調用SecurityContextHolder類的靜态getContext()方法來擷取對SecurityContext對象的引用。
      2. 通過調用SecurityContext類的setAuthentication()方法清除身份驗證。 将null作為方法參數傳遞。

我們的單元測試類的源代碼如下所示:

import org.junit.Before;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebAppContext.class, UnitTestContext.class})
@WebAppConfiguration
public class RegistrationControllerTest2 {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webAppContext;

    @Autowired
    private UserService userServiceMock;

    @Before
    public void setUp() {
        Mockito.reset(userServiceMock);

        mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext)
                .build();
               
        SecurityContextHolder.getContext().setAuthentication(null);
    }
}
           

注意:如果要獲得有關使用Spring MVC Test架構的單元測試的配置的更多資訊,建議您閱讀此部落格文章 。

讓我們繼續并為呈現系統資料庫格的控制器方法編寫單元測試。

送出系統資料庫

呈現系統資料庫的控制器方法具有一項重要職責:

如果使用者正在使用社交登入,則使用由使用過的SaaS API提供程式提供的使用資訊來預填充注冊字段。

讓我們重新整理記憶體,看一下RegistrationController類的源代碼:

import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionKey;
import org.springframework.social.connect.UserProfile;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.request.WebRequest;

@Controller
@SessionAttributes("user")
public class RegistrationController {

    @RequestMapping(value = "/user/register", method = RequestMethod.GET)
    public String showRegistrationForm(WebRequest request, Model model) {
        Connection<?> connection = ProviderSignInUtils.getConnection(request);

        RegistrationForm registration = createRegistrationDTO(connection);
        model.addAttribute("user", registration);

        return "user/registrationForm";
    }

    private RegistrationForm createRegistrationDTO(Connection<?> connection) {
        RegistrationForm dto = new RegistrationForm();

        if (connection != null) {
            UserProfile socialMediaProfile = connection.fetchUserProfile();
            dto.setEmail(socialMediaProfile.getEmail());
            dto.setFirstName(socialMediaProfile.getFirstName());
            dto.setLastName(socialMediaProfile.getLastName());

            ConnectionKey providerKey = connection.getKey();
            dto.setSignInProvider(SocialMediaService.valueOf(providerKey.getProviderId().toUpperCase()));
        }

        return dto;
    }
}
           

顯然,我們必須為此控制器方法編寫兩個單元測試:

  1. 我們必須編寫一個測試,以確定當使用者使用“正常”注冊時,控制器方法能夠正常工作。
  2. 我們必須編寫一個測試,以確定當使用者使用社交登入時,控制器方法能夠正常工作。

讓我們移動并編寫這些單元測試。

測試1:提​​交普通系統資料庫

我們可以按照以下步驟編寫第一個單元測試:

  1. 執行GET請求以發送url'/ user / register'。
  2. 確定傳回HTTP狀态代碼200。
  3. 驗證渲染視圖的名稱為“ user / registrationForm”。
  4. Verify that the request is forwarded to url '/WEB-INF/jsp/user/registrationForm.jsp'.
  5. Ensure that all fields of the model attribute called 'user' are either null or empty.
  6. Verify that no methods of the UserService mock were called.

我們的單元測試的源代碼如下所示:

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebAppContext.class, UnitTestContext.class})
@WebAppConfiguration
public class RegistrationControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webAppContext;

    @Autowired
    private UserService userServiceMock;

    //The setUp() method is omitted for the sake of clarity

    @Test
    public void showRegistrationForm_NormalRegistration_ShouldRenderRegistrationPageWithEmptyForm() throws Exception {
        mockMvc.perform(get("/user/register"))
                .andExpect(status().isOk())
                .andExpect(view().name("user/registrationForm"))
                .andExpect(forwardedUrl("/WEB-INF/jsp/user/registrationForm.jsp"))
                .andExpect(model().attribute("user", allOf(
                        hasProperty("email", isEmptyOrNullString()),
                        hasProperty("firstName", isEmptyOrNullString()),
                        hasProperty("lastName", isEmptyOrNullString()),
                        hasProperty("password", isEmptyOrNullString()),
                        hasProperty("passwordVerification", isEmptyOrNullString()),
                        hasProperty("signInProvider", isEmptyOrNullString())
                )));

        verifyZeroInteractions(userServiceMock);
    }
}
           

Test 2: Rendering the Registration Form by Using Social Sign In

We can write the second unit test by following these steps:

  1. Create a new TestProviderSignInAttempt object by using the TestProviderSignInAttemptBuilder class. Set the provider id, first name, last name and email address.
  2. Execute a GET request to url '/user/register' and set the created TestProviderSignInAttempt object to the HTTP session.
  3. 確定傳回HTTP狀态代碼200。
  4. Verify that the name of the rendered view is 'user/registrationForm'.
  5. Ensure that the request is forwarded to url '/WEB-INF/jsp/user/registrationForm.jsp'.
  6. Verify that the fields of the model object called 'user' are pre-populated by using the information contained by the TestProviderSignInAttempt object. 我們可以按照以下步驟進行操作:
    1. Ensure that the value of the email field is '[email protected]'.
    2. Ensure that the value of the firstName field is 'John'.
    3. Ensure that the value of the lastName field is 'Smith'.
    4. Ensure that the value of the password field is empty or null String.
    5. Ensure that the value of the passwordVerification field is empty or null String.
    6. Ensure that the value of the signInProvider field is 'twitter'.
  7. Verify that the methods of the UserService interface were not called.

我們的單元測試的源代碼如下所示:

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.social.connect.support.TestProviderSignInAttemptBuilder;
import org.springframework.social.connect.web.ProviderSignInAttempt;
import org.springframework.social.connect.web.TestProviderSignInAttempt;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebAppContext.class, UnitTestContext.class})
@WebAppConfiguration
public class RegistrationControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webAppContext;

    @Autowired
    private UserService userServiceMock;

    //The setUp() method is omitted for the sake of clarity

    @Test
    public void showRegistrationForm_SocialSignInWithAllValues_ShouldRenderRegistrationPageWithAllValuesSet() throws Exception {
        TestProviderSignInAttempt socialSignIn = new TestProviderSignInAttemptBuilder()
                .connectionData()
                    .providerId("twitter")
                .userProfile()
                    .email("[email protected]")
                    .firstName("John")
                    .lastName("Smith")
                .build();

        mockMvc.perform(get("/user/register")
                .sessionAttr(ProviderSignInAttempt.SESSION_ATTRIBUTE, socialSignIn)
        )
                .andExpect(status().isOk())
                .andExpect(view().name("user/registrationForm"))
                .andExpect(forwardedUrl("/WEB-INF/jsp/user/registrationForm.jsp"))
                .andExpect(model().attribute("user", allOf(
                        hasProperty("email", is("[email protected]")),
                        hasProperty("firstName", is("John")),
                        hasProperty("lastName", is("Smith")),
                        hasProperty("password", isEmptyOrNullString()),
                        hasProperty("passwordVerification", isEmptyOrNullString()),
                        hasProperty("signInProvider", is("twitter"))
                )));

        verifyZeroInteractions(userServiceMock);
    }
}
           

Submitting The Registration Form

The controller method which processes the submissions of the registration form has the following responsibilities:

  1. It validates the information entered to the registration form. If the information is not valid, it renders the registration form and shows validation error messages to user.
  2. If the email address given by the user is not unique, it renders the registration form and shows an error message to the user.
  3. It creates a new user account by using the UserService interface and logs the created user in.
  4. It persists the connection to a SaaS API provider if user was using social sign in
  5. It redirects user to the front page.

The relevant part of the RegistrationController class looks as follows:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.request.WebRequest;

import javax.validation.Valid;

@Controller
@SessionAttributes("user")
public class RegistrationController {

    private UserService service;

    @Autowired
    public RegistrationController(UserService service) {
        this.service = service;
    }

    @RequestMapping(value ="/user/register", method = RequestMethod.POST)
    public String registerUserAccount(@Valid @ModelAttribute("user") RegistrationForm userAccountData,
                                      BindingResult result,
                                      WebRequest request) throws DuplicateEmailException {
        if (result.hasErrors()) {
            return "user/registrationForm";
        }

        User registered = createUserAccount(userAccountData, result);

        if (registered == null) {
            return "user/registrationForm";
        }
        SecurityUtil.logInUser(registered);
        ProviderSignInUtils.handlePostSignUp(registered.getEmail(), request);

        return "redirect:/";
    }

    private User createUserAccount(RegistrationForm userAccountData, BindingResult result) {
        User registered = null;

        try {
            registered = service.registerNewUserAccount(userAccountData);
        }
        catch (DuplicateEmailException ex) {
            addFieldError(
                    "user",
                    "email",
                    userAccountData.getEmail(),
                    "NotExist.user.email",
                    result);
        }

        return registered;
    }

    private void addFieldError(String objectName, String fieldName, String fieldValue,  String errorCode, BindingResult result) {
        FieldError error = new FieldError(
                objectName,
                fieldName,
                fieldValue,
                false,
                new String[]{errorCode},
                new Object[]{},
                errorCode
        );

        result.addError(error);
    }
}
           

We will write three unit tests for this controller method:

  1. We write a unit test which ensures that the controller method is working properly when validation fails.
  2. We write a unit test which ensures the the controller method is working when the email address isn't unique.
  3. We write a unit test which ensures that the controller method is working properly when the registration is successful.

Let's find out how we can write these unit tests.

測試1:驗證失敗

We can write the first unit test by following these steps:

  1. Create a new TestProviderSignInAttempt object by using the TestProviderSignInAttemptBuilder class. Set the provider id, first name, last name and email address.
  2. Create a new RegistrationForm object by using the RegistrationFormBuilder class. Set the value of the signInProvider field.
  3. Execute a POST request to url '/user/register' by following these steps:
    1. 将請求的内容類型設定為“ application / x-www-form-urlencoded”。
    2. Convert the form object into url encoded bytes and set the outcome of the conversion into the body of the request.
    3. Set the created TestProviderSignInAttempt object to the HTTP session.
    4. Set the form object to the HTTP session.
  4. 驗證是否傳回HTTP狀态代碼200。
  5. 確定渲染視圖的名稱為“ user / registrationForm”。
  6. Ensure that the request is forwarded to url '/WEB-INF/jsp/user/registrationForm.jsp'.
  7. Verify that field values of the model object called 'user' are correct by following these steps:
    1. Verify that the value of the email field is empty or null String.
    2. Verify that the value of the firstName field is empty or null String.
    3. Verify that the value of the lastName field is empty or null String.
    4. Verify that the value of the password field is empty or null String.
    5. Verify that the value of the passwordVerification field is empty or null String.
    6. Verify that the value of the signInProvider field is 'twitter'.
  8. Ensure that the model attribute called 'user' has field errors in email , firstName , and lastName fields.
  9. Verify that the current user is not logged in.
  10. Ensure that no connections were created by using the TestProviderSignInAttempt object.
  11. Verify that the methods of the UserService mock were not called.

我們的單元測試的源代碼如下所示:

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.social.connect.support.TestProviderSignInAttemptBuilder;
import org.springframework.social.connect.web.ProviderSignInAttempt;
import org.springframework.social.connect.web.TestProviderSignInAttempt;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebAppContext.class, UnitTestContext.class})
@WebAppConfiguration
public class RegistrationControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webAppContext;

    @Autowired
    private UserService userServiceMock;

    //The setUp() method is omitted for the sake of clarity

    @Test
    public void registerUserAccount_SocialSignInAndEmptyForm_ShouldRenderRegistrationFormWithValidationErrors() throws Exception {
        TestProviderSignInAttempt socialSignIn = new TestProviderSignInAttemptBuilder()
                .connectionData()
                    .providerId("twitter")
                .userProfile()
                    .email("[email protected]")
                    .firstName("John")
                    .lastName("Smith")
                .build();

        RegistrationForm userAccountData = new RegistrationFormBuilder()
                .signInProvider(SocialMediaService.TWITTER)
                .build();

        mockMvc.perform(post("/user/register")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .content(TestUtil.convertObjectToFormUrlEncodedBytes(userAccountData))
                .sessionAttr(ProviderSignInAttempt.SESSION_ATTRIBUTE, socialSignIn)
                .sessionAttr("user", userAccountData)
        )
                .andExpect(status().isOk())
                .andExpect(view().name("user/registrationForm"))
                .andExpect(forwardedUrl("/WEB-INF/jsp/user/registrationForm.jsp"))
                .andExpect(model().attribute("user", allOf(
                        hasProperty("email", isEmptyOrNullString()),
                        hasProperty("firstName", isEmptyOrNullString()),
                        hasProperty("lastName", isEmptyOrNullString()),
                        hasProperty("password", isEmptyOrNullString()),
                        hasProperty("passwordVerification", isEmptyOrNullString()),
                        hasProperty("signInProvider", is(SocialMediaService.TWITTER))
                )))
                .andExpect(model().attributeHasFieldErrors("user", "email", "firstName", "lastName"));

        assertThat(SecurityContextHolder.getContext()).userIsAnonymous();
        assertThatSignIn(socialSignIn).createdNoConnections();
        verifyZeroInteractions(userServiceMock);
    }
}
           

測試2:從資料庫中找到電子郵件位址

We can write the second unit test by following these steps:

  1. Create a new TestProviderSignInAttempt object by using the TestProviderSignInAttemptBuilder class. Set the provider id, first name, last name and email address.
  2. Create a new RegistrationForm object by using the RegistrationFormBuilder class. Set the values of email , firstName , lastName , and signInProvider fields.
  3. Configure the UserService mock to throw a DuplicateEmailException when its registerNewUserAccount() method is called and the form object is given as a method parameter.
  4. Execute a POST request to url '/user/register' by following these steps:
    1. 将請求的内容類型設定為“ application / x-www-form-urlencoded”。
    2. Convert the form object into url encoded bytes and set the outcome of the conversion into the body of the request.
    3. Set the created TestProviderSignInAttempt object to the HTTP session.
    4. Set the form object to the HTTP session.
  5. 驗證是否傳回HTTP狀态代碼200。
  6. 確定渲染視圖的名稱為“ user / registrationForm”。
  7. Ensure that the request is forwarded to url '/WEB-INF/jsp/user/registrationForm.jsp'.
  8. Verify that field values of the model object called 'user' are correct by following these steps:
    1. Ensure that the value of the email field is '[email protected]'.
    2. Ensure that the value of the firstName field is 'John'.
    3. Ensure that the value of the lastName field is 'Smith'.
    4. Ensure that the value of the password field is empty or null String.
    5. Ensure that the value of the passwordVerification field is empty or null String.
    6. Ensure that the value of the signInProvider field is 'twitter'.
  9. Ensure that the model attribute called 'user' has field error in email field.
  10. Verify that the current user is not logged in.
  11. Ensure that no connections were created by using the TestProviderSignInAttempt object.
  12. Verify that the registerNewUserAccount() method of the UserService mock was called once and that the RegistrationForm object was given as a method parameter.
  13. Verify that the other methods of the UserService interface weren't invoked during the test.

我們的單元測試的源代碼如下所示:

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.social.connect.support.TestProviderSignInAttemptBuilder;
import org.springframework.social.connect.web.ProviderSignInAttempt;
import org.springframework.social.connect.web.TestProviderSignInAttempt;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebAppContext.class, UnitTestContext.class})
@WebAppConfiguration
public class RegistrationControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webAppContext;

    @Autowired
    private UserService userServiceMock;

    //The setUp() method is omitted for the sake of clarity.

    @Test
    public void registerUserAccount_SocialSignInAndEmailExist_ShouldRenderRegistrationFormWithFieldError() throws Exception {
        TestProviderSignInAttempt socialSignIn = new TestProviderSignInAttemptBuilder()
                .connectionData()
                    .providerId("twitter")
                .userProfile()
                    .email("[email protected]")
                    .firstName("John")
                    .lastName("Smith")
                .build();

        RegistrationForm userAccountData = new RegistrationFormBuilder()
                .email("[email protected]")
                .firstName("John")
                .lastName("Smith")
                .signInProvider(SocialMediaService.TWITTER)
                .build();

        when(userServiceMock.registerNewUserAccount(userAccountData)).thenThrow(new DuplicateEmailException(""));

        mockMvc.perform(post("/user/register")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .content(TestUtil.convertObjectToFormUrlEncodedBytes(userAccountData))
                .sessionAttr(ProviderSignInAttempt.SESSION_ATTRIBUTE, socialSignIn)
                .sessionAttr("user", userAccountData)
        )
                .andExpect(status().isOk())
                .andExpect(view().name("user/registrationForm"))
                .andExpect(forwardedUrl("/WEB-INF/jsp/user/registrationForm.jsp"))
                .andExpect(model().attribute("user", allOf(
                        hasProperty("email", is("[email protected]")),
                        hasProperty("firstName", is("John")),
                        hasProperty("lastName", is("Smith")),
                        hasProperty("password", isEmptyOrNullString()),
                        hasProperty("passwordVerification", isEmptyOrNullString()),
                        hasProperty("signInProvider", is(SocialMediaService.TWITTER))
                )))
                .andExpect(model().attributeHasFieldErrors("user", "email"));

        assertThat(SecurityContextHolder.getContext()).userIsAnonymous();
        assertThatSignIn(socialSignIn).createdNoConnections();

        verify(userServiceMock, times(1)).registerNewUserAccount(userAccountData);
        verifyNoMoreInteractions(userServiceMock);
    }
}
           

測試3:注冊成功

We can write the third unit test by following these steps:

  1. Create a new TestProviderSignInAttempt object by using the TestProviderSignInAttemptBuilder class. Set the provider id, first name, last name and email address.
  2. Create a new RegistrationForm object by using the RegistrationFormBuilder class. Set the values of email , firstName , lastName , and signInProvider fields.
  3. Create a new User object by using the UserBuilder class. Set the values of id , email , firstName , lastName , and signInProvider fields.
  4. Configure the UserService mock object to return the created User object when its registerNewUserAccount() method is called and the RegistrationForm object is given as a method parameter.
  5. Execute a POST request to url '/user/register' by following these steps:
    1. 将請求的内容類型設定為“ application / x-www-form-urlencoded”。
    2. Convert the form object into url encoded bytes and set the outcome of the conversion into the body of the request.
    3. Set the created TestProviderSignInAttempt object to the HTTP session.
    4. Set the form object to the HTTP session.
  6. 驗證是否傳回了HTTP狀态代碼302。
  7. Ensure that the request is redirected to url '/'.
  8. Verify that the created user is logged in by using Twitter.
  9. Verify that the TestProviderSignInAttempt object was used to created a connection for a user with email address '[email protected]'.
  10. Verify that the registerNewUserAccount() method of the UserService mock was called once and that the form object was given as a method parameter.
  11. Verify that the other methods of the UserService mock weren't invoked during the test.

我們的單元測試的源代碼如下所示:

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.social.connect.support.TestProviderSignInAttemptBuilder;
import org.springframework.social.connect.web.ProviderSignInAttempt;
import org.springframework.social.connect.web.TestProviderSignInAttempt;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebAppContext.class, UnitTestContext.class})
@WebAppConfiguration
public class RegistrationControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webAppContext;

    @Autowired
    private UserService userServiceMock;

    //The setUp() method is omitted for the sake of clarity.

    @Test
    public void registerUserAccount_SocialSignIn_ShouldCreateNewUserAccountAndRenderHomePage() throws Exception {
        TestProviderSignInAttempt socialSignIn = new TestProviderSignInAttemptBuilder()
                .connectionData()
                    .providerId("twitter")
                .userProfile()
                    .email("[email protected]")
                    .firstName("John")
                    .lastName("Smith")
                .build();

        RegistrationForm userAccountData = new RegistrationFormBuilder()
                .email("[email protected]")
                .firstName("John")
                .lastName("Smith")
                .signInProvider(SocialMediaService.TWITTER)
                .build();

        User registered = new UserBuilder()
                .id(1L)
                .email("[email protected]")
                .firstName("John")
                .lastName("Smith")
                .signInProvider(SocialMediaService.TWITTER)
                .build();

        when(userServiceMock.registerNewUserAccount(userAccountData)).thenReturn(registered);

        mockMvc.perform(post("/user/register")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .content(TestUtil.convertObjectToFormUrlEncodedBytes(userAccountData))
                .sessionAttr(ProviderSignInAttempt.SESSION_ATTRIBUTE, socialSignIn)
                .sessionAttr("user", userAccountData)
        )
                .andExpect(status().isMovedTemporarily())
                .andExpect(redirectedUrl("/"));

        assertThat(SecurityContextHolder.getContext())
                .loggedInUserIs(registered)
                .loggedInUserIsSignedInByUsingSocialProvider(SocialMediaService.TWITTER);
        assertThatSignIn(socialSignIn).createdConnectionForUserId("[email protected]");

        verify(userServiceMock, times(1)).registerNewUserAccount(userAccountData);
        verifyNoMoreInteractions(userServiceMock);
    }
}
           

摘要

We have now written some unit tests for the registration function of our example application. 這篇部落格文章教會了我們四件事:

  1. We learned how we can create the test doubles required by our unit tests.
  2. We learned to emulate social sign in by using the created test double classes.
  3. We learned how we can verify that the connection to the used SaaS API provider is persisted after a new user account has been created for a user who used social sign in.
  4. We learned how we can verify that the user is logged in after a new user account has been created.

The example application of this blog post has many tests which were not covered in this blog post. If you are interested to see them, you can get the example application from Github .

PS This blog post describes one possible approach for writing unit tests to a registration controller which uses Spring Social 1.1.0. If you have any improvement ideas, questions, or feedback about my approach, feel free to leave a comment to this blog post.

Reference:

Adding Social Sign In to a Spring MVC Web Application: Unit Testing from our JCG partner Petri Kainulainen at the Petri Kainulainen blog.

翻譯自: https://www.javacodegeeks.com/2013/12/adding-social-sign-in-to-a-spring-mvc-web-application-unit-testing.html