Repository: jhipster/generator-jhipster (ts)

Issue:
Test fails with Social Login and MongoDB
##### **Overview of the issue**

I just created a monolithic application with social login and MongoDB. After the application is succesfully created, if run ./mvnw clean package it return 2 failing tests and 8 error test, all from SocialServiceIntTest.java

<details>
<summary>Maven ouput</summary>
<pre>
Failed tests: 
  SocialServiceIntTest.testCreateSocialUserShouldCreateUserIfNotExist:149 
Expecting Optional to contain a value but was empty.
  SocialServiceIntTest.testCreateSocialUserShouldNotCreateUserIfEmailAlreadyExist:306 expected:<1[2]L> but was:<1[3]L>
Tests in error: 
  SocialServiceIntTest.testCreateSocialUserShouldCreateActivatedUserWithRoleUserAndPassword:192 » NoSuchElement
  SocialServiceIntTest.testCreateSocialUserShouldCreateSocialConnection:282 » NoSuchElement
  SocialServiceIntTest.testCreateSocialUserShouldCreateUserWithExactLangKey:216 » NoSuchElement
  SocialServiceIntTest.testCreateSocialUserShouldCreateUserWithLoginSameAsEmailIfNotTwitter:237 » NoSuchElement
  SocialServiceIntTest.testCreateSocialUserShouldCreateUserWithSocialInformation:169 » NoSuchElement
  SocialServiceIntTest.testCreateSocialUserShouldCreateUserWithSocialLoginWhenIsTwitter:258 » NoSuchElement
  SocialServiceIntTest.testCreateSocialUserShouldNotChangeUserIfEmailAlreadyExist:332 » NoSuchElement
  SocialServiceIntTest.testCreateSocialUserShouldSendRegistrationValidationEmail:358 » NoSuchElement

Tests run: 177, Failures: 2, Errors: 8, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 45.445 s
[INFO] Finished at: 2018-01-10T12:38:15+01:00
[INFO] Final Memory: 55M/538M
[INFO] ------------------------------------------------------------------------
</pre>
</details>


##### **Motivation for or Use Case**

I'd like to use social login in my new application.

##### **Reproduce the error**

Create a new application with the options described below. Then run ./mvnw clean package.

##### **JHipster Version(s)**

```
tierdeck@0.0.0 /home/javier/sts-workspace/tierdeck
└── generator-jhipster@4.13.3 

```


##### **JHipster configuration, a `.yo-rc.json` file generated in the root folder**


<details>
<summary>.yo-rc.json file</summary>
<pre>
{
  "generator-jhipster": {
    "promptValues": {
      "packageName": "com.tierdeck.www",
      "nativeLanguage": "en"
    },
    "jhipsterVersion": "4.13.3",
    "baseName": "tierdeck",
    "packageName": "com.tierdeck.www",
    "packageFolder": "com/tierdeck/www",
    "serverPort": "8080",
    "authenticationType": "jwt",
    "cacheProvider": "ehcache",
    "enableHibernateCache": false,
    "websocket": false,
    "databaseType": "mongodb",
    "devDatabaseType": "mongodb",
    "prodDatabaseType": "mongodb",
    "searchEngine": "elasticsearch",
    "messageBroker": false,
    "serviceDiscoveryType": "eureka",
    "buildTool": "maven",
    "enableSocialSignIn": true,
    "enableSwaggerCodegen": false,
    "jwtSecretKey": "replaced-by-jhipster-info",
    "clientFramework": "angularX",
    "useSass": false,
    "clientPackageManager": "yarn",
    "applicationType": "monolith",
    "testFrameworks": [],
    "jhiPrefix": "jhi",
    "enableTranslation": true,
    "nativeLanguage": "en",
    "languages": [
      "en",
      "es"
    ]
  }
}
</pre>
</details>


##### **JDL for the Entity configuration(s) `entityName.json` files generated in the `.jhipster` directory**

<details>
<summary>JDL entity definitions</summary>

<pre>
</pre>
</details>


##### **Environment and Tools**

java version "1.8.0_102"
Java(TM) SE Runtime Environment (build 1.8.0_102-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode)

git version 2.11.0

node: v8.9.4

npm: 5.5.1

bower: 1.8.2

gulp:
[12:39:25] CLI version 1.2.2

yeoman: 1.8.5

yarn: 1.3.2

Docker version 1.13.1, build 092cba3

docker-compose version 1.8.0, build unknown

##### **Browsers and Operating System**

Ubuntu 17.04

- [X] Checking this box is mandatory (this is just to show you read everything)


Pull request description:
fix tests for mongo+social
Fix #6968
- clear cache and delete users between tests in SocialServiceIntTest
- factor out cacheManagerIsAvailable into a server generator variable

---

- [ ] [Travis tests](https://travis-ci.org/jhipster/generator-jhipster/pull_requests) are green
- [X] Tests are added where necessary
- [X] Documentation is added/updated where necessary
- [X] Coding Rules & Commit Guidelines as per our [CONTRIBUTING.md document](https://github.com/jhipster/generator-jhipster/blob/master/CONTRIBUTING.md) are followed


Patch:
diff --git a/generators/server/index.js b/generators/server/index.js
index f9ca0737d4..44be4ffefd 100644
--- a/generators/server/index.js
+++ b/generators/server/index.js
@@ -165,6 +165,7 @@ module.exports = class extends BaseGenerator {
 
                 this.cacheProvider = this.config.get('cacheProvider') || this.config.get('hibernateCache') || 'no';
                 this.enableHibernateCache = this.config.get('enableHibernateCache') || (this.config.get('hibernateCache') !== undefined && this.config.get('hibernateCache') !== 'no');
+                this.cacheManagerIsAvailable = ['ehcache', 'hazelcast', 'infinispan'].includes(this.cacheProvider) || this.applicationType === 'gateway';
 
                 this.databaseType = this.config.get('databaseType');
                 if (this.databaseType === 'mongodb') {
diff --git a/generators/server/templates/src/main/java/package/repository/UserRepository.java.ejs b/generators/server/templates/src/main/java/package/repository/UserRepository.java.ejs
index 0ee217d5e3..00aa741fc3 100644
--- a/generators/server/templates/src/main/java/package/repository/UserRepository.java.ejs
+++ b/generators/server/templates/src/main/java/package/repository/UserRepository.java.ejs
@@ -16,12 +16,6 @@
  See the License for the specific language governing permissions and
  limitations under the License.
 -%>
-<%_
-let cacheManagerIsAvailable = false;
-if (['ehcache', 'hazelcast', 'infinispan'].includes(cacheProvider) || applicationType === 'gateway') {
-    cacheManagerIsAvailable = true;
-}
-_%>
 package <%=packageName%>.repository;
 <%_ if (databaseType === 'cassandra') { _%>
 
diff --git a/generators/server/templates/src/main/java/package/service/SocialService.java.ejs b/generators/server/templates/src/main/java/package/service/SocialService.java.ejs
index 386b061cef..e0f13f4f00 100644
--- a/generators/server/templates/src/main/java/package/service/SocialService.java.ejs
+++ b/generators/server/templates/src/main/java/package/service/SocialService.java.ejs
@@ -31,6 +31,9 @@ import org.apache.commons.lang3.RandomStringUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+<%_ if (cacheManagerIsAvailable === true) { _%>
+import org.springframework.cache.CacheManager;
+<%_ } _%>
 import org.springframework.security.crypto.password.PasswordEncoder;
 import org.springframework.social.connect.Connection;
 import org.springframework.social.connect.ConnectionRepository;
@@ -38,10 +41,7 @@ import org.springframework.social.connect.UserProfile;
 import org.springframework.social.connect.UsersConnectionRepository;
 import org.springframework.stereotype.Service;
 
-import java.util.HashSet;
-import java.util.Locale;
-import java.util.Optional;
-import java.util.Set;
+import java.util.*;
 
 @Service
 public class SocialService {
@@ -61,10 +61,14 @@ public class SocialService {
 
     private final UserSearchRepository userSearchRepository;
     <%_ } _%>
+    <%_ if (cacheManagerIsAvailable === true) { _%>
+
+    private final CacheManager cacheManager;
+    <%_ } _%>
 
     public SocialService(UsersConnectionRepository usersConnectionRepository, AuthorityRepository authorityRepository,
             PasswordEncoder passwordEncoder, UserRepository userRepository,
-            MailService mailService<% if (searchEngine === 'elasticsearch') { %>, UserSearchRepository userSearchRepository<% } %>) {
+            MailService mailService<% if (searchEngine === 'elasticsearch') { %>, UserSearchRepository userSearchRepository<% } %><% if (cacheManagerIsAvailable === true) { %>, CacheManager cacheManager<% } %>) {
 
         this.usersConnectionRepository = usersConnectionRepository;
         this.authorityRepository = authorityRepository;
@@ -74,6 +78,9 @@ public class SocialService {
         <%_ if (searchEngine === 'elasticsearch') { _%>
         this.userSearchRepository = userSearchRepository;
         <%_ } _%>
+        <%_ if (cacheManagerIsAvailable === true) { _%>
+        this.cacheManager = cacheManager;
+        <%_ } _%>
     }
 
     public void deleteUserSocialConnection(String login) {
@@ -139,6 +146,10 @@ public class SocialService {
         <%_ if (searchEngine === 'elasticsearch') { _%>
         userSearchRepository.save(newUser);
         <%_ } _%>
+        <%_ if (cacheManagerIsAvailable === true) { _%>
+        Objects.requireNonNull(cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE)).evict(newUser.getLogin());
+        Objects.requireNonNull(cacheManager.getCache(UserRepository.USERS_BY_EMAIL_CACHE)).evict(newUser.getEmail());
+        <%_ } _%>
         return userRepository.save(newUser);
     }
 
diff --git a/generators/server/templates/src/main/java/package/service/UserService.java.ejs b/generators/server/templates/src/main/java/package/service/UserService.java.ejs
index 37bed81ded..413508e1b2 100644
--- a/generators/server/templates/src/main/java/package/service/UserService.java.ejs
+++ b/generators/server/templates/src/main/java/package/service/UserService.java.ejs
@@ -16,12 +16,6 @@
  See the License for the specific language governing permissions and
  limitations under the License.
 -%>
-<%_
-let cacheManagerIsAvailable = false;
-if (['ehcache', 'hazelcast', 'infinispan'].includes(cacheProvider) || applicationType === 'gateway') {
-    cacheManagerIsAvailable = true;
-}
-_%>
 package <%=packageName%>.service;
 
 <%_ if (databaseType === 'sql' || databaseType === 'mongodb' || databaseType === 'couchbase') { _%>


Test patch:
diff --git a/generators/server/templates/src/test/java/package/service/SocialServiceIntTest.java.ejs b/generators/server/templates/src/test/java/package/service/SocialServiceIntTest.java.ejs
index 77c3c111ca..468bf31197 100644
--- a/generators/server/templates/src/test/java/package/service/SocialServiceIntTest.java.ejs
+++ b/generators/server/templates/src/test/java/package/service/SocialServiceIntTest.java.ejs
@@ -34,6 +34,9 @@ import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
+<%_ if (cacheManagerIsAvailable === true) { _%>
+import org.springframework.cache.CacheManager;
+<%_ } _%>
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.test.context.SpringBootTest;
 import org.springframework.security.crypto.password.PasswordEncoder;
@@ -68,6 +71,11 @@ public class SocialServiceIntTest {
     @Autowired
     private UserSearchRepository userSearchRepository;
 
+    <%_ } _%>
+    <%_ if (cacheManagerIsAvailable === true) { _%>
+    @Autowired
+    private CacheManager cacheManager;
+
     <%_ } _%>
 
     @Mock
@@ -86,13 +94,18 @@ public class SocialServiceIntTest {
         <%_ if (databaseType === 'couchbase') { _%>
         mockAuthentication();
         <%_ } _%>
+        userRepository.deleteAll();
+        <%_ if (cacheManagerIsAvailable === true) { _%>
+        cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).clear();
+        cacheManager.getCache(UserRepository.USERS_BY_EMAIL_CACHE).clear();
+        <%_ } _%>
         MockitoAnnotations.initMocks(this);
         doNothing().when(mockMailService).sendSocialRegistrationValidationEmail(any(), anyString());
         doNothing().when(mockConnectionRepository).addConnection(any());
         when(mockUsersConnectionRepository.createConnectionRepository(anyString())).thenReturn(mockConnectionRepository);
 
         socialService = new SocialService(mockUsersConnectionRepository, authorityRepository,
-                passwordEncoder, userRepository, mockMailService<% if (searchEngine === 'elasticsearch') { %>, userSearchRepository<% } %>);
+                passwordEncoder, userRepository, mockMailService<% if (searchEngine === 'elasticsearch') { %>, userSearchRepository<% } %><% if (cacheManagerIsAvailable === true) { %>, cacheManager<% } %>);
     }
 
     @Test
diff --git a/generators/server/templates/src/test/java/package/web/rest/UserResourceIntTest.java.ejs b/generators/server/templates/src/test/java/package/web/rest/UserResourceIntTest.java.ejs
index 27bfed242d..2ec20ed598 100644
--- a/generators/server/templates/src/test/java/package/web/rest/UserResourceIntTest.java.ejs
+++ b/generators/server/templates/src/test/java/package/web/rest/UserResourceIntTest.java.ejs
@@ -16,12 +16,6 @@
  See the License for the specific language governing permissions and
  limitations under the License.
 -%>
-<%_
-let cacheManagerIsAvailable = false;
-if (['ehcache', 'hazelcast', 'infinispan'].includes(cacheProvider) || applicationType === 'gateway') {
-    cacheManagerIsAvailable = true;
-}
-_%>
 package <%= packageName %>.web.rest;
 
 <%_ if (databaseType === 'cassandra') { _%>
diff --git a/generators/server/templates/src/test/resources/config/application.yml.ejs b/generators/server/templates/src/test/resources/config/application.yml.ejs
index 463051eddd..117aa4d312 100644
--- a/generators/server/templates/src/test/resources/config/application.yml.ejs
+++ b/generators/server/templates/src/test/resources/config/application.yml.ejs
@@ -16,12 +16,6 @@
  See the License for the specific language governing permissions and
  limitations under the License.
 -%>
-<%_
-let cacheManagerIsAvailable = false;
-if (['ehcache', 'hazelcast', 'infinispan'].includes(cacheProvider) || applicationType === 'gateway') {
-    cacheManagerIsAvailable = true;
-}
-_%>
 # ===================================================================
 # Spring Boot configuration.
 #