javascript
在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庫可幫助我們在不終止測試方法執行的情況下捕獲異常,并使捕獲的異??捎糜谶M一步分析。 由于我們已經添加了“ 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類有兩個目的:
如果我們想了解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類的源代碼中看到兩件事:
顯然,為了為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提供程序之間的連接的方法。
首先想到的是模擬這些依賴關系。 盡管這似乎是一個好主意,但是這種方法有兩個問題:
顯然,模擬并不是解決此問題的最佳解決方案。 我們必須記住,即使模擬是一種有價值且方便的測試工具, 我們也不應過度使用它 。
這就產生了一個新問題:
如果無法進行模擬,那么什么才是正確的工具?
這個問題的答案可以從Martin Fowler的一篇文章中找到。 在本文中,馬丁·福勒(Martin Fowler)指定了一個稱為存根的測試雙精度,如下所示:
存根提供對測試過程中進行的呼叫的固定答復,通常通常根本不響應為測試編程的內容。 存根還可以記錄有關呼叫的信息,例如,電子郵件網關存根可以記住“已發送”的消息,或者僅記住“已發送”的消息數量。
使用存根非常有意義,因為我們對兩件事感興趣:
我們可以按照以下步驟創建一個實現這些目標的存根:
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類的源代碼如下所示:
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對象:
創建一個新的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類的源代碼如下所示:
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類的源代碼如下所示:
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類的源代碼如下所示:
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類的源代碼如下所示:
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類的源代碼如下所示:
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);} }接下來要做的是配置單元測試。 我們可以按照以下步驟進行操作:
我們的單元測試類的源代碼如下所示:
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:提??交普通注冊表
我們可以按照以下步驟編寫第一個單元測試:
我們的單元測試的源代碼如下所示:
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:
我們的單元測試的源代碼如下所示:
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:
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:
Let's find out how we can write these unit tests.
測試1:驗證失敗
We can write the first unit test by following these steps:
我們的單元測試的源代碼如下所示:
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:
我們的單元測試的源代碼如下所示:
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:
我們的單元測試的源代碼如下所示:
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. 這篇博客文章教會了我們四件事:
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.
翻譯自: https://www.javacodegeeks.com/2013/12/adding-social-sign-in-to-a-spring-mvc-web-application-unit-testing.html
總結
以上是生活随笔為你收集整理的在Spring MVC Web应用程序中添加社交登录:单元测试的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 苹果屏幕旋转在哪关闭
- 下一篇: 大型布线:Java云应用程序缺少的技术