日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

在Spring MVC Web应用程序中添加社交登录:单元测试

發布時間:2023/12/3 javascript 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 在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類有兩個目的:

  • 呈現注冊表單時,如果用戶正在使用社交登錄創建新的用戶帳戶,則RegistrationController類會預先填充表單字段。表單對象是使用所用SaaS API提供程序提供的信息來預先填充的。 此信息存儲到Connection對象。 控制器類通過調用ProviderSignInUtils類的靜態getConnection()方法來獲取Connection對象。
  • 創建新用戶帳戶后,如果用戶帳戶是使用社交登錄創建的,則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類的源代碼中看到兩件事:

  • getConnection()方法從會話中獲取ProviderSignInAttempt對象。 如果獲取的對象為null,則返回null。 否則,它將調用ProviderSignInAttempt類的getConnection()方法并返回Connection對象。
  • 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提供程序之間的連接的方法。

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

  • 在編寫的每個測試中,我們都必須配置模擬對象的行為。 這意味著我們的測試將更難理解。
  • 我們正在將Spring Social的實現細節泄漏到我們的測試中。 這將使我們的測試難以維護,因為如果實施Spring Social更改,我們的測試可能會被破壞。
  • 顯然,模擬并不是解決此問題的最佳解決方案。 我們必須記住,即使模擬是一種有價值且方便的測試工具, 我們也不應過度使用它 。

    這就產生了一個新問題:

    如果無法進行模擬,那么什么才是正確的工具?

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

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

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

  • 我們需要能夠配置存根返回的Connection <?>對象。
  • 創建新的用戶帳戶后,我們需要驗證連接是否與數據庫保持一致。
  • 我們可以按照以下步驟創建一個實現這些目標的存根:

  • 創建一個TestProviderSignInAttempt類,該類擴展了ProviderSignInAttempt類。
  • 將私有連接字段添加到該類,并將添加的字段的類型設置為Connection <?> 。 該字段包含對用戶和SaaS API提供程序之間的連接的引用。
  • 將私有連接字段添加到該類,并將添加到的字段的類型設置為Set <String> 。 該字段包含持久連接的用戶標識。
  • 向創建的類添加一個將Connection <?>對象作為構造函數參數的構造函數。 通過執行以下步驟來實現構造函數:
  • 調用ProviderSignInAttempt類的構造函數,并將Connection <?>對象作為構造函數參數傳遞。 將其他構造函數參數的值設置為null 。
  • 將作為構造函數參數提供的Connection <?>對象設置為connection字段。
  • 重寫ProviderSignInAttempt類的getConnection()方法,并通過將存儲的對象返回到連接字段來實現它。
  • 重寫ProviderSignInAttempt類的addConnection(String userId)方法,并通過將作為方法參數給出的用戶ID添加到連接集中來實現它。
  • 將公共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;}@Overridepublic Connection<?> getConnection() {return connection;}@Overridevoid addConnection(String userId) {connections.add(userId);}public Set<String> getConnections() {return connections;} }

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

    創建連接類

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

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

  • 創建一個TestConnection類,該類擴展了AbstractConnection類。 AbstractConnection類是基類,它定義了所有連接實現共享的狀態和行為。
  • 將connectionData字段添加到創建的類。 將字段的類型設置為ConnectionData 。 ConnectionData是一個數據傳輸對象,其中包含與使用的SaaS API提供程序的連接的內部狀態。
  • 將userProfile字段添加到創建的類。 將字段的類型設置為UserProfile 。 此類表示所使用的SaaS API提供程序的用戶配置文件,并且包含在不同服務提供程序之間共享的信息。
  • 創建一個將ConnectionData和UserProfile對象作為構造函數參數的構造函數,并按照以下步驟實現它:
  • 調用AbstractConnection類的構造函數,并將ConnectionData對象作為第一個構造函數參數傳遞。 將第二個構造函數參數設置為null 。
  • 設置connectionData字段的值。
  • 設置userProfile字段的值。
  • 重寫AbstractConnection類的fetchUserProfile()方法,并通過將存儲的對象返回到userProfile字段來實現它。
  • 重寫AbstractConnection類的getAPI()方法,并通過返回null來實現它。
  • 重寫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;}@Overridepublic UserProfile fetchUserProfile() {return userProfile;}@Overridepublic Object getApi() {return null;}@Overridepublic ConnectionData createData() {return connectionData;} }

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

    創建構建器類

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

    至此,我們知道

  • TestProviderSignInAttempt類的構造函數將Connection對象作為構造函數參數。
  • TestConnection類的構造函數將ConnectionData和UserProfile對象用作構造函數參數。
  • 這意味著我們可以按照以下步驟創建新的TestProviderSignInAttempt對象:

  • 創建一個新的ConnectionData對象。 ConnectionData類具有單個構造函數,該構造函數將必填字段用作構造函數參數。
  • 創建一個新的UserProfile對象。 我們可以使用UserProfileBuilder類創建新的UserProfile對象。
  • 創建一個新的TestConnection對象,并將創建的ConnectionData和UserProfile對象作為構造函數參數傳遞。
  • 創建一個新的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。 我們可以按照以下步驟創建此類:

  • 創建一個名為TestProviderSignInAttemptBuilder的類。
  • 將創建新的ConnectionData和UserProfile對象所需的所有字段添加到TestProviderSignInAttemptBuilder類。
  • 添加用于設置所添加字段的字段值的方法。 通過執行以下步驟來實現每種方法:
  • 將作為方法參數給出的值設置為正確的字段。
  • 返回對TestProviderSignInAttemptBuilder對象的引用。
  • 將connectionData()和userProfile()方法添加到TestProviderSignInAttemptBuilder類。 這些方法僅返回對TestProviderSignInAttemptBuilder對象的引用,其目的是使我們的API更具可讀性。
  • 將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類

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

  • 創建一個ExampleUserDetailsAssert類,該類擴展了GenericAssert類。 提供以下類型參數:
  • 第一個類型參數是自定義斷言的類型。 將此類型參數的值設置為ExampleUserDetailsAssert 。
  • 第二個類型參數是實際值對象的類型。 將此類型參數的值設置為ExampleUserDetails。
  • 向創建的類添加一個私有構造函數。 此構造函數將ExampleUserDetails對象作為構造函數參數。 通過調用超類的構造函數并將以下對象作為構造函數參數傳遞來實現控制器:
  • 第一個構造函數參數是一個Class對象,它指定自定義斷言類的類型。 將此構造函數參數的值設置為ExampleUserDetailsAssert.class 。
  • 第二個構造函數參數是實際值對象。 將作為構造函數參數給出的對象傳遞給超類的構造函數。
  • 將靜態assertThat()方法添加到創建的類。 此方法將ExampleUserDetails對象作為方法參數。 通過創建一個新的ExampleUserDetailsAssert對象來實現此方法。
  • 將hasFirstName()方法添加到ExampleUserDetailsAssert類。 此方法將String對象作為方法參數,并返回ExampleUserDetailsAssert對象。 我們可以通過執行以下步驟來實現此方法:
  • 通過調用GenericAssert類的isNotNull()方法,確保實際的ExampleUserDetails對象不為null。
  • 驗證實際的名字是否等于作為方法參數給出的期望的名字。
  • 返回對ExampleUserDetailsAssert對象的引用。
  • 將一個hasId()方法添加到ExampleUserDetailsAssert類。 此方法將Long對象作為方法參數,并返回ExampleUserDetailsAssert對象。 我們可以通過執行以下步驟來實現此方法:
  • 通過調用GenericAssert類的isNotNull()方法,確保實際的ExampleUserDetails對象不為null。
  • 驗證實際ID是否等于作為方法參數給出的預期ID。
  • 返回對ExampleUserDetailsAssert對象的引用。
  • 將hasLastName()方法添加到ExampleUserDetailsAssert類。 此方法將String對象作為方法參數,并返回ExampleUserDetailsAssert對象。 我們可以通過執行以下步驟來實現此方法:
  • 通過調用GenericAssert類的isNotNull()方法,確保實際的ExampleUserDetails對象不為null。
  • 驗證實際的姓氏是否等于作為方法參數給出的期望的姓氏。
  • 返回對ExampleUserDetailsAssert對象的引用。
  • 將hasPassword()方法添加到ExampleUserDetailsAssert類。 此方法將String對象作為方法參數,并返回ExampleUserDetailsAssert對象。 我們可以通過執行以下步驟來實現此方法:
  • 通過調用GenericAssert類的isNotNull()方法,確保實際的ExampleUserDetails對象不為null。
  • 驗證實際密碼是否等于作為方法參數給出的預期密碼。
  • 返回對ExampleUserDetailsAssert對象的引用。
  • 將一個hasUsername()方法添加到ExampleUserDetailsAssert類。 此方法將String對象作為方法參數,并返回ExampleUserDetailsAssert對象。 我們可以通過執行以下步驟來實現此方法:
  • 通過調用GenericAssert類的isNotNull()方法,確保實際的ExampleUserDetails對象不為null。
  • 驗證實際用戶名是否等于作為方法參數給出的預期用戶名。
  • 返回對ExampleUserDetailsAssert對象的引用。
  • 將isActive()方法添加到ExampleUserDetailsAssert類。 此方法不帶方法參數,它返回ExampleUserDetailsAssert對象。
  • 通過調用GenericAssert類的isNotNull()方法,確保實際的ExampleUserDetails對象不為null。
  • 驗證其信息存儲在ExampleUserDetails對象中的用戶是否處于活動狀態。
  • 返回對ExampleUserDetailsAssert對象的引用。
  • 將isRegisteredUser()方法添加到ExampleUserDetailsAssert類。 此方法不帶方法參數,它返回ExampleUserDetailsAssert對象。
  • 通過調用GenericAssert類的isNotNull()方法,確保實際的ExampleUserDetails對象不為null。
  • 驗證其信息存儲在ExampleUserDetails對象中的用戶是注冊用戶。
  • 返回對ExampleUserDetailsAssert對象的引用。
  • 將isRegisteredByUsingFormRegistration()方法添加到ExampleUserDetailsAssert類。 此方法返回ExampleUserDetailsAssert對象。 我們可以通過執行以下步驟來實現此方法:
  • 通過調用GenericAssert類的isNotNull()方法,確保實際的ExampleUserDetails對象不為null。
  • 驗證socialSignInProvider字段的值為空。
  • 返回對ExampleUserDetailsAssert對象的引用。
  • 將isSignedInByUsingSocialSignInProvider()方法添加到ExampleUserDetailsAssert類。 此方法將SocialMediaService枚舉作為方法參數,并返回ExampleUserDetailsAssert對象。 我們可以通過執行以下步驟來實現此方法:
  • 通過調用GenericAssert類的isNotNull()方法,確保實際的ExampleUserDetails對象不為null。
  • 驗證socialSignInProvider的值等于作為方法參數給出的預期的SocialMediaService枚舉。
  • 返回對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類

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

  • 創建一個SecurityContextAssert類,該類擴展了GenericAssert類。 提供以下類型參數:
  • 第一個類型參數是自定義斷言的類型。 將此類型參數的值設置為SecurityContextAssert 。
  • 第二個類型參數是實際值對象的類型。 將此類型參數的值設置為SecurityContext 。
  • 向創建的類添加一個私有構造函數。 該構造函數將SecurityContext對象作為構造函數參數。 通過調用超類的構造函數并將以下對象作為構造函數參數傳遞來實現控制器:
  • 第一個構造函數參數是一個Class對象,它指定自定義斷言類的類型。 將此構造函數參數的值設置為SecurityContextAssert.class 。
  • 第二個構造函數參數是實際值對象。 將作為構造函數參數給出的對象傳遞給超類的構造函數。
  • 將靜態assertThat()方法添加到創建的類。 此方法將SecurityContext對象作為方法參數。 通過創建一個新的SecurityContextAssert對象來實現此方法。
  • 將userIsAnonymous()方法添加到SecurityContextAssert類,并通過以下步驟實現它:
  • 通過調用GenericAssert類的isNotNull()方法,確保實際的SecurityContext對象不為null。
  • 從SecurityContext獲取Authentication對象,并確保它為null 。
  • 返回對SecurityContextAssert對象的引用。
  • 將一個loggingInUserIs()方法添加到SecurityContextAssert類。 此方法將User對象作為方法參數,并返回SecurityContextAssert對象。 我們可以通過執行以下步驟來實現此方法:
  • 通過調用GenericAssert類的isNotNull()方法,確保實際的SecurityContext對象不為null。
  • 從SecurityContext獲取ExampleUserDetails對象,并確保它不為null。
  • 確保ExampleUserDetails對象的信息與User對象的信息相等。
  • 返回對SecurityContextAssert對象的引用。
  • 將一個loggingInUserHasPassword()方法添加到SecurityContextAssert類。 此方法將String對象作為方法參數,并返回SecurityContextAssert對象。 我們可以通過執行以下步驟來實現此方法:
  • 通過調用GenericAssert類的isNotNull()方法,確保實際的SecurityContext對象不為null。
  • 從SecurityContext獲取ExampleUserDetails對象,并確保它不為null。
  • 確保ExampleUserDetails對象的密碼字段等于作為方法參數給出的密碼。
  • 返回對SecurityContextAssert對象的引用。
  • 將一個loggingInUserIsRegisteredByUsingNormalRegistration()方法添加到SecurityContextAssert類,并通過以下步驟實現它:
  • 通過調用GenericAssert類的isNotNull()方法,確保實際的SecurityContext對象不為null。
  • 從SecurityContext獲取ExampleUserDetails對象,并確保它不為null。
  • 確保使用普通注冊創建用戶帳戶。
  • 返回對SecurityContextAssert對象的引用。
  • 將一個loggingInUserIsSignedInByUsingSocialProvider()方法添加到SecurityContextAssert類。 此方法將SocialMediaService枚舉作為方法參數,并返回SecurityContextAssert對象。 我們可以通過執行以下步驟來實現此方法:
  • 通過調用GenericAssert類的isNotNull()方法,確保實際的SecurityContext對象不為null。
  • 從SecurityContext獲取ExampleUserDetails對象,并確保它不為null。
  • 確保通過使用作為方法參數給出的SociaMediaService創建用戶帳戶。
  • 返回對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類

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

  • 創建一個TestProviderSignInAttemptAssert類,該類擴展了GenericAssert類。 提供以下類型參數:
  • 第一個類型參數是自定義斷言的類型。 將此類型參數的值設置為TestProviderSignInAttemptAssert 。
  • 第二個類型參數是實際值對象的類型。 將此類型參數的值設置為TestProviderSignInAttempt 。
  • 向創建的類添加一個私有構造函數。 此構造函數將TestProviderSignInAttempt對象作為構造函數參數。 通過調用超類的構造函數并將以下對象作為構造函數參數傳遞來實現控制器:
  • 第一個構造函數參數是一個Class對象,它指定自定義斷言類的類型。 將此構造函數參數的值設置為TestProviderSignInAttemptAssert.class 。
  • 第二個構造函數參數是實際值對象。 將作為構造函數參數給出的對象傳遞給超類的構造函數。
  • 將靜態assertThatSignIn()方法添加到創建的類。 此方法將TestProviderSignInAttempt對象作為方法參數。 通過創建一個新的TestProviderSignInAttemptAssert對象來實現此方法。
  • 向創建的類添加一個createdNoConnections()方法。 此方法不帶方法參數,并且返回對TestProviderSignInAttemptAssert對象的引用。 我們可以通過執行以下步驟來實現此方法:
  • 通過調用GenericAssert類的isNotNull()方法,確保實際的TestProviderSignInAttempt對象不為null。
  • 確保實際的TestProviderSignInAttempt對象未創建任何連接。
  • 返回對TestProviderSignInAttemptAssert對象的引用。
  • 向創建的類中添加一個createdConnectionForUserId()方法。 此方法將String對象作為方法參數,并返回對TestProviderSignInAttempt對象的引用。 我們可以通過執行以下步驟來實現此方法:
  • 通過調用GenericAssert類的isNotNull()方法,確保實際的TestProviderSignInAttempt對象不為null。
  • 確保為用戶ID為方法參數的用戶創建了連接。
  • 返回對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層的應用程序上下文配置類并為單元測試創??建一個新的應用程序上下文配置類來做到這一點。

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

  • 創建一個名為UnitTestContext的類。
  • 用@Configuration注釋對創建的類進行注釋。
  • 向創建的類中添加messageSource()方法,并使用@Bean注釋對方法進行注釋。 通過執行以下步驟配置MessageSource bean:
  • 創建一個新的ResourceBundleMessageSource對象。
  • 設置消息文件的基本名稱,并確保如果未找到消息,則返回其代碼。
  • 返回創建的對象。
  • 將userService()方法添加到創建的類中,并使用@Bean注釋對該方法進行注釋。 通過執行以下步驟配置UserService模擬對象:
  • 調用Mockito類的靜態嘲笑()方法,并將UserService.class作為方法參數傳遞。
  • 返回創建的對象。
  • 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 {@Beanpublic MessageSource messageSource() {ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();messageSource.setBasename("i18n/messages");messageSource.setUseCodeAsDefaultMessage(true);return messageSource;}@Beanpublic UserService userService() {return mock(UserService.class);} }

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

  • 使用@RunWith注釋對測試類進行注釋,并確保通過使用SpringUnit4ClassRunner執行我們的測試。
  • 使用@ContextConfiguration批注對類進行批注,并確保使用正確的配置類。 在我們的例子中,正確的配置類是: WebAppContext和UnitTestContext 。
  • 用@WebAppConfiguration批注對類進行批注。 此批注確保加載的應用程序上下文是WebApplicationContext 。
  • 將MockMvc字段添加到測試類。
  • 將WebApplicationContext字段添加到類中,并使用@Autowired批注對其進行批注。
  • 將UserService字段添加到測試類,并使用@Autowired批注對其進行批注。
  • 將setUp()方法添加到測試類,并使用@Before注釋對方法進行注釋。 這樣可以確保在每個測試方法之前調用該方法。 通過執行以下步驟來實現此方法:
  • 通過調用Mockito類的靜態reset()方法并將經過重置的模擬作為方法參數傳遞來重置UserService模擬。
  • 通過使用MockMvcBuilders類創建一個新的MockMvc對象。
  • 運行我們的測試時,請確保從SecurityContext中沒有找到Authentication對象。 我們可以按照以下步驟進行操作:
  • 通過調用SecurityContextHolder類的靜態getContext()方法來獲取對SecurityContext對象的引用。
  • 通過調用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;@Autowiredprivate WebApplicationContext webAppContext;@Autowiredprivate UserService userServiceMock;@Beforepublic 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:提??交普通注冊表

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

  • 執行GET請求以發送url'/ user / register'。
  • 確保返回HTTP狀態代碼200。
  • 驗證渲染視圖的名稱為“ user / registrationForm”。
  • Verify that the request is forwarded to url '/WEB-INF/jsp/user/registrationForm.jsp'.
  • Ensure that all fields of the model attribute called 'user' are either null or empty.
  • 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;@Autowiredprivate WebApplicationContext webAppContext;@Autowiredprivate UserService userServiceMock;//The setUp() method is omitted for the sake of clarity@Testpublic 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:

  • Create a new TestProviderSignInAttempt object by using the TestProviderSignInAttemptBuilder class. Set the provider id, first name, last name and email address.
  • Execute a GET request to url '/user/register' and set the created TestProviderSignInAttempt object to the HTTP session.
  • 確保返回HTTP狀態代碼200。
  • Verify that the name of the rendered view is 'user/registrationForm'.
  • Ensure that the request is forwarded to url '/WEB-INF/jsp/user/registrationForm.jsp'.
  • Verify that the fields of the model object called 'user' are pre-populated by using the information contained by the TestProviderSignInAttempt object. 我們可以按照以下步驟進行操作:
  • Ensure that the value of the email field is 'john.smith@gmail.com'.
  • Ensure that the value of the firstName field is 'John'.
  • Ensure that the value of the lastName field is 'Smith'.
  • Ensure that the value of the password field is empty or null String.
  • Ensure that the value of the passwordVerification field is empty or null String.
  • Ensure that the value of the signInProvider field is 'twitter'.
  • 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;@Autowiredprivate WebApplicationContext webAppContext;@Autowiredprivate UserService userServiceMock;//The setUp() method is omitted for the sake of clarity@Testpublic void showRegistrationForm_SocialSignInWithAllValues_ShouldRenderRegistrationPageWithAllValuesSet() throws Exception {TestProviderSignInAttempt socialSignIn = new TestProviderSignInAttemptBuilder().connectionData().providerId("twitter").userProfile().email("john.smith@gmail.com").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("john.smith@gmail.com")),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:

  • 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.
  • If the email address given by the user is not unique, it renders the registration form and shows an error message to the user.
  • It creates a new user account by using the UserService interface and logs the created user in.
  • It persists the connection to a SaaS API provider if user was using social sign in
  • 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;@Autowiredpublic 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:

  • We write a unit test which ensures that the controller method is working properly when validation fails.
  • We write a unit test which ensures the the controller method is working when the email address isn't unique.
  • 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:

  • Create a new TestProviderSignInAttempt object by using the TestProviderSignInAttemptBuilder class. Set the provider id, first name, last name and email address.
  • Create a new RegistrationForm object by using the RegistrationFormBuilder class. Set the value of the signInProvider field.
  • Execute a POST request to url '/user/register' by following these steps:
  • 將請求的內容類型設置為“ application / x-www-form-urlencoded”。
  • Convert the form object into url encoded bytes and set the outcome of the conversion into the body of the request.
  • Set the created TestProviderSignInAttempt object to the HTTP session.
  • Set the form object to the HTTP session.
  • 驗證是否返回HTTP狀態代碼200。
  • 確保渲染視圖的名稱為“ user / registrationForm”。
  • Ensure that the request is forwarded to url '/WEB-INF/jsp/user/registrationForm.jsp'.
  • Verify that field values of the model object called 'user' are correct by following these steps:
  • Verify that the value of the email field is empty or null String.
  • Verify that the value of the firstName field is empty or null String.
  • Verify that the value of the lastName field is empty or null String.
  • Verify that the value of the password field is empty or null String.
  • Verify that the value of the passwordVerification field is empty or null String.
  • Verify that the value of the signInProvider field is 'twitter'.
  • Ensure that the model attribute called 'user' has field errors in email , firstName , and lastName fields.
  • Verify that the current user is not logged in.
  • Ensure that no connections were created by using the TestProviderSignInAttempt object.
  • 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;@Autowiredprivate WebApplicationContext webAppContext;@Autowiredprivate UserService userServiceMock;//The setUp() method is omitted for the sake of clarity@Testpublic void registerUserAccount_SocialSignInAndEmptyForm_ShouldRenderRegistrationFormWithValidationErrors() throws Exception {TestProviderSignInAttempt socialSignIn = new TestProviderSignInAttemptBuilder().connectionData().providerId("twitter").userProfile().email("john.smith@gmail.com").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:

  • Create a new TestProviderSignInAttempt object by using the TestProviderSignInAttemptBuilder class. Set the provider id, first name, last name and email address.
  • Create a new RegistrationForm object by using the RegistrationFormBuilder class. Set the values of email , firstName , lastName , and signInProvider fields.
  • Configure the UserService mock to throw a DuplicateEmailException when its registerNewUserAccount() method is called and the form object is given as a method parameter.
  • Execute a POST request to url '/user/register' by following these steps:
  • 將請求的內容類型設置為“ application / x-www-form-urlencoded”。
  • Convert the form object into url encoded bytes and set the outcome of the conversion into the body of the request.
  • Set the created TestProviderSignInAttempt object to the HTTP session.
  • Set the form object to the HTTP session.
  • 驗證是否返回HTTP狀態代碼200。
  • 確保渲染視圖的名稱為“ user / registrationForm”。
  • Ensure that the request is forwarded to url '/WEB-INF/jsp/user/registrationForm.jsp'.
  • Verify that field values of the model object called 'user' are correct by following these steps:
  • Ensure that the value of the email field is 'john.smith@gmail.com'.
  • Ensure that the value of the firstName field is 'John'.
  • Ensure that the value of the lastName field is 'Smith'.
  • Ensure that the value of the password field is empty or null String.
  • Ensure that the value of the passwordVerification field is empty or null String.
  • Ensure that the value of the signInProvider field is 'twitter'.
  • Ensure that the model attribute called 'user' has field error in email field.
  • Verify that the current user is not logged in.
  • Ensure that no connections were created by using the TestProviderSignInAttempt object.
  • Verify that the registerNewUserAccount() method of the UserService mock was called once and that the RegistrationForm object was given as a method parameter.
  • 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;@Autowiredprivate WebApplicationContext webAppContext;@Autowiredprivate UserService userServiceMock;//The setUp() method is omitted for the sake of clarity.@Testpublic void registerUserAccount_SocialSignInAndEmailExist_ShouldRenderRegistrationFormWithFieldError() throws Exception {TestProviderSignInAttempt socialSignIn = new TestProviderSignInAttemptBuilder().connectionData().providerId("twitter").userProfile().email("john.smith@gmail.com").firstName("John").lastName("Smith").build();RegistrationForm userAccountData = new RegistrationFormBuilder().email("john.smith@gmail.com").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("john.smith@gmail.com")),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:

  • Create a new TestProviderSignInAttempt object by using the TestProviderSignInAttemptBuilder class. Set the provider id, first name, last name and email address.
  • Create a new RegistrationForm object by using the RegistrationFormBuilder class. Set the values of email , firstName , lastName , and signInProvider fields.
  • Create a new User object by using the UserBuilder class. Set the values of id , email , firstName , lastName , and signInProvider fields.
  • 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.
  • Execute a POST request to url '/user/register' by following these steps:
  • 將請求的內容類型設置為“ application / x-www-form-urlencoded”。
  • Convert the form object into url encoded bytes and set the outcome of the conversion into the body of the request.
  • Set the created TestProviderSignInAttempt object to the HTTP session.
  • Set the form object to the HTTP session.
  • 驗證是否返回了HTTP狀態代碼302。
  • Ensure that the request is redirected to url '/'.
  • Verify that the created user is logged in by using Twitter.
  • Verify that the TestProviderSignInAttempt object was used to created a connection for a user with email address 'john.smith@gmail.com'.
  • Verify that the registerNewUserAccount() method of the UserService mock was called once and that the form object was given as a method parameter.
  • 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;@Autowiredprivate WebApplicationContext webAppContext;@Autowiredprivate UserService userServiceMock;//The setUp() method is omitted for the sake of clarity.@Testpublic void registerUserAccount_SocialSignIn_ShouldCreateNewUserAccountAndRenderHomePage() throws Exception {TestProviderSignInAttempt socialSignIn = new TestProviderSignInAttemptBuilder().connectionData().providerId("twitter").userProfile().email("john.smith@gmail.com").firstName("John").lastName("Smith").build();RegistrationForm userAccountData = new RegistrationFormBuilder().email("john.smith@gmail.com").firstName("John").lastName("Smith").signInProvider(SocialMediaService.TWITTER).build();User registered = new UserBuilder().id(1L).email("john.smith@gmail.com").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("john.smith@gmail.com");verify(userServiceMock, times(1)).registerNewUserAccount(userAccountData);verifyNoMoreInteractions(userServiceMock);} }

    摘要

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

  • We learned how we can create the test doubles required by our unit tests.
  • We learned to emulate social sign in by using the created test double classes.
  • 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.
  • 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

    總結

    以上是生活随笔為你收集整理的在Spring MVC Web应用程序中添加社交登录:单元测试的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。