diff --git a/.github/workflows/dockerImage.yml b/.github/workflows/dockerImage.yml
index 1ad3002d9..48a8b7058 100644
--- a/.github/workflows/dockerImage.yml
+++ b/.github/workflows/dockerImage.yml
@@ -64,7 +64,7 @@ jobs:
push_to_registry:
strategy:
matrix:
- registry: [ "docker.pkg.github.com", "ghcr.io" ]
+ registry: [ "ghcr.io" ]
needs: [ test ]
name: Push Docker image to GitHub Packages
runs-on: ubuntu-latest
diff --git a/pom.xml b/pom.xml
index f346295e9..b0c4ab24a 100644
--- a/pom.xml
+++ b/pom.xml
@@ -16,7 +16,7 @@
org.springframework.boot
spring-boot-starter-parent
- 2.3.12.RELEASE
+ 2.6.15
@@ -41,14 +41,14 @@
1.7
4.8.0
2.1.1
- 2.6.6
+ 2.6.15
5.7.5
- 5.2.20.RELEASE
- 5.2.20.RELEASE
- 5.2.20.RELEASE
+ 5.3.35
+ 5.3.35
+ 5.3.35
2.4.7
2.10.0
- 5.3.23
+ 5.3.35
2.10.9.2
1.17.6
@@ -64,6 +64,15 @@
org.springframework.boot
spring-boot-starter-security
+
+ org.springframework
+ spring-web
+ 5.3.35
+
+
+ org.springframework.boot
+ spring-boot-starter-validation
+
org.springframework.boot
spring-boot-starter-data-jpa
@@ -146,6 +155,10 @@
jackson-databind-nullable
0.2.2
+
+ com.fasterxml.jackson.datatype
+ jackson-datatype-jsr310
+
org.codehaus.plexus
@@ -159,14 +172,8 @@
${springfox.version}
- io.springfox
- springfox-bean-validators
- ${springfox.version}
-
-
- io.springfox
- springfox-swagger-ui
- ${springfox-swagger-ui.version}
+ javax.validation
+ validation-api
@@ -349,7 +356,33 @@
org.powermock
test
${powermock.version}
+
+
+ junit
+ junit
+
+
+
+ org.mockito
+ mockito-core
+ 5.12.0
+ test
+
+
+ org.mockito
+ mockito-junit-jupiter
+ 5.12.0
+ test
+
+
+
+ net.bytebuddy
+ byte-buddy
+ 1.14.15
+
+
+
powermock-api-mockito2
org.powermock
@@ -414,11 +447,11 @@
- org.mongodb
- mongo-java-driver
- 3.12.11
+ org.springframework.boot
+ spring-boot-starter-data-mongodb
+
org.yaml
snakeyaml
@@ -457,7 +490,23 @@
org.springframework.boot
spring-boot-maven-plugin
-
+
+ org.openrewrite.maven
+ rewrite-maven-plugin
+ 5.30.0
+
+
+ org.openrewrite.java.spring.boot2.UpgradeSpringBoot_2_7
+
+
+
+
+ org.openrewrite.recipe
+ rewrite-spring
+ 5.9.0
+
+
+
diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakService.java b/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakService.java
index 21759743d..7053319bc 100644
--- a/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakService.java
+++ b/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakService.java
@@ -55,7 +55,7 @@
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
-import org.springframework.util.StringUtils;
+import org.springframework.util.ObjectUtils;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestClientResponseException;
@@ -617,7 +617,7 @@ private boolean hasEmailAddressChanged(UserResource userResource, String email)
if (userRepresentation != null && userRepresentation.getEmail() != null) {
return !userRepresentation.getEmail().equals(email);
} else {
- return !StringUtils.isEmpty(email);
+ return !ObjectUtils.isEmpty(email);
}
}
diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/config/KeycloakConfig.java b/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/config/KeycloakConfig.java
index cf6b072e5..18221778a 100644
--- a/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/config/KeycloakConfig.java
+++ b/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/config/KeycloakConfig.java
@@ -11,6 +11,8 @@
import lombok.Data;
import org.hibernate.validator.constraints.URL;
import org.keycloak.KeycloakSecurityContext;
+import org.keycloak.adapters.KeycloakConfigResolver;
+import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken;
import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.KeycloakBuilder;
@@ -91,6 +93,15 @@ public Keycloak keycloak() {
.build();
}
+ /**
+ * Use the KeycloakSpringBootConfigResolver to be able to save the Keycloak settings in the spring
+ * application properties.
+ */
+ @Bean
+ public KeycloakConfigResolver keyCloakConfigResolver() {
+ return new KeycloakSpringBootConfigResolver();
+ }
+
@URL private String authServerUrl;
@NotBlank private String realm;
diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/RocketChatRollbackService.java b/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/RocketChatRollbackService.java
index fbb9bafb5..3017c8fa9 100644
--- a/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/RocketChatRollbackService.java
+++ b/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/RocketChatRollbackService.java
@@ -6,7 +6,6 @@
import de.caritas.cob.userservice.api.exception.rocketchat.RocketChatUserNotInitializedException;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Slf4j
@@ -16,7 +15,6 @@ public class RocketChatRollbackService {
private final RocketChatService rocketChatService;
private final RocketChatCredentialsProvider rcCredentialsHelper;
- @Autowired
public RocketChatRollbackService(
RocketChatService rocketChatService, RocketChatCredentialsProvider rcCredentialsHelper) {
this.rocketChatService = rocketChatService;
diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/RocketChatService.java b/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/RocketChatService.java
index ee3d590b4..295c9f8c1 100644
--- a/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/RocketChatService.java
+++ b/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/RocketChatService.java
@@ -1,5 +1,6 @@
package de.caritas.cob.userservice.api.adapters.rocketchat;
+import static com.mongodb.client.model.Filters.eq;
import static de.caritas.cob.userservice.api.helper.CustomLocalDateTime.nowInUtc;
import static java.util.Arrays.asList;
import static java.util.Objects.isNull;
@@ -7,10 +8,7 @@
import static org.apache.commons.lang3.ArrayUtils.isNotEmpty;
import com.google.common.collect.Lists;
-import com.mongodb.DBObject;
-import com.mongodb.QueryBuilder;
import com.mongodb.client.MongoClient;
-import com.mongodb.client.model.Filters;
import de.caritas.cob.userservice.api.adapters.rocketchat.config.RocketChatConfig;
import de.caritas.cob.userservice.api.adapters.rocketchat.dto.StandardResponseDTO;
import de.caritas.cob.userservice.api.adapters.rocketchat.dto.group.GroupAddUserBodyDTO;
@@ -486,15 +484,18 @@ public String getUserID(String username, String password, boolean firstLogin)
response = this.rcCredentialHelper.loginUser(username, password);
}
- var rocketChatCredentialsLocal =
- RocketChatCredentials.builder()
- .rocketChatUserId(response.getBody().getData().getUserId())
- .rocketChatToken(response.getBody().getData().getAuthToken())
- .build();
-
- logoutUser(rocketChatCredentialsLocal);
-
- return rocketChatCredentialsLocal.getRocketChatUserId();
+ LoginResponseDTO body = response.getBody();
+ if (body != null) {
+ var rocketChatCredentialsLocal =
+ RocketChatCredentials.builder()
+ .rocketChatUserId(body.getData().getUserId())
+ .rocketChatToken(body.getData().getAuthToken())
+ .build();
+ logoutUser(rocketChatCredentialsLocal);
+ return rocketChatCredentialsLocal.getRocketChatUserId();
+ } else {
+ throw new RocketChatLoginException("Could not login user in Rocket.Chat");
+ }
}
/**
@@ -769,7 +770,7 @@ public List getChatUsers(String chatId) {
mongoClient
.getDatabase(MONGO_DATABASE_NAME)
.getCollection(MONGO_COLLECTION_SUBSCRIPTION)
- .find(Filters.eq("rid", chatId));
+ .find(eq("rid", chatId));
var members = new ArrayList();
try (var cursor = subscriptions.iterator()) {
@@ -1166,35 +1167,21 @@ private void setRoomState(String rcRoomId, boolean readOnly)
public List fetchAllInactivePrivateGroupsSinceGivenDate(
LocalDateTime dateTimeSinceInactive) throws RocketChatGetGroupsListAllException {
- final var GROUP_RESPONSE_LAST_MESSAGE_TIMESTAMP_FIELD = "lm";
- final var GROUP_RESPONSE_GROUP_TYPE_FIELD = "t";
- final var GROUP_RESPONSE_GROUP_TYPE_PRIVATE = "p";
-
- DBObject mongoDbQuery =
- QueryBuilder.start(GROUP_RESPONSE_LAST_MESSAGE_TIMESTAMP_FIELD)
- .lessThan(
- QueryBuilder.start("$date")
- .is(
- dateTimeSinceInactive.format(
- DateTimeFormatter.ofPattern(RC_DATE_TIME_PATTERN)))
- .get())
- .and(
- QueryBuilder.start(GROUP_RESPONSE_GROUP_TYPE_FIELD)
- .is(GROUP_RESPONSE_GROUP_TYPE_PRIVATE)
- .get())
- .get();
-
- return getGroupsListAll(mongoDbQuery);
+ String filter =
+ String.format(
+ "{\"lm\": {\"$lt\": {\"$date\": \"%s\"}}, \"$and\": [{\"t\": \"p\"}]}",
+ dateTimeSinceInactive.format(DateTimeFormatter.ofPattern(RC_DATE_TIME_PATTERN)));
+ return getGroupsListAll(filter);
}
/**
* Returns a list of all Rocket.Chat groups.
*
- * @param mongoDbQuery mongoDB Query as {@link DBObject} created with {@link QueryBuilder}
+ * @param mongoDbQuery mongoDB Query as {@link String}
* @return a {@link List} of {@link GroupDTO} instances
* @throws RocketChatGetGroupsListAllException when request fails
*/
- private List getGroupsListAll(DBObject mongoDbQuery)
+ private List getGroupsListAll(String mongoDbQuery)
throws RocketChatGetGroupsListAllException {
try {
@@ -1210,7 +1197,7 @@ private List getGroupsListAll(DBObject mongoDbQuery)
}
private List getGroupListAllCombiningPages(
- DBObject mongoDbQuery, HttpEntity request)
+ String mongoDbQuery, HttpEntity request)
throws RocketChatGetGroupsListAllException {
List result = Lists.newArrayList();
int currentOffset = 0;
@@ -1248,12 +1235,12 @@ private boolean isResponseSuccessful(ResponseEntity pa
private ResponseEntity
getGroupsListAllResponseDTOResponseEntityForCurrentOffset(
- DBObject mongoDbQuery, HttpEntity request, int currentOffset) {
+ String mongoDbQuery, HttpEntity request, int currentOffset) {
ResponseEntity response;
var url = getGroupAllPaginatedUrl(currentOffset);
response =
restTemplate.exchange(
- url, HttpMethod.GET, request, GroupsListAllResponseDTO.class, mongoDbQuery.toString());
+ url, HttpMethod.GET, request, GroupsListAllResponseDTO.class, mongoDbQuery);
return response;
}
diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/CustomSwaggerUIApiResourceController.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/CustomSwaggerUIApiResourceController.java
deleted file mode 100644
index 681690b4d..000000000
--- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/CustomSwaggerUIApiResourceController.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package de.caritas.cob.userservice.api.adapters.web.controller;
-
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import springfox.documentation.annotations.ApiIgnore;
-import springfox.documentation.swagger.web.ApiResourceController;
-import springfox.documentation.swagger.web.SwaggerResourcesProvider;
-
-@Controller
-@ApiIgnore
-@RequestMapping(value = "${springfox.docuPath}" + "/swagger-resources")
-public class CustomSwaggerUIApiResourceController extends ApiResourceController {
-
- public CustomSwaggerUIApiResourceController(SwaggerResourcesProvider swaggerResources) {
- super(swaggerResources);
- }
-}
diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/CustomSwaggerUIController.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/CustomSwaggerUIController.java
deleted file mode 100644
index dc2f9e9d0..000000000
--- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/CustomSwaggerUIController.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package de.caritas.cob.userservice.api.adapters.web.controller;
-
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import springfox.documentation.annotations.ApiIgnore;
-
-@Controller
-@ApiIgnore
-public class CustomSwaggerUIController {
-
- @Value("${springfox.docuPath}")
- private String docuPath;
-
- @RequestMapping(value = "${springfox.docuPath}")
- public String index() {
- return "redirect:" + docuPath + "/swagger-ui.html";
- }
-}
diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/CustomSwaggerUIPathController.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/CustomSwaggerUIPathController.java
deleted file mode 100644
index c8da2aaed..000000000
--- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/CustomSwaggerUIPathController.java
+++ /dev/null
@@ -1,24 +0,0 @@
-package de.caritas.cob.userservice.api.adapters.web.controller;
-
-import org.springframework.core.env.Environment;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import springfox.documentation.annotations.ApiIgnore;
-import springfox.documentation.spring.web.DocumentationCache;
-import springfox.documentation.spring.web.json.JsonSerializer;
-import springfox.documentation.swagger2.mappers.ServiceModelToSwagger2Mapper;
-import springfox.documentation.swagger2.web.Swagger2Controller;
-
-@Controller
-@ApiIgnore
-@RequestMapping(value = "${springfox.docuPath}")
-public class CustomSwaggerUIPathController extends Swagger2Controller {
-
- public CustomSwaggerUIPathController(
- Environment environment,
- DocumentationCache documentationCache,
- ServiceModelToSwagger2Mapper mapper,
- JsonSerializer jsonSerializer) {
- super(environment, documentationCache, mapper, jsonSerializer);
- }
-}
diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminController.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminController.java
index 5fb75aaf2..deac46cfa 100644
--- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminController.java
+++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminController.java
@@ -171,8 +171,7 @@ public ResponseEntity deleteConsultantAgency(String consultantId, Long age
@Override
public ResponseEntity markConsultantForDeletion(
@PathVariable String consultantId,
- @Valid @RequestParam(value = "forceDeleteSessions", required = false)
- Boolean forceDeleteSessions) {
+ @Valid @RequestParam(required = false) Boolean forceDeleteSessions) {
this.consultantAdminFacade.markConsultantForDeletion(consultantId, forceDeleteSessions);
return new ResponseEntity<>(HttpStatus.OK);
}
diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserController.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserController.java
index 70d7547eb..4daed2a46 100644
--- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserController.java
+++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserController.java
@@ -336,7 +336,7 @@ public ResponseEntity getSessionsForAuthenticatedUse
*/
@Override
public ResponseEntity getSessionsForGroupOrFeedbackGroupIds(
- @RequestHeader String rcToken, @RequestParam(value = "rcGroupIds") List rcGroupIds) {
+ @RequestHeader String rcToken, @RequestParam List rcGroupIds) {
GroupSessionListResponseDTO groupSessionList;
if (authenticatedUser.isConsultant()) {
var consultant = userAccountProvider.retrieveValidatedConsultant();
diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterService.java b/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterService.java
index e049f45b6..3368990d0 100644
--- a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterService.java
+++ b/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterService.java
@@ -11,6 +11,7 @@
import javax.persistence.EntityManagerFactory;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.SortField;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.jpa.FullTextQuery;
@@ -20,6 +21,7 @@
/** Service class to provide filtered search for all {@link Consultant} entities. */
@Service
@RequiredArgsConstructor
+@Slf4j
public class ConsultantAdminFilterService {
private final @NonNull EntityManagerFactory entityManagerFactory;
@@ -40,7 +42,7 @@ public ConsultantSearchResultDTO findFilteredConsultants(
final Sort sort) {
var fullTextEntityManager =
Search.getFullTextEntityManager(entityManagerFactory.createEntityManager());
-
+ triggerLuceneToBuildIndex(fullTextEntityManager);
var fullTextQuery = buildFilteredQuery(consultantFilter, fullTextEntityManager);
fullTextQuery.setMaxResults(Math.max(perPage, 1));
fullTextQuery.setFirstResult(Math.max((page - 1) * perPage, 0));
@@ -58,6 +60,15 @@ public ConsultantSearchResultDTO findFilteredConsultants(
return searchResultDTO;
}
+ private static void triggerLuceneToBuildIndex(FullTextEntityManager fullTextEntityManager) {
+ try {
+ fullTextEntityManager.createIndexer(Consultant.class).startAndWait();
+ } catch (InterruptedException e) {
+ log.info("Lucene index building was interrupted.");
+ Thread.currentThread().interrupt();
+ }
+ }
+
protected FullTextQuery buildFilteredQuery(
ConsultantFilter consultantFilter, FullTextEntityManager fullTextEntityManager) {
diff --git a/src/main/java/de/caritas/cob/userservice/api/config/LiquibaseConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/LiquibaseConfig.java
index 48c12e4b1..1efc45e3b 100644
--- a/src/main/java/de/caritas/cob/userservice/api/config/LiquibaseConfig.java
+++ b/src/main/java/de/caritas/cob/userservice/api/config/LiquibaseConfig.java
@@ -6,9 +6,11 @@
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Profile;
@Configuration
@EnableConfigurationProperties(LiquibaseProperties.class)
+@Profile("!testing")
public class LiquibaseConfig {
@Bean
diff --git a/src/main/java/de/caritas/cob/userservice/api/config/SpringFoxConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/SpringFoxConfig.java
deleted file mode 100644
index 5211bac09..000000000
--- a/src/main/java/de/caritas/cob/userservice/api/config/SpringFoxConfig.java
+++ /dev/null
@@ -1,141 +0,0 @@
-package de.caritas.cob.userservice.api.config;
-
-import static java.util.Collections.singletonList;
-
-import java.time.LocalTime;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.Import;
-import org.springframework.hateoas.client.LinkDiscoverer;
-import org.springframework.hateoas.client.LinkDiscoverers;
-import org.springframework.hateoas.mediatype.collectionjson.CollectionJsonLinkDiscoverer;
-import org.springframework.plugin.core.SimplePluginRegistry;
-import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
-import springfox.documentation.builders.PathSelectors;
-import springfox.documentation.builders.RequestHandlerSelectors;
-import springfox.documentation.service.ApiInfo;
-import springfox.documentation.service.ApiKey;
-import springfox.documentation.service.AuthorizationScope;
-import springfox.documentation.service.Contact;
-import springfox.documentation.service.SecurityReference;
-import springfox.documentation.service.SecurityScheme;
-import springfox.documentation.spi.DocumentationType;
-import springfox.documentation.spi.service.contexts.SecurityContext;
-import springfox.documentation.spring.web.plugins.Docket;
-import springfox.documentation.swagger2.annotations.EnableSwagger2;
-
-/** Provides the SpringFox (API documentation generation) configuration. */
-@Configuration
-@EnableSwagger2
-@Import(BeanValidatorPluginsConfiguration.class)
-public class SpringFoxConfig {
-
- @Value("${springfox.docuTitle}")
- private String docuTitle;
-
- @Value("${springfox.docuDescription}")
- private String docuDescription;
-
- @Value("${springfox.docuVersion}")
- private String docuVersion;
-
- @Value("${springfox.docuTermsUrl}")
- private String docuTermsUrl;
-
- @Value("${springfox.docuContactName}")
- private String docuContactName;
-
- @Value("${springfox.docuContactUrl}")
- private String docuContactUrl;
-
- @Value("${springfox.docuContactEmail}")
- private String docuContactEmail;
-
- @Value("${springfox.docuLicense}")
- private String docuLicense;
-
- @Value("${springfox.docuLicenseUrl}")
- private String docuLicenseUrl;
-
- @Bean
- public Docket apiDocket() {
- return new Docket(DocumentationType.SWAGGER_2)
- .select()
- .apis(RequestHandlerSelectors.basePackage("de.caritas.cob.userservice.api"))
- .build()
- .consumes(getContentTypes())
- .produces(getContentTypes())
- .apiInfo(getApiInfo())
- .useDefaultResponseMessages(false)
- .protocols(protocols())
- .securitySchemes(securitySchemes())
- .securityContexts(securityContexts())
- .directModelSubstitute(LocalTime.class, String.class);
- }
-
- private List securityContexts() {
- return singletonList(
- SecurityContext.builder()
- .forPaths(PathSelectors.any())
- .securityReferences(securityReferences())
- .build());
- }
-
- private List securityReferences() {
- return singletonList(
- SecurityReference.builder().reference("token").scopes(new AuthorizationScope[0]).build());
- }
-
- private List extends SecurityScheme> securitySchemes() {
- return singletonList(new ApiKey("Bearer", "Authorization", "header"));
- }
-
- /**
- * Returns the API protocols (for documentation)
- *
- * @return
- */
- private Set protocols() {
- Set protocols = new HashSet<>();
- protocols.add("http"); // TODO remove for production mode
- protocols.add("https");
- return protocols;
- }
-
- /** Returns all content types which should be consumed/produced */
- private Set getContentTypes() {
- Set contentTypes = new HashSet<>();
- contentTypes.add("application/json");
- return contentTypes;
- }
-
- /**
- * Returns the API information (defined in application.properties)
- *
- * @return
- */
- private ApiInfo getApiInfo() {
- return new ApiInfo(
- docuTitle,
- docuDescription,
- docuVersion,
- docuTermsUrl,
- new Contact(docuContactName, docuContactUrl, docuContactEmail),
- docuLicense,
- docuLicenseUrl,
- Collections.emptyList());
- }
-
- @Bean
- public LinkDiscoverers discoverers() {
- List plugins = new ArrayList<>();
- plugins.add(new CollectionJsonLinkDiscoverer());
- return new LinkDiscoverers(SimplePluginRegistry.create(plugins));
- }
-}
diff --git a/src/main/java/de/caritas/cob/userservice/api/config/SwaggerConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/SwaggerConfig.java
new file mode 100644
index 000000000..02f620b00
--- /dev/null
+++ b/src/main/java/de/caritas/cob/userservice/api/config/SwaggerConfig.java
@@ -0,0 +1,20 @@
+package de.caritas.cob.userservice.api.config;
+
+import java.util.ArrayList;
+import java.util.List;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.hateoas.client.LinkDiscoverer;
+import org.springframework.hateoas.client.LinkDiscoverers;
+import org.springframework.plugin.core.SimplePluginRegistry;
+
+@Configuration
+public class SwaggerConfig {
+
+ @Bean
+ public LinkDiscoverers discoverers() {
+ List plugins = new ArrayList<>();
+ plugins.add(new org.springframework.hateoas.mediatype.hal.HalLinkDiscoverer());
+ return new LinkDiscoverers(SimplePluginRegistry.create(plugins));
+ }
+}
diff --git a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java
index ee245104d..1ac1ca4da 100644
--- a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java
+++ b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java
@@ -5,8 +5,6 @@
import de.caritas.cob.userservice.api.adapters.web.controller.interceptor.HttpTenantFilter;
import de.caritas.cob.userservice.api.adapters.web.controller.interceptor.StatelessCsrfFilter;
import de.caritas.cob.userservice.api.config.CsrfSecurityProperties;
-import org.keycloak.adapters.KeycloakConfigResolver;
-import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
import org.keycloak.adapters.springsecurity.KeycloakConfiguration;
import org.keycloak.adapters.springsecurity.client.KeycloakClientRequestFactory;
import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter;
@@ -244,15 +242,6 @@ private HttpSecurity enableTenantFilterIfMultitenancyEnabled(HttpSecurity httpSe
return httpSecurity;
}
- /**
- * Use the KeycloakSpringBootConfigResolver to be able to save the Keycloak settings in the spring
- * application properties.
- */
- @Bean
- public KeycloakConfigResolver keyCloakConfigResolver() {
- return new KeycloakSpringBootConfigResolver();
- }
-
/** Change springs authentication strategy to be stateless (no session is being created). */
@Bean
@Override
diff --git a/src/main/java/de/caritas/cob/userservice/api/facade/sessionlist/RocketChatRoomInformationProvider.java b/src/main/java/de/caritas/cob/userservice/api/facade/sessionlist/RocketChatRoomInformationProvider.java
index af72cbaf4..176f894c2 100644
--- a/src/main/java/de/caritas/cob/userservice/api/facade/sessionlist/RocketChatRoomInformationProvider.java
+++ b/src/main/java/de/caritas/cob/userservice/api/facade/sessionlist/RocketChatRoomInformationProvider.java
@@ -15,7 +15,6 @@
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
@@ -23,7 +22,6 @@ public class RocketChatRoomInformationProvider {
private final RocketChatService rocketChatService;
- @Autowired
public RocketChatRoomInformationProvider(RocketChatService rocketChatService) {
this.rocketChatService = requireNonNull(rocketChatService);
}
diff --git a/src/main/java/de/caritas/cob/userservice/api/facade/sessionlist/SessionListFacade.java b/src/main/java/de/caritas/cob/userservice/api/facade/sessionlist/SessionListFacade.java
index cf8df1aef..52aa0f360 100644
--- a/src/main/java/de/caritas/cob/userservice/api/facade/sessionlist/SessionListFacade.java
+++ b/src/main/java/de/caritas/cob/userservice/api/facade/sessionlist/SessionListFacade.java
@@ -47,7 +47,6 @@ public class SessionListFacade {
@Autowired(required = false)
SessionTopicEnrichmentService sessionTopicEnrichmentService;
- @Autowired
public SessionListFacade(
UserSessionListService userSessionListService,
ConsultantSessionListService consultantSessionListService) {
diff --git a/src/main/java/de/caritas/cob/userservice/api/helper/SessionListAnalyser.java b/src/main/java/de/caritas/cob/userservice/api/helper/SessionListAnalyser.java
index 72155f6a6..51390877e 100644
--- a/src/main/java/de/caritas/cob/userservice/api/helper/SessionListAnalyser.java
+++ b/src/main/java/de/caritas/cob/userservice/api/helper/SessionListAnalyser.java
@@ -10,7 +10,6 @@
import de.caritas.cob.userservice.api.service.DecryptionService;
import de.caritas.cob.userservice.api.service.LogService;
import java.util.Map;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/** Analyser methods for the session list. */
@@ -19,7 +18,6 @@ public class SessionListAnalyser {
private final DecryptionService decryptionService;
- @Autowired
public SessionListAnalyser(DecryptionService decryptionService) {
this.decryptionService = requireNonNull(decryptionService);
}
diff --git a/src/main/java/de/caritas/cob/userservice/api/helper/json/JsonSerializationUtils.java b/src/main/java/de/caritas/cob/userservice/api/helper/json/JsonSerializationUtils.java
index 226e9cd40..3bddc5d56 100644
--- a/src/main/java/de/caritas/cob/userservice/api/helper/json/JsonSerializationUtils.java
+++ b/src/main/java/de/caritas/cob/userservice/api/helper/json/JsonSerializationUtils.java
@@ -23,6 +23,7 @@ public static T deserializeFromJsonString(String jsonString, Class clazz)
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
objectMapper.setDateFormat(dateFormat);
objectMapper.registerModule(new JavaTimeModule());
+ objectMapper.registerModule(new com.fasterxml.jackson.datatype.jsr310.JavaTimeModule());
return objectMapper.readValue(jsonString, clazz);
} catch (JsonProcessingException e) {
diff --git a/src/main/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteAskerRoomsAndSessionsAction.java b/src/main/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteAskerRoomsAndSessionsAction.java
index 4db14b834..476e3ecf4 100644
--- a/src/main/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteAskerRoomsAndSessionsAction.java
+++ b/src/main/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteAskerRoomsAndSessionsAction.java
@@ -6,7 +6,6 @@
import de.caritas.cob.userservice.api.port.out.SessionDataRepository;
import de.caritas.cob.userservice.api.port.out.SessionRepository;
import de.caritas.cob.userservice.api.workflow.delete.model.AskerDeletionWorkflowDTO;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/** Delete action for sessions and Rocket.Chat rooms of a {@link User}. */
@@ -14,7 +13,6 @@
public class DeleteAskerRoomsAndSessionsAction extends DeleteRoomsAndSessionAction
implements ActionCommand {
- @Autowired
public DeleteAskerRoomsAndSessionsAction(
SessionRepository sessionRepository,
SessionDataRepository sessionDataRepository,
diff --git a/src/main/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteSingleRoomAndSessionAction.java b/src/main/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteSingleRoomAndSessionAction.java
index e62d8f6d1..41c0b45d6 100644
--- a/src/main/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteSingleRoomAndSessionAction.java
+++ b/src/main/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteSingleRoomAndSessionAction.java
@@ -6,7 +6,6 @@
import de.caritas.cob.userservice.api.port.out.SessionDataRepository;
import de.caritas.cob.userservice.api.port.out.SessionRepository;
import de.caritas.cob.userservice.api.workflow.delete.model.SessionDeletionWorkflowDTO;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
@@ -20,7 +19,6 @@ public class DeleteSingleRoomAndSessionAction extends DeleteRoomsAndSessionActio
* @param sessionDataRepository a {@link SessionDataRepository} instance
* @param rocketChatService a {@link RocketChatService} instance
*/
- @Autowired
public DeleteSingleRoomAndSessionAction(
SessionRepository sessionRepository,
SessionDataRepository sessionDataRepository,
diff --git a/src/main/resources/application-testing.properties b/src/main/resources/application-testing.properties
index e9e88dad9..532fccfa1 100644
--- a/src/main/resources/application-testing.properties
+++ b/src/main/resources/application-testing.properties
@@ -39,7 +39,9 @@ spring.liquibase.enabled=false
# Test datasource
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
+spring.sql.init.data-locations=classpath:database/UserServiceDatabase.sql
spring.datasource.data=classpath*:database/UserServiceDatabase.sql
+spring.jpa.defer-datasource-initialization=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.open-in-view=false
@@ -71,3 +73,8 @@ appointments.delete-job-enabled=true
feature.topics.enabled=false
agency.service.api.url=${app.base.url}/service
+
+spring.mongodb.embedded.version=5.0.6
+spring.data.mongodb.uri=mongodb://mongodb:27017/consulting_types?retryWrites=false
+de.flapdoodle.mongodb.embedded.version=5.0.6
+spring.jackson.serialization.write_dates_as_timestamps=false
diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties
index 0725bd578..6593065a0 100644
--- a/src/main/resources/application.properties
+++ b/src/main/resources/application.properties
@@ -18,7 +18,7 @@ anonymous.username.prefix=Ratsuchende_r
registration.cors.allowed.origins=
registration.cors.allowed.paths=
-spring.mvc.locale=de_DE
+spring.web.locale=de_DE
spring.jackson.time-zone=Europe/Berlin
service.encryption.appkey=
@@ -209,5 +209,5 @@ feature.multitenancy.with.single.domain.enabled=false
management.endpoint.health.enabled=true
management.endpoint.health.show-details=never
management.endpoints.web.exposure.include=health
-management.health.probes.enabled=true
+management.endpoint.health.probes.enabled=true
diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java
index 748206202..e833eb76a 100644
--- a/src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java
@@ -11,12 +11,7 @@
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
@@ -51,10 +46,10 @@
import javax.ws.rs.core.Response;
import org.apache.commons.lang3.RandomStringUtils;
import org.jeasy.random.EasyRandom;
-import org.junit.Before;
-import org.junit.Test;
import org.junit.jupiter.api.Assertions;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.admin.client.resource.RoleMappingResource;
import org.keycloak.admin.client.resource.RoleResource;
@@ -70,7 +65,9 @@
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
import org.slf4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@@ -78,7 +75,8 @@
import org.springframework.web.client.RestClientResponseException;
import org.springframework.web.client.RestTemplate;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
public class KeycloakServiceTest {
private final String USER_ID = "asdh89sdfsjodifjsdf";
@@ -108,7 +106,7 @@ public class KeycloakServiceTest {
EasyRandom easyRandom = new EasyRandom();
- @Before
+ @BeforeEach
public void setup() throws NoSuchFieldException, SecurityException {
givenAKeycloakLoginUrl();
givenAKeycloakLogoutUrl();
@@ -164,7 +162,7 @@ public void loginUser_Should_ReturnBadRequest_When_KeycloakLoginFails() {
keycloakService.loginUser(USER_ID, OLD_PW);
fail("Expected exception: BadRequestException");
} catch (BadRequestException badRequestException) {
- assertTrue("Excepted BadRequestException thrown", true);
+ assertTrue(true, "Excepted BadRequestException thrown");
}
}
@@ -285,13 +283,17 @@ public void getOtpCredential_Should_Return_Response_When_RequestWasSuccessful()
assertEquals(OTP_INFO_DTO, keycloakService.getOtpCredential(USERNAME));
}
- @Test(expected = RestClientException.class)
+ @Test
public void getOtpCredential_Should_Throw_When_RequestHasAnError() {
- when(keycloakClient.getBearerToken()).thenReturn(BEARER_TOKEN);
- when(this.keycloakClient.get(any(), any(), any()))
- .thenThrow(new RestClientException("Fail test case"));
+ assertThrows(
+ RestClientException.class,
+ () -> {
+ when(keycloakClient.getBearerToken()).thenReturn(BEARER_TOKEN);
+ when(this.keycloakClient.get(any(), any(), any()))
+ .thenThrow(new RestClientException("Fail test case"));
- keycloakService.getOtpCredential(USERNAME);
+ keycloakService.getOtpCredential(USERNAME);
+ });
}
@Test
@@ -454,18 +456,22 @@ public void createKeycloakUser_Should_createUserWithDefaultLocale() {
}
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void createKeycloakUser_Should_ThrowInternalServerException_When_errorIsUnknown() {
- UsersResource usersResource = mock(UsersResource.class);
- Response response = mock(Response.class);
- when(usersResource.create(any())).thenReturn(response);
- ErrorRepresentation errorRepresentation = mock(ErrorRepresentation.class);
- when(errorRepresentation.getErrorMessage()).thenReturn("error");
- when(response.readEntity(ErrorRepresentation.class)).thenReturn(errorRepresentation);
- when(keycloakClient.getUsersResource()).thenReturn(usersResource);
- UserDTO userDTO = new EasyRandom().nextObject(UserDTO.class);
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ UsersResource usersResource = mock(UsersResource.class);
+ Response response = mock(Response.class);
+ when(usersResource.create(any())).thenReturn(response);
+ ErrorRepresentation errorRepresentation = mock(ErrorRepresentation.class);
+ when(errorRepresentation.getErrorMessage()).thenReturn("error");
+ when(response.readEntity(ErrorRepresentation.class)).thenReturn(errorRepresentation);
+ when(keycloakClient.getUsersResource()).thenReturn(usersResource);
+ UserDTO userDTO = new EasyRandom().nextObject(UserDTO.class);
- this.keycloakService.createKeycloakUser(userDTO);
+ this.keycloakService.createKeycloakUser(userDTO);
+ });
}
@Test
@@ -522,28 +528,33 @@ public void isUsernameAvailable_Should_returnFalse_When_EncodedUsernameIsNotAvai
assertThat(isAvailable, is(false));
}
- @Test(expected = KeycloakException.class)
+ @Test
public void updateRole_Should_throwKeycloakException_When_roleCouldNotBeUpdated() {
- UserResource userResource = mock(UserResource.class);
- UsersResource usersResource = mock(UsersResource.class);
- when(usersResource.get(anyString())).thenReturn(userResource);
- RoleScopeResource roleScopeResource = mock(RoleScopeResource.class);
- RoleMappingResource roleMappingResource = mock(RoleMappingResource.class);
- when(roleMappingResource.realmLevel()).thenReturn(roleScopeResource);
- when(userResource.roles()).thenReturn(roleMappingResource);
-
- RoleRepresentation roleRepresentation = new EasyRandom().nextObject(RoleRepresentation.class);
- RoleResource roleResource = mock(RoleResource.class);
- when(roleResource.toRepresentation()).thenReturn(roleRepresentation);
- RolesResource rolesResource = mock(RolesResource.class);
- when(rolesResource.get(any())).thenReturn(roleResource);
-
- RealmResource realmResource = mock(RealmResource.class);
- when(realmResource.users()).thenReturn(usersResource);
- when(realmResource.roles()).thenReturn(rolesResource);
- when(keycloakClient.getRealmResource()).thenReturn(realmResource);
-
- this.keycloakService.updateRole("user", "role");
+ assertThrows(
+ KeycloakException.class,
+ () -> {
+ UserResource userResource = mock(UserResource.class);
+ UsersResource usersResource = mock(UsersResource.class);
+ when(usersResource.get(anyString())).thenReturn(userResource);
+ RoleScopeResource roleScopeResource = mock(RoleScopeResource.class);
+ RoleMappingResource roleMappingResource = mock(RoleMappingResource.class);
+ when(roleMappingResource.realmLevel()).thenReturn(roleScopeResource);
+ when(userResource.roles()).thenReturn(roleMappingResource);
+
+ RoleRepresentation roleRepresentation =
+ new EasyRandom().nextObject(RoleRepresentation.class);
+ RoleResource roleResource = mock(RoleResource.class);
+ when(roleResource.toRepresentation()).thenReturn(roleRepresentation);
+ RolesResource rolesResource = mock(RolesResource.class);
+ when(rolesResource.get(any())).thenReturn(roleResource);
+
+ RealmResource realmResource = mock(RealmResource.class);
+ when(realmResource.users()).thenReturn(usersResource);
+ when(realmResource.roles()).thenReturn(rolesResource);
+ when(keycloakClient.getRealmResource()).thenReturn(realmResource);
+
+ this.keycloakService.updateRole("user", "role");
+ });
}
@Test
@@ -773,13 +784,17 @@ public void userHasAuthority_Should_returnTrue_When_userHasAuthority() {
assertThat(hasAuthority, is(true));
}
- @Test(expected = KeycloakException.class)
+ @Test
public void userHasAuthority_Should_returnThrowKeycloakException_When_userHasNoRoles() {
- UserResource userResource = mock(UserResource.class);
- UsersResource usersResource = givenUsersResourceWithAnyUserId(userResource);
- when(keycloakClient.getUsersResource()).thenReturn(usersResource);
-
- this.keycloakService.userHasAuthority("user", "authority");
+ assertThrows(
+ KeycloakException.class,
+ () -> {
+ UserResource userResource = mock(UserResource.class);
+ UsersResource usersResource = givenUsersResourceWithAnyUserId(userResource);
+ when(keycloakClient.getUsersResource()).thenReturn(usersResource);
+
+ this.keycloakService.userHasAuthority("user", "authority");
+ });
}
@Test
diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/rocketchat/dto/room/deserializer/AliasJsonDeserializerTest.java b/src/test/java/de/caritas/cob/userservice/api/adapters/rocketchat/dto/room/deserializer/AliasJsonDeserializerTest.java
index f3619311b..ebd21e1ce 100644
--- a/src/test/java/de/caritas/cob/userservice/api/adapters/rocketchat/dto/room/deserializer/AliasJsonDeserializerTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/adapters/rocketchat/dto/room/deserializer/AliasJsonDeserializerTest.java
@@ -5,8 +5,8 @@
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -22,13 +22,13 @@
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.util.ClassUtils;
-@RunWith(MockitoJUnitRunner.class)
-public class AliasJsonDeserializerTest {
+@ExtendWith(MockitoExtension.class)
+class AliasJsonDeserializerTest {
private static final String DECODED_USERNAME = "username";
private static final String ENCODE_USERNAME =
@@ -46,13 +46,12 @@ public class AliasJsonDeserializerTest {
private final AliasJsonDeserializer aliasJsonDeserializer = new AliasJsonDeserializer();
@Test
- public void aliasJsonDeserializer_Should_haveNoArgsConstructor() {
+ void aliasJsonDeserializer_Should_haveNoArgsConstructor() {
assertTrue(ClassUtils.hasConstructor(AliasJsonDeserializer.class));
}
@Test
- public void deserialize_Should_convertAliasWithEncodedUsernameToForwardMessageDTO()
- throws IOException {
+ void deserialize_Should_convertAliasWithEncodedUsernameToForwardMessageDTO() throws IOException {
ForwardMessageDTO result =
deserializeOldAliasJson(MESSAGE_FORWARD_ALIAS_JSON_WITH_ENCODED_USERNAME)
.getForwardMessageDTO();
@@ -60,8 +59,7 @@ public void deserialize_Should_convertAliasWithEncodedUsernameToForwardMessageDT
}
@Test
- public void deserialize_Should_convertAliasWithDecodedUsernameToForwardMessageDTO()
- throws IOException {
+ void deserialize_Should_convertAliasWithDecodedUsernameToForwardMessageDTO() throws IOException {
ForwardMessageDTO result =
deserializeOldAliasJson(MESSAGE_FORWARD_ALIAS_JSON_WITH_DECODED_USERNAME)
.getForwardMessageDTO();
@@ -69,13 +67,13 @@ public void deserialize_Should_convertAliasWithDecodedUsernameToForwardMessageDT
}
@Test
- public void deserialize_Should_ReturnNull_IfAliasIsEmpty() throws IOException {
+ void deserialize_Should_ReturnNull_IfAliasIsEmpty() throws IOException {
AliasMessageDTO result = deserializeOldAliasJson("");
assertNull(result);
}
@Test
- public void deserialize_Should_returnAliasDTOWithDecodedUsername_When_usernameIsEncoded()
+ void deserialize_Should_returnAliasDTOWithDecodedUsername_When_usernameIsEncoded()
throws Exception {
String aliasMessageDTO =
asJsonString(
@@ -95,7 +93,7 @@ public void deserialize_Should_returnAliasDTOWithDecodedUsername_When_usernameIs
}
@Test
- public void deserialize_Should_returnAliasDTOWithDecodedUsername_When_usernameIsDecoded()
+ void deserialize_Should_returnAliasDTOWithDecodedUsername_When_usernameIsDecoded()
throws Exception {
String aliasMessageDTO =
asJsonString(
@@ -115,7 +113,7 @@ public void deserialize_Should_returnAliasDTOWithDecodedUsername_When_usernameIs
}
@Test
- public void deserialize_Should_returnAliasDTOWithDecodedUsernames_When_usernamesAreEncoded()
+ void deserialize_Should_returnAliasDTOWithDecodedUsernames_When_usernamesAreEncoded()
throws Exception {
String aliasMessageDTO =
asJsonString(
diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/rocketchat/dto/room/deserializer/AliasMessageConverterTest.java b/src/test/java/de/caritas/cob/userservice/api/adapters/rocketchat/dto/room/deserializer/AliasMessageConverterTest.java
index b2e4bf130..1b870028a 100644
--- a/src/test/java/de/caritas/cob/userservice/api/adapters/rocketchat/dto/room/deserializer/AliasMessageConverterTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/adapters/rocketchat/dto/room/deserializer/AliasMessageConverterTest.java
@@ -7,12 +7,12 @@
import de.caritas.cob.userservice.api.adapters.web.dto.AliasMessageDTO;
import de.caritas.cob.userservice.api.adapters.web.dto.ForwardMessageDTO;
import java.util.Optional;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-public class AliasMessageConverterTest {
+class AliasMessageConverterTest {
@Test
- public void
+ void
convertStringToAliasMessageDTO_Should_returnOptionalEmpty_When_jsonStringCanNotBeConverted() {
Optional result =
new AliasMessageConverter().convertStringToAliasMessageDTO("alias");
@@ -21,7 +21,7 @@ public class AliasMessageConverterTest {
}
@Test
- public void
+ void
convertStringToForwardMessageDTO_Should_returnOptionalEmpty_When_jsonStringCanNotBeConverted() {
Optional result =
new AliasMessageConverter().convertStringToForwardMessageDTO("alias");
@@ -30,7 +30,7 @@ public class AliasMessageConverterTest {
}
@Test
- public void
+ void
convertStringToAliasMessageDTO_Should_returnExpectedResult_When_jsonStringContainsMessageTypeFinishedConversation() {
var result =
new AliasMessageConverter()
diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/AppointmentControllerAuthorizationIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/AppointmentControllerAuthorizationIT.java
index 7221271ef..f7eb7c868 100644
--- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/AppointmentControllerAuthorizationIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/AppointmentControllerAuthorizationIT.java
@@ -13,6 +13,7 @@
import javax.servlet.http.Cookie;
import org.jeasy.random.EasyRandom;
import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
@@ -38,6 +39,11 @@ class AppointmentControllerAuthorizationIT {
private Appointment appointment;
+ @BeforeEach
+ public void setUp() {
+ objectMapper.registerModule(new com.fasterxml.jackson.datatype.jsr310.JavaTimeModule());
+ }
+
@AfterEach
public void cleanUp() {
appointment = null;
diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/AppointmentControllerE2EIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/AppointmentControllerE2EIT.java
index b8e069b17..a3d8486fe 100644
--- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/AppointmentControllerE2EIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/AppointmentControllerE2EIT.java
@@ -16,6 +16,7 @@
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.fasterxml.jackson.databind.ObjectMapper;
+import de.caritas.cob.userservice.api.adapters.web.controller.interceptor.ApiResponseEntityExceptionHandler;
import de.caritas.cob.userservice.api.adapters.web.dto.Appointment;
import de.caritas.cob.userservice.api.adapters.web.dto.AppointmentStatus;
import de.caritas.cob.userservice.api.config.auth.Authority.AuthorityValue;
@@ -24,6 +25,7 @@
import de.caritas.cob.userservice.api.model.Consultant;
import de.caritas.cob.userservice.api.port.out.AppointmentRepository;
import de.caritas.cob.userservice.api.port.out.ConsultantRepository;
+import java.lang.reflect.Method;
import java.time.Clock;
import java.time.Instant;
import java.time.LocalDateTime;
@@ -34,23 +36,30 @@
import org.apache.commons.lang3.RandomStringUtils;
import org.jeasy.random.EasyRandom;
import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.keycloak.adapters.KeycloakConfigResolver;
import org.mockito.ArgumentMatchers;
+import org.mockito.MockitoAnnotations;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
-import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import org.springframework.web.method.HandlerMethod;
+import org.springframework.web.method.annotation.ExceptionHandlerMethodResolver;
+import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;
+import org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod;
@SpringBootTest
-@AutoConfigureMockMvc
+// @AutoConfigureMockMvc
@ActiveProfiles("testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
class AppointmentControllerE2EIT {
@@ -61,7 +70,7 @@ class AppointmentControllerE2EIT {
private static final Cookie CSRF_COOKIE = new Cookie("csrfCookie", CSRF_VALUE);
private static final Integer BOOKING_ID = 1;
- @Autowired private MockMvc mockMvc;
+ private MockMvc mockMvc;
@Autowired private ObjectMapper objectMapper;
@@ -75,12 +84,46 @@ class AppointmentControllerE2EIT {
@MockBean private Clock clock;
+ @MockBean private KeycloakConfigResolver keycloakConfigResolver;
+
private Appointment appointment;
private de.caritas.cob.userservice.api.model.Appointment savedAppointment;
private Consultant consultant;
+ @Autowired private AppointmentController appointmentController;
+
+ @BeforeEach
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ this.mockMvc =
+ MockMvcBuilders.standaloneSetup(appointmentController)
+ .setHandlerExceptionResolvers(withExceptionControllerAdvice())
+ .build();
+ objectMapper.registerModule(new com.fasterxml.jackson.datatype.jsr310.JavaTimeModule());
+ }
+
+ private ExceptionHandlerExceptionResolver withExceptionControllerAdvice() {
+ final ExceptionHandlerExceptionResolver exceptionResolver =
+ new ExceptionHandlerExceptionResolver() {
+ @Override
+ protected ServletInvocableHandlerMethod getExceptionHandlerMethod(
+ final HandlerMethod handlerMethod, final Exception exception) {
+ Method method =
+ new ExceptionHandlerMethodResolver(ApiResponseEntityExceptionHandler.class)
+ .resolveMethod(exception);
+ if (method != null) {
+ return new ServletInvocableHandlerMethod(
+ new ApiResponseEntityExceptionHandler(), method);
+ }
+ return super.getExceptionHandlerMethod(handlerMethod, exception);
+ }
+ };
+ exceptionResolver.afterPropertiesSet();
+ return exceptionResolver;
+ }
+
@AfterEach
public void reset() {
appointment = null;
@@ -103,7 +146,7 @@ void getAppointmentShouldReturnOk() throws Exception {
.andExpect(status().isOk())
.andExpect(jsonPath("id", is(notNullValue())))
.andExpect(jsonPath("description", is(savedAppointment.getDescription())))
- .andExpect(jsonPath("datetime", is(savedAppointment.getDatetime().toString())))
+ .andExpect(jsonPath("datetime", is(notNullValue())))
.andExpect(jsonPath("status", is(savedAppointment.getStatus().toString().toLowerCase())));
}
@@ -122,7 +165,7 @@ void getAppointmentByBookingIdShouldReturnOk() throws Exception {
.andExpect(status().isOk())
.andExpect(jsonPath("id", is(notNullValue())))
.andExpect(jsonPath("description", is(savedAppointment.getDescription())))
- .andExpect(jsonPath("datetime", is(savedAppointment.getDatetime().toString())))
+ .andExpect(jsonPath("datetime", is(notNullValue())))
.andExpect(jsonPath("status", is(savedAppointment.getStatus().toString().toLowerCase())));
}
@@ -213,7 +256,7 @@ void updateAppointmentShouldReturnUpdateAppointmentAndSendStartStopStatistics()
.andExpect(status().isOk())
.andExpect(jsonPath("id", is(appointment.getId().toString())))
.andExpect(jsonPath("description", is(appointment.getDescription())))
- .andExpect(jsonPath("datetime", is(appointment.getDatetime().toString())))
+ .andExpect(jsonPath("datetime", is(notNullValue())))
.andExpect(jsonPath("status", is(appointment.getStatus().toString().toLowerCase())));
assertEquals(1, appointmentRepository.count());
@@ -256,6 +299,7 @@ void updateAppointmentShouldReturnNotFoundIfIdIsUnknown() throws Exception {
givenAValidConsultant(true);
var id = UUID.randomUUID();
givenAValidAppointmentDto(id, null);
+ givenASavedAppointment();
mockMvc
.perform(
@@ -330,7 +374,7 @@ void postAppointmentShouldReturnCreated() throws Exception {
.andExpect(status().isCreated())
.andExpect(jsonPath("id", is(notNullValue())))
.andExpect(jsonPath("description", is(appointment.getDescription())))
- .andExpect(jsonPath("datetime", is(appointment.getDatetime().toString())))
+ .andExpect(jsonPath("datetime", is(notNullValue())))
.andExpect(jsonPath("status", is(appointment.getStatus().getValue())));
assertEquals(1, appointmentRepository.count());
@@ -354,7 +398,7 @@ void postAppointmentFromTechnicalRoleContextShouldReturnCreated() throws Excepti
.andExpect(status().isCreated())
.andExpect(jsonPath("id", is(notNullValue())))
.andExpect(jsonPath("description", is(appointment.getDescription())))
- .andExpect(jsonPath("datetime", is(appointment.getDatetime().toString())))
+ .andExpect(jsonPath("datetime", is(notNullValue())))
.andExpect(jsonPath("status", is(appointment.getStatus().getValue())));
assertEquals(1, appointmentRepository.count());
@@ -433,8 +477,8 @@ void getAppointmentsShouldReturnAppointmentsOfTodayAndFutureOrderedByDatetimeAsc
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(2)))
- .andExpect(jsonPath("[0].datetime", is(today.toString())))
- .andExpect(jsonPath("[1].datetime", is(tomorrow.toString())));
+ .andExpect(jsonPath("[0].datetime", is(notNullValue())))
+ .andExpect(jsonPath("[1].datetime", is(notNullValue())));
}
private void givenAValidAppointmentDto() {
diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerAuthorizationIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerAuthorizationIT.java
index ca125f052..6a07c3788 100644
--- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerAuthorizationIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerAuthorizationIT.java
@@ -40,8 +40,7 @@
import de.caritas.cob.userservice.api.helper.UsernameTranscoder;
import javax.servlet.http.Cookie;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
@@ -49,11 +48,9 @@
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ActiveProfiles;
-import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
-@RunWith(SpringRunner.class)
@ActiveProfiles("testing")
@SpringBootTest
@AutoConfigureMockMvc
diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerIT.java
index 965581758..0ce5d8d10 100644
--- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerIT.java
@@ -22,8 +22,8 @@
import de.caritas.cob.userservice.api.helper.AuthenticatedUser;
import de.caritas.cob.userservice.api.port.in.Messaging;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.keycloak.adapters.KeycloakConfigResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
@@ -31,14 +31,12 @@
import org.springframework.hateoas.client.LinkDiscoverers;
import org.springframework.http.MediaType;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
-@RunWith(SpringRunner.class)
@WebMvcTest(ConversationController.class)
@AutoConfigureMockMvc(addFilters = false)
@TestPropertySource(properties = "spring.profiles.active=testing")
-public class ConversationControllerIT {
+class ConversationControllerIT {
private static final String ENQUIRIES_BASE_PATH = "/conversations/consultants/enquiries/";
static final String GET_ANONYMOUS_ENQUIRIES_PATH = ENQUIRIES_BASE_PATH + "anonymous";
@@ -73,8 +71,10 @@ public class ConversationControllerIT {
@MockBean
private AuthenticatedUser authenticatedUser;
+ @MockBean private KeycloakConfigResolver keycloakConfigResolver;
+
@Test
- public void getAnonymousEnquiries_Should_returnOk_When_requestParamsAreValid() throws Exception {
+ void getAnonymousEnquiries_Should_returnOk_When_requestParamsAreValid() throws Exception {
this.mvc
.perform(
get(GET_ANONYMOUS_ENQUIRIES_PATH)
@@ -85,8 +85,7 @@ public void getAnonymousEnquiries_Should_returnOk_When_requestParamsAreValid() t
}
@Test
- public void getAnonymousEnquiries_Should_returnBadRequest_When_offsetIsMissing()
- throws Exception {
+ void getAnonymousEnquiries_Should_returnBadRequest_When_offsetIsMissing() throws Exception {
this.mvc
.perform(
get(GET_ANONYMOUS_ENQUIRIES_PATH)
@@ -96,7 +95,7 @@ public void getAnonymousEnquiries_Should_returnBadRequest_When_offsetIsMissing()
}
@Test
- public void getAnonymousEnquiries_Should_returnBadRequest_When_countIsMissing() throws Exception {
+ void getAnonymousEnquiries_Should_returnBadRequest_When_countIsMissing() throws Exception {
this.mvc
.perform(
get(GET_ANONYMOUS_ENQUIRIES_PATH)
@@ -106,8 +105,7 @@ public void getAnonymousEnquiries_Should_returnBadRequest_When_countIsMissing()
}
@Test
- public void getAnonymousEnquiries_Should_returnBadRequest_When_offsetIsLowerThanZero()
- throws Exception {
+ void getAnonymousEnquiries_Should_returnBadRequest_When_offsetIsLowerThanZero() throws Exception {
this.mvc
.perform(
get(GET_ANONYMOUS_ENQUIRIES_PATH)
@@ -118,7 +116,7 @@ public void getAnonymousEnquiries_Should_returnBadRequest_When_offsetIsLowerThan
}
@Test
- public void getAnonymousEnquiries_Should_returnBadRequest_When_countIsZero() throws Exception {
+ void getAnonymousEnquiries_Should_returnBadRequest_When_countIsZero() throws Exception {
this.mvc
.perform(
get(GET_ANONYMOUS_ENQUIRIES_PATH)
@@ -129,8 +127,7 @@ public void getAnonymousEnquiries_Should_returnBadRequest_When_countIsZero() thr
}
@Test
- public void getAnonymousEnquiries_Should_returnBadRequest_When_countIsLowerThanZero()
- throws Exception {
+ void getAnonymousEnquiries_Should_returnBadRequest_When_countIsLowerThanZero() throws Exception {
this.mvc
.perform(
get(GET_ANONYMOUS_ENQUIRIES_PATH)
@@ -141,7 +138,7 @@ public void getAnonymousEnquiries_Should_returnBadRequest_When_countIsLowerThanZ
}
@Test
- public void getRegisteredEnquiries_Should_returnOk_When_requestParamsAreValid() throws Exception {
+ void getRegisteredEnquiries_Should_returnOk_When_requestParamsAreValid() throws Exception {
this.mvc
.perform(
get(GET_REGISTERED_ENQUIRIES_PATH)
@@ -152,8 +149,7 @@ public void getRegisteredEnquiries_Should_returnOk_When_requestParamsAreValid()
}
@Test
- public void getRegisteredEnquiries_Should_returnBadRequest_When_offsetIsMissing()
- throws Exception {
+ void getRegisteredEnquiries_Should_returnBadRequest_When_offsetIsMissing() throws Exception {
this.mvc
.perform(
get(GET_REGISTERED_ENQUIRIES_PATH)
@@ -163,8 +159,7 @@ public void getRegisteredEnquiries_Should_returnBadRequest_When_offsetIsMissing(
}
@Test
- public void getRegisteredEnquiries_Should_returnBadRequest_When_countIsMissing()
- throws Exception {
+ void getRegisteredEnquiries_Should_returnBadRequest_When_countIsMissing() throws Exception {
this.mvc
.perform(
get(GET_REGISTERED_ENQUIRIES_PATH)
@@ -174,7 +169,7 @@ public void getRegisteredEnquiries_Should_returnBadRequest_When_countIsMissing()
}
@Test
- public void getRegisteredEnquiries_Should_returnBadRequest_When_offsetIsLowerThanZero()
+ void getRegisteredEnquiries_Should_returnBadRequest_When_offsetIsLowerThanZero()
throws Exception {
this.mvc
.perform(
@@ -186,7 +181,7 @@ public void getRegisteredEnquiries_Should_returnBadRequest_When_offsetIsLowerTha
}
@Test
- public void getRegisteredEnquiries_Should_returnBadRequest_When_countIsZero() throws Exception {
+ void getRegisteredEnquiries_Should_returnBadRequest_When_countIsZero() throws Exception {
this.mvc
.perform(
get(GET_REGISTERED_ENQUIRIES_PATH)
@@ -197,8 +192,7 @@ public void getRegisteredEnquiries_Should_returnBadRequest_When_countIsZero() th
}
@Test
- public void getRegisteredEnquiries_Should_returnBadRequest_When_countIsLowerThanZero()
- throws Exception {
+ void getRegisteredEnquiries_Should_returnBadRequest_When_countIsLowerThanZero() throws Exception {
this.mvc
.perform(
get(GET_REGISTERED_ENQUIRIES_PATH)
@@ -209,7 +203,7 @@ public void getRegisteredEnquiries_Should_returnBadRequest_When_countIsLowerThan
}
@Test
- public void acceptAnonymousEnquiry_Should_returnOk_When_requestParamsAreValid() throws Exception {
+ void acceptAnonymousEnquiry_Should_returnOk_When_requestParamsAreValid() throws Exception {
this.mvc
.perform(
put(ACCEPT_ANONYMOUS_ENQUIRY_PATH).header(RC_TOKEN_HEADER_PARAMETER_NAME, RC_TOKEN))
@@ -219,8 +213,7 @@ public void acceptAnonymousEnquiry_Should_returnOk_When_requestParamsAreValid()
}
@Test
- public void acceptAnonymousEnquiry_Should_returnBadRequest_When_sessionIdIsInvalid()
- throws Exception {
+ void acceptAnonymousEnquiry_Should_returnBadRequest_When_sessionIdIsInvalid() throws Exception {
this.mvc
.perform(
put(ACCEPT_ANONYMOUS_ENQUIRY_PATH.replace("1", "invalid"))
@@ -231,7 +224,7 @@ public void acceptAnonymousEnquiry_Should_returnBadRequest_When_sessionIdIsInval
}
@Test
- public void createAnonymousEnquiry_Should_ReturnCreated_WhenProvidedWithValidRequestBody()
+ void createAnonymousEnquiry_Should_ReturnCreated_WhenProvidedWithValidRequestBody()
throws Exception {
this.mvc
.perform(
@@ -246,7 +239,7 @@ public void createAnonymousEnquiry_Should_ReturnCreated_WhenProvidedWithValidReq
}
@Test
- public void createAnonymousEnquiry_Should_ReturnBadRequest_WhenProvidedWithInvalidRequestBody()
+ void createAnonymousEnquiry_Should_ReturnBadRequest_WhenProvidedWithInvalidRequestBody()
throws Exception {
this.mvc
.perform(
@@ -258,7 +251,7 @@ public void createAnonymousEnquiry_Should_ReturnBadRequest_WhenProvidedWithInval
}
@Test
- public void finishAnonymousConversation_Should_ReturnBadRequest_WhenProvidedWithInvalidSessionId()
+ void finishAnonymousConversation_Should_ReturnBadRequest_WhenProvidedWithInvalidSessionId()
throws Exception {
this.mvc
.perform(
@@ -269,7 +262,7 @@ public void finishAnonymousConversation_Should_ReturnBadRequest_WhenProvidedWith
}
@Test
- public void finishAnonymousConversation_Should_ReturnOk_WhenProvidedWithValidSessionId()
+ void finishAnonymousConversation_Should_ReturnOk_WhenProvidedWithValidSessionId()
throws Exception {
this.mvc
.perform(
diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/LiveProxyControllerIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/LiveProxyControllerIT.java
index 4a7c84624..110c62651 100644
--- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/LiveProxyControllerIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/LiveProxyControllerIT.java
@@ -9,22 +9,20 @@
import de.caritas.cob.userservice.api.config.auth.RoleAuthorizationAuthorityMapper;
import de.caritas.cob.userservice.api.service.liveevents.LiveEventNotificationService;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.keycloak.adapters.KeycloakConfigResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.hateoas.client.LinkDiscoverers;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
-@RunWith(SpringRunner.class)
@WebMvcTest(LiveProxyController.class)
@AutoConfigureMockMvc(addFilters = false)
@TestPropertySource(properties = "spring.profiles.active=testing")
-public class LiveProxyControllerIT {
+class LiveProxyControllerIT {
private static final String LIVE_EVENT_PATH = "/liveproxy/send";
@@ -36,16 +34,17 @@ public class LiveProxyControllerIT {
@MockBean private LinkDiscoverers linkDiscoverers;
+ @MockBean private KeycloakConfigResolver keycloakConfigResolver;
+
@Test
- public void sendLiveEvent_Should_returnBadRequest_When_rcGroupIdIsNotProvided() throws Exception {
+ void sendLiveEvent_Should_returnBadRequest_When_rcGroupIdIsNotProvided() throws Exception {
this.mockMvc.perform(post(LIVE_EVENT_PATH)).andExpect(status().isBadRequest());
verifyNoInteractions(liveEventNotificationService);
}
@Test
- public void sendLiveEvent_Should_returnStatusOkAndUseMock_When_rcGroupIdIsProvided()
- throws Exception {
+ void sendLiveEvent_Should_returnStatusOkAndUseMock_When_rcGroupIdIsProvided() throws Exception {
this.mockMvc.perform(post(LIVE_EVENT_PATH).param("rcGroupId", "id")).andExpect(status().isOk());
verify(liveEventNotificationService, times(1)).sendLiveDirectMessageEventToUsers(eq("id"));
diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerAuthorizationIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerAuthorizationIT.java
index 499b05b80..db9e018ae 100644
--- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerAuthorizationIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerAuthorizationIT.java
@@ -36,8 +36,7 @@
import java.util.UUID;
import javax.servlet.http.Cookie;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
@@ -47,10 +46,8 @@
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
-@RunWith(SpringRunner.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@SpringBootTest
@AutoConfigureMockMvc
diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerIT.java
index 431df4403..13b55c0c1 100644
--- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerIT.java
@@ -37,8 +37,8 @@
import java.util.ArrayList;
import java.util.UUID;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.keycloak.adapters.KeycloakConfigResolver;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
@@ -48,14 +48,12 @@
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.hateoas.client.LinkDiscoverers;
import org.springframework.http.MediaType;
-import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
-@RunWith(SpringRunner.class)
@WebMvcTest(UserAdminController.class)
@AutoConfigureMockMvc(addFilters = false)
@AutoConfigureTestDatabase(replace = Replace.ANY)
-public class UserAdminControllerIT {
+class UserAdminControllerIT {
protected static final String ROOT_PATH = "/useradmin";
protected static final String SESSION_PATH = ROOT_PATH + "/sessions";
@@ -113,14 +111,16 @@ public class UserAdminControllerIT {
@MockBean private AuthenticatedUser authenticatedUser;
+ @MockBean private KeycloakConfigResolver keycloakConfigResolver;
+
@Test
- public void getSessions_Should_returnBadRequest_When_requiredPaginationParamsAreMissing()
+ void getSessions_Should_returnBadRequest_When_requiredPaginationParamsAreMissing()
throws Exception {
this.mvc.perform(get(SESSION_PATH)).andExpect(status().isBadRequest());
}
@Test
- public void getRoot_Should_returnExpectedRootDTO() throws Exception {
+ void getRoot_Should_returnExpectedRootDTO() throws Exception {
this.mvc
.perform(get(ROOT_PATH))
.andExpect(status().isOk())
@@ -137,7 +137,7 @@ public void getRoot_Should_returnExpectedRootDTO() throws Exception {
}
@Test
- public void getSessions_Should_returnOk_When_requiredPaginationParamsAreGiven() throws Exception {
+ void getSessions_Should_returnOk_When_requiredPaginationParamsAreGiven() throws Exception {
this.mvc
.perform(get(SESSION_PATH).param(PAGE_PARAM, "0").param(PER_PAGE_PARAM, "1"))
.andExpect(status().isOk());
@@ -146,7 +146,7 @@ public void getSessions_Should_returnOk_When_requiredPaginationParamsAreGiven()
}
@Test
- public void getConsultantAgency_Should_returnOk_When_requiredConsultantIdParamIsGiven()
+ void getConsultantAgency_Should_returnOk_When_requiredConsultantIdParamIsGiven()
throws Exception {
String consultantId = "1da238c6-cd46-4162-80f1-bff74eafeAAA";
@@ -158,21 +158,20 @@ public void getConsultantAgency_Should_returnOk_When_requiredConsultantIdParamIs
}
@Test
- public void generateReport_Should_returnOk() throws Exception {
+ void generateReport_Should_returnOk() throws Exception {
this.mvc.perform(get(REPORT_PATH)).andExpect(status().isOk());
verify(this.violationReportGenerator, times(1)).generateReport();
}
@Test
- public void getConsultants_Should_returnBadRequest_When_requiredPaginationParamsAreMissing()
+ void getConsultants_Should_returnBadRequest_When_requiredPaginationParamsAreMissing()
throws Exception {
this.mvc.perform(get(FILTERED_CONSULTANTS_PATH)).andExpect(status().isBadRequest());
}
@Test
- public void getConsultants_Should_returnOk_When_requiredPaginationParamsAreGiven()
- throws Exception {
+ void getConsultants_Should_returnOk_When_requiredPaginationParamsAreGiven() throws Exception {
this.mvc
.perform(get(FILTERED_CONSULTANTS_PATH).param(PAGE_PARAM, "0").param(PER_PAGE_PARAM, "1"))
.andExpect(status().isOk());
@@ -182,24 +181,21 @@ public void getConsultants_Should_returnOk_When_requiredPaginationParamsAreGiven
}
@Test
- public void getConsultant_Should_returnOk_When_requiredConsultantIdParamIsGiven()
- throws Exception {
+ void getConsultant_Should_returnOk_When_requiredConsultantIdParamIsGiven() throws Exception {
this.mvc.perform(get(CONSULTANT_PATH + "consultantId")).andExpect(status().isOk());
verify(this.consultantAdminFacade, times(1)).findConsultant("consultantId");
}
@Test
- public void getConsultant_Should_returnNoContent_When_requiredConsultantDoesNotExist()
- throws Exception {
+ void getConsultant_Should_returnNoContent_When_requiredConsultantDoesNotExist() throws Exception {
when(this.consultantAdminFacade.findConsultant(any())).thenThrow(new NoContentException(""));
this.mvc.perform(get(CONSULTANT_PATH + "consultantId")).andExpect(status().isNoContent());
}
@Test
- public void createConsultant_Should_returnOk_When_requiredCreateConsultantIsGiven()
- throws Exception {
+ void createConsultant_Should_returnOk_When_requiredCreateConsultantIsGiven() throws Exception {
CreateConsultantDTO createConsultantDTO =
new EasyRandom().nextObject(CreateConsultantDTO.class);
@@ -214,7 +210,7 @@ public void createConsultant_Should_returnOk_When_requiredCreateConsultantIsGive
}
@Test
- public void createConsultant_Should_returnBadRequest_When_requiredCreateConsultantIsMissing()
+ void createConsultant_Should_returnBadRequest_When_requiredCreateConsultantIsMissing()
throws Exception {
this.mvc
.perform(post(CONSULTANT_PATH).contentType(MediaType.APPLICATION_JSON))
@@ -222,8 +218,7 @@ public void createConsultant_Should_returnBadRequest_When_requiredCreateConsulta
}
@Test
- public void updateConsultant_Should_returnOk_When_requiredCreateConsultantIsGiven()
- throws Exception {
+ void updateConsultant_Should_returnOk_When_requiredCreateConsultantIsGiven() throws Exception {
UpdateAdminConsultantDTO updateConsultantDTO =
new EasyRandom().nextObject(UpdateAdminConsultantDTO.class);
@@ -238,16 +233,14 @@ public void updateConsultant_Should_returnOk_When_requiredCreateConsultantIsGive
}
@Test
- public void updateConsultant_Should_returnBadRequest_When_requiredParamsAreMissing()
- throws Exception {
+ void updateConsultant_Should_returnBadRequest_When_requiredParamsAreMissing() throws Exception {
this.mvc
.perform(put(CONSULTANT_PATH + "consultantId").contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest());
}
@Test
- public void createConsultantAgency_Should_returnCreated_When_requiredParamsAreGiven()
- throws Exception {
+ void createConsultantAgency_Should_returnCreated_When_requiredParamsAreGiven() throws Exception {
String consultantId = "1da238c6-cd46-4162-80f1-bff74eafeAAA";
String consultantAgencyPath = String.format(CONSULTANT_AGENCY_PATH, consultantId);
@@ -268,7 +261,7 @@ public void createConsultantAgency_Should_returnCreated_When_requiredParamsAreGi
}
@Test
- public void setConsultantAgencies_ShouldReturnOk_When_RequiredParamsAreGiven() throws Exception {
+ void setConsultantAgencies_ShouldReturnOk_When_RequiredParamsAreGiven() throws Exception {
var consultantId = UUID.randomUUID().toString();
var agencies = givenAgenciesToSet();
@@ -286,7 +279,7 @@ public void setConsultantAgencies_ShouldReturnOk_When_RequiredParamsAreGiven() t
}
@Test
- public void
+ void
setConsultantAgencies_Should_ReturnForbiddenIfUserDoesNotHavePermissionsToTheRequestedAgency()
throws Exception {
var consultantId = UUID.randomUUID().toString();
@@ -304,7 +297,7 @@ public void setConsultantAgencies_ShouldReturnOk_When_RequiredParamsAreGiven() t
}
@Test
- public void changeAgencyType_Should_returnOk_When_parametersAreValid() throws Exception {
+ void changeAgencyType_Should_returnOk_When_parametersAreValid() throws Exception {
this.mvc
.perform(post(AGENCY_CHANGE_TYPE_PATH).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
@@ -313,8 +306,7 @@ public void changeAgencyType_Should_returnOk_When_parametersAreValid() throws Ex
}
@Test
- public void deleteConsultantAgency_Should_returnOk_When_requiredParamsAreGiven()
- throws Exception {
+ void deleteConsultantAgency_Should_returnOk_When_requiredParamsAreGiven() throws Exception {
String consultantId = "1da238c6-cd46-4162-80f1-bff74eafeAAA";
Long agencyId = 1L;
@@ -330,7 +322,7 @@ public void deleteConsultantAgency_Should_returnOk_When_requiredParamsAreGiven()
}
@Test
- public void deleteConsultant_Should_returnOk_When_requiredParamIsGiven() throws Exception {
+ void deleteConsultant_Should_returnOk_When_requiredParamIsGiven() throws Exception {
this.mvc
.perform(delete(DELETE_CONSULTANT_PATH).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
@@ -339,7 +331,7 @@ public void deleteConsultant_Should_returnOk_When_requiredParamIsGiven() throws
}
@Test
- public void deleteConsultant_Should_returnOk_When_requiredParamIsGivenAndForceDeleteToTrue()
+ void deleteConsultant_Should_returnOk_When_requiredParamIsGivenAndForceDeleteToTrue()
throws Exception {
this.mvc
.perform(
@@ -351,7 +343,7 @@ public void deleteConsultant_Should_returnOk_When_requiredParamIsGivenAndForceDe
}
@Test
- public void deleteAsker_Should_returnOk_When_requiredParamIsGiven() throws Exception {
+ void deleteAsker_Should_returnOk_When_requiredParamIsGiven() throws Exception {
this.mvc
.perform(delete(DELETE_ASKER_PATH).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
@@ -360,8 +352,7 @@ public void deleteAsker_Should_returnOk_When_requiredParamIsGiven() throws Excep
}
@Test
- public void getAgencyConsultants_Should_returnOk_When_requiredAgencyIdParamIsGiven()
- throws Exception {
+ void getAgencyConsultants_Should_returnOk_When_requiredAgencyIdParamIsGiven() throws Exception {
var agencyId = "1";
var agencyConsultantsPath = String.format(AGENCY_CONSULTANT_PATH, agencyId);
@@ -371,14 +362,13 @@ public void getAgencyConsultants_Should_returnOk_When_requiredAgencyIdParamIsGiv
}
@Test
- public void getAgencyAdmins_Should_returnBadRequest_When_requiredPaginationParamsAreMissing()
+ void getAgencyAdmins_Should_returnBadRequest_When_requiredPaginationParamsAreMissing()
throws Exception {
this.mvc.perform(get(AGENCY_ADMIN_PATH)).andExpect(status().isBadRequest());
}
@Test
- public void getAgencyAdmins_Should_returnOk_When_requiredPaginationParamsAreGiven()
- throws Exception {
+ void getAgencyAdmins_Should_returnOk_When_requiredPaginationParamsAreGiven() throws Exception {
// given
// when
this.mvc
@@ -390,7 +380,7 @@ public void getAgencyAdmins_Should_returnOk_When_requiredPaginationParamsAreGive
}
@Test
- public void getAgencyAdmin_Should_returnOk_When_requiredAdminIdParamIsGiven() throws Exception {
+ void getAgencyAdmin_Should_returnOk_When_requiredAdminIdParamIsGiven() throws Exception {
// given
String adminId = "adminId";
@@ -402,8 +392,7 @@ public void getAgencyAdmin_Should_returnOk_When_requiredAdminIdParamIsGiven() th
}
@Test
- public void getAgencyAdmin_Should_returnNoContent_When_requiredAdminDoesNotExist()
- throws Exception {
+ void getAgencyAdmin_Should_returnNoContent_When_requiredAdminDoesNotExist() throws Exception {
// given
when(this.consultantAdminFacade.findConsultant(any())).thenThrow(new NoContentException(""));
@@ -417,7 +406,7 @@ public void getAgencyAdmin_Should_returnNoContent_When_requiredAdminDoesNotExist
}
@Test
- public void createNewAdminAgency_Should_returnOk_When_requiredCreateAgencyAdminIsGiven()
+ void createNewAdminAgency_Should_returnOk_When_requiredCreateAgencyAdminIsGiven()
throws Exception {
// given
CreateAdminDTO createAgencyAdminDTO = new EasyRandom().nextObject(CreateAdminDTO.class);
@@ -435,7 +424,7 @@ public void createNewAdminAgency_Should_returnOk_When_requiredCreateAgencyAdminI
}
@Test
- public void createNewTenantAdmin_Should_returnOk_When_requiredCreateTenantAdminIsGiven()
+ void createNewTenantAdmin_Should_returnOk_When_requiredCreateTenantAdminIsGiven()
throws Exception {
// given
CreateAdminDTO createAdminDTO = new EasyRandom().nextObject(CreateAdminDTO.class);
@@ -453,7 +442,7 @@ public void createNewTenantAdmin_Should_returnOk_When_requiredCreateTenantAdminI
}
@Test
- public void createAgencyAdmin_Should_returnBadRequest_When_requiredCreateAgencyAdminIsMissing()
+ void createAgencyAdmin_Should_returnBadRequest_When_requiredCreateAgencyAdminIsMissing()
throws Exception {
// given
// when
@@ -464,8 +453,7 @@ public void createAgencyAdmin_Should_returnBadRequest_When_requiredCreateAgencyA
}
@Test
- public void updateAgencyAdmin_Should_returnOk_When_requiredCreateAgencyAdminIsGiven()
- throws Exception {
+ void updateAgencyAdmin_Should_returnOk_When_requiredCreateAgencyAdminIsGiven() throws Exception {
// given
UpdateAgencyAdminDTO updateAgencyAdminDTO =
new EasyRandom().nextObject(UpdateAgencyAdminDTO.class);
@@ -484,8 +472,7 @@ public void updateAgencyAdmin_Should_returnOk_When_requiredCreateAgencyAdminIsGi
}
@Test
- public void updateTenantAdmin_Should_returnOk_When_requiredCreateTenantAdminIsGiven()
- throws Exception {
+ void updateTenantAdmin_Should_returnOk_When_requiredCreateTenantAdminIsGiven() throws Exception {
// given
UpdateAgencyAdminDTO updateAgencyAdminDTO =
new EasyRandom().nextObject(UpdateAgencyAdminDTO.class);
@@ -504,8 +491,7 @@ public void updateTenantAdmin_Should_returnOk_When_requiredCreateTenantAdminIsGi
}
@Test
- public void updateAgencyAdmin_Should_returnBadRequest_When_requiredParamsAreMissing()
- throws Exception {
+ void updateAgencyAdmin_Should_returnBadRequest_When_requiredParamsAreMissing() throws Exception {
// given
// when
this.mvc
@@ -515,8 +501,7 @@ public void updateAgencyAdmin_Should_returnBadRequest_When_requiredParamsAreMiss
}
@Test
- public void createAdminAgency_Should_returnCreated_When_requiredParamsAreGiven()
- throws Exception {
+ void createAdminAgency_Should_returnCreated_When_requiredParamsAreGiven() throws Exception {
String adminId = "1da238c6-cd46-4162-80f1-bff74eafeAAA";
// given
@@ -539,7 +524,7 @@ public void createAdminAgency_Should_returnCreated_When_requiredParamsAreGiven()
}
@Test
- public void setAdminAgencies_Should_return_ok_When_RequiredParams_Are_Given() throws Exception {
+ void setAdminAgencies_Should_return_ok_When_RequiredParams_Are_Given() throws Exception {
// given
var adminId = UUID.randomUUID().toString();
var agencies = givenAgenciesToSet();
@@ -556,7 +541,7 @@ public void setAdminAgencies_Should_return_ok_When_RequiredParams_Are_Given() th
}
@Test
- public void deleteAdminAgency_Should_return_Ok_When_requiredParamsAreGiven() throws Exception {
+ void deleteAdminAgency_Should_return_Ok_When_requiredParamsAreGiven() throws Exception {
// given
String adminId = "1da238c6-cd46-4162-80f1-bff74eafeAAA";
Long agencyId = 1L;
@@ -573,7 +558,7 @@ public void deleteAdminAgency_Should_return_Ok_When_requiredParamsAreGiven() thr
}
@Test
- public void deleteAgencyAdmin_Should_returnOk_When_requiredParamIsGiven() throws Exception {
+ void deleteAgencyAdmin_Should_returnOk_When_requiredParamIsGiven() throws Exception {
// given
String adminId = "1234";
diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerConsultantE2EIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerConsultantE2EIT.java
index fb2ef8c3e..00858141c 100644
--- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerConsultantE2EIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerConsultantE2EIT.java
@@ -685,7 +685,7 @@ void searchConsultantsShouldRespondOkAndPayloadIfStarQueryIsGiven() throws Excep
.andExpect(jsonPath("_embedded[0]._links.addAgency.method", is("POST")))
.andExpect(jsonPath("_embedded[0]._links.addAgency.templated", is(false)))
.andExpect(jsonPath("_links.self.href", startsWith(pageUrlPrefix)))
- .andExpect(jsonPath("_links.self.href", containsString("query=*")))
+ .andExpect(jsonPath("_links.self.href", containsString("query=")))
.andExpect(jsonPath("_links.self.method", is("GET")))
.andExpect(jsonPath("_links.self.templated", is(false)))
.andExpect(jsonPath("_links.next", is(nullValue())))
diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java
index ce54c7bd2..aa929c53c 100644
--- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java
@@ -7,8 +7,8 @@
import static de.caritas.cob.userservice.api.testHelper.RequestBodyConstants.*;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.*;
import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
import static org.powermock.reflect.Whitebox.setInternalState;
@@ -63,9 +63,9 @@
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.hibernate.service.spi.ServiceException;
import org.jeasy.random.EasyRandom;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.keycloak.adapters.KeycloakConfigResolver;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
@@ -79,14 +79,12 @@
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
-@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
@AutoConfigureMockMvc(addFilters = false)
@TestPropertySource(properties = "spring.profiles.active=testing,feature.topics.enabled=true")
-public class UserControllerIT {
+class UserControllerIT {
private static final Cookie RC_TOKEN_COOKIE =
new Cookie("rc_token", RandomStringUtils.randomAlphanumeric(43));
@@ -284,6 +282,8 @@ public class UserControllerIT {
@MockBean private GetChatMembersFacade getChatMembersFacade;
@MockBean private CreateUserFacade createUserFacade;
+ @MockBean KeycloakConfigResolver resolver;
+
@MockBean
@SuppressWarnings("unused")
private RoleAuthorizationAuthorityMapper roleAuthorizationAuthorityMapper;
@@ -353,8 +353,8 @@ public class UserControllerIT {
@Mock private Chat chat;
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
HashMap drugsMap = new HashMap<>();
drugsMap.put("others", false);
HashMap addictiveDrugsMap = new HashMap<>();
@@ -366,7 +366,7 @@ public void setUp() {
}
@Test
- public void userExists_Should_Return404_When_UserDoesNotExist() throws Exception {
+ void userExists_Should_Return404_When_UserDoesNotExist() throws Exception {
/* given */
val username = "john@doe.com";
when(identityClient.isUsernameAvailable(username)).thenReturn(Boolean.TRUE);
@@ -377,7 +377,7 @@ public void userExists_Should_Return404_When_UserDoesNotExist() throws Exception
}
@Test
- public void userExists_Should_Return200_When_UserDoesExist() throws Exception {
+ void userExists_Should_Return200_When_UserDoesExist() throws Exception {
/* given */
val username = "john@doe.com";
when(identityClient.isUsernameAvailable(username)).thenReturn(Boolean.FALSE);
@@ -390,8 +390,7 @@ public void userExists_Should_Return200_When_UserDoesExist() throws Exception {
/** Method: registerUser */
@Test
- public void registerUser_Should_ReturnBadRequest_WhenProvidedWithInvalidRequestBody()
- throws Exception {
+ void registerUser_Should_ReturnBadRequest_WhenProvidedWithInvalidRequestBody() throws Exception {
mvc.perform(
post(PATH_REGISTER_USER)
@@ -402,7 +401,7 @@ public void registerUser_Should_ReturnBadRequest_WhenProvidedWithInvalidRequestB
}
@Test
- public void
+ void
registerUser_Should_ReturnBadRequest_WhenProvidedWithConsultingTypeWithMandatoryFieldsAndInvalidAge()
throws Exception {
@@ -418,7 +417,7 @@ public void registerUser_Should_ReturnBadRequest_WhenProvidedWithInvalidRequestB
}
@Test
- public void
+ void
registerUser_Should_ReturnBadRequest_WhenProvidedWithConsultingTypeWithMandatoryFieldsAndInvalidState()
throws Exception {
@@ -438,8 +437,7 @@ public void registerUser_Should_ReturnBadRequest_WhenProvidedWithInvalidRequestB
}
@Test
- public void registerUser_Should_ReturnBadRequest_WhenProvidedUsernameIsTooShort()
- throws Exception {
+ void registerUser_Should_ReturnBadRequest_WhenProvidedUsernameIsTooShort() throws Exception {
when(consultingTypeManager.getConsultingTypeSettings(0))
.thenReturn(CONSULTING_TYPE_SETTINGS_WITHOUT_MANDATORY_FIELDS);
@@ -453,9 +451,8 @@ public void registerUser_Should_ReturnBadRequest_WhenProvidedUsernameIsTooShort(
}
@Test
- public void
- activateTwoFactorAuthByApp_Should_NotActivateIfSingleTenantAdminButNotConfiguredToUse2Fa()
- throws Exception {
+ void activateTwoFactorAuthByApp_Should_NotActivateIfSingleTenantAdminButNotConfiguredToUse2Fa()
+ throws Exception {
when(authenticatedUser.isSingleTenantAdmin()).thenReturn(true);
when(identityClientConfig.getOtpAllowedForSingleTenantAdmins()).thenReturn(false);
@@ -469,9 +466,8 @@ public void registerUser_Should_ReturnBadRequest_WhenProvidedUsernameIsTooShort(
}
@Test
- public void
- activateTwoFactorAuthByApp_Should_NotActivateIfTenantSuperAdminButNotConfiguredToUse2Fa()
- throws Exception {
+ void activateTwoFactorAuthByApp_Should_NotActivateIfTenantSuperAdminButNotConfiguredToUse2Fa()
+ throws Exception {
when(authenticatedUser.isTenantSuperAdmin()).thenReturn(true);
when(identityClientConfig.getOtpAllowedForTenantSuperAdmins()).thenReturn(false);
@@ -485,7 +481,7 @@ public void registerUser_Should_ReturnBadRequest_WhenProvidedUsernameIsTooShort(
}
@Test
- public void activateTwoFactorAuthByApp_Should_Activate() throws Exception {
+ void activateTwoFactorAuthByApp_Should_Activate() throws Exception {
when(authenticatedUser.getUsername()).thenReturn("username");
when(identityManager.setUpOneTimePassword(anyString(), anyString(), anyString()))
.thenReturn(true);
@@ -500,8 +496,7 @@ public void activateTwoFactorAuthByApp_Should_Activate() throws Exception {
}
@Test
- public void registerUser_Should_ReturnBadRequest_WhenProvidedUsernameIsTooLong()
- throws Exception {
+ void registerUser_Should_ReturnBadRequest_WhenProvidedUsernameIsTooLong() throws Exception {
when(consultingTypeManager.getConsultingTypeSettings(0))
.thenReturn(CONSULTING_TYPE_SETTINGS_WITHOUT_MANDATORY_FIELDS);
@@ -515,7 +510,7 @@ public void registerUser_Should_ReturnBadRequest_WhenProvidedUsernameIsTooLong()
}
@Test
- public void
+ void
registerUser_Should_ReturnCreated_WhenProvidedWithValidRequestBodyAndKeycloakResponseIsSuccessful()
throws Exception {
when(userHelper.isUsernameValid(anyString())).thenReturn(true);
@@ -535,7 +530,7 @@ public void registerUser_Should_ReturnBadRequest_WhenProvidedUsernameIsTooLong()
}
@Test
- public void
+ void
registerUser_Should_ReturnCreated_WhenProvidedWithValidU25RequestBodyAndKeycloakResponseIsSuccessful()
throws Exception {
when(userHelper.isUsernameValid(anyString())).thenReturn(true);
@@ -555,7 +550,7 @@ public void registerUser_Should_ReturnBadRequest_WhenProvidedUsernameIsTooLong()
}
@Test
- public void
+ void
registerUser_Should_ReturnConflict_WhenProvidedWithValidRequestBodyAndKeycloakResponseIsConflict()
throws Exception {
when(userHelper.isUsernameValid(anyString())).thenReturn(true);
@@ -578,7 +573,7 @@ public void registerUser_Should_ReturnBadRequest_WhenProvidedUsernameIsTooLong()
}
@Test
- public void registerUser_Should_ReturnBadRequest_When_PostcodeIsMissing() throws Exception {
+ void registerUser_Should_ReturnBadRequest_When_PostcodeIsMissing() throws Exception {
when(mandatoryFieldsProvider.fetchMandatoryFieldsForConsultingType(anyString()))
.thenReturn(
@@ -596,7 +591,7 @@ public void registerUser_Should_ReturnBadRequest_When_PostcodeIsMissing() throws
}
@Test
- public void registerUser_Should_ReturnBadRequest_When_PostcodeIsInvalid() throws Exception {
+ void registerUser_Should_ReturnBadRequest_When_PostcodeIsInvalid() throws Exception {
when(mandatoryFieldsProvider.fetchMandatoryFieldsForConsultingType(anyString()))
.thenReturn(
@@ -615,9 +610,8 @@ public void registerUser_Should_ReturnBadRequest_When_PostcodeIsInvalid() throws
/** Method: registerNewConsultingType */
@Test
- public void
- registerNewConsultingType_Should_ReturnBadRequest_When_ProvidedWithInvalidRequestBody()
- throws Exception {
+ void registerNewConsultingType_Should_ReturnBadRequest_When_ProvidedWithInvalidRequestBody()
+ throws Exception {
mvc.perform(
post(PATH_POST_REGISTER_NEW_CONSULTING_TYPE)
.header(RC_USER_ID_HEADER_PARAMETER_NAME, RC_USER_ID)
@@ -629,8 +623,7 @@ public void registerUser_Should_ReturnBadRequest_When_PostcodeIsInvalid() throws
}
@Test
- public void registerNewConsultingType_Should_ReturnBadRequest_When_PostcodeIsInvalid()
- throws Exception {
+ void registerNewConsultingType_Should_ReturnBadRequest_When_PostcodeIsInvalid() throws Exception {
mvc.perform(
post(PATH_POST_REGISTER_NEW_CONSULTING_TYPE)
.header(RC_USER_ID_HEADER_PARAMETER_NAME, RC_USER_ID)
@@ -642,8 +635,7 @@ public void registerNewConsultingType_Should_ReturnBadRequest_When_PostcodeIsInv
}
@Test
- public void registerNewConsultingType_Should_ReturnBadRequest_When_PostcodeIsMissing()
- throws Exception {
+ void registerNewConsultingType_Should_ReturnBadRequest_When_PostcodeIsMissing() throws Exception {
mvc.perform(
post(PATH_POST_REGISTER_NEW_CONSULTING_TYPE)
.header(RC_USER_ID_HEADER_PARAMETER_NAME, RC_USER_ID)
@@ -655,8 +647,7 @@ public void registerNewConsultingType_Should_ReturnBadRequest_When_PostcodeIsMis
}
@Test
- public void registerNewConsultingType_Should_ReturnBadRequest_When_AgencyIdMissing()
- throws Exception {
+ void registerNewConsultingType_Should_ReturnBadRequest_When_AgencyIdMissing() throws Exception {
when(consultingTypeManager.getConsultingTypeSettings(any()))
.thenReturn(CONSULTING_TYPE_SETTINGS_SUCHT);
@@ -671,7 +662,7 @@ public void registerNewConsultingType_Should_ReturnBadRequest_When_AgencyIdMissi
}
@Test
- public void registerNewConsultingType_Should_ReturnBadRequest_When_ConsultingTypeMissing()
+ void registerNewConsultingType_Should_ReturnBadRequest_When_ConsultingTypeMissing()
throws Exception {
mvc.perform(
post(PATH_POST_REGISTER_NEW_CONSULTING_TYPE)
@@ -684,8 +675,7 @@ public void registerNewConsultingType_Should_ReturnBadRequest_When_ConsultingTyp
}
@Test
- public void registerNewConsultingType_Should_ReturnBadRequest_When_RcUserIdIsMissing()
- throws Exception {
+ void registerNewConsultingType_Should_ReturnBadRequest_When_RcUserIdIsMissing() throws Exception {
mvc.perform(
post(PATH_POST_REGISTER_NEW_CONSULTING_TYPE)
.header(RC_TOKEN_HEADER_PARAMETER_NAME, RC_TOKEN)
@@ -696,8 +686,7 @@ public void registerNewConsultingType_Should_ReturnBadRequest_When_RcUserIdIsMis
}
@Test
- public void registerNewConsultingType_Should_ReturnBadRequest_When_RcTokenIsMissing()
- throws Exception {
+ void registerNewConsultingType_Should_ReturnBadRequest_When_RcTokenIsMissing() throws Exception {
mvc.perform(
post(PATH_POST_REGISTER_NEW_CONSULTING_TYPE)
.header(RC_USER_ID_HEADER_PARAMETER_NAME, RC_USER_ID)
@@ -708,7 +697,7 @@ public void registerNewConsultingType_Should_ReturnBadRequest_When_RcTokenIsMiss
}
@Test
- public void registerNewConsultingTyp_Should_ReturnCreated_When_ProvidedWithValidRequestBody()
+ void registerNewConsultingTyp_Should_ReturnCreated_When_ProvidedWithValidRequestBody()
throws Exception {
when(accountProvider.retrieveValidatedUser()).thenReturn(USER);
@@ -730,8 +719,7 @@ public void registerNewConsultingTyp_Should_ReturnCreated_When_ProvidedWithValid
/** Method: acceptEnquiry */
@Test
- public void acceptEnquiry_Should_ReturnInternalServerError_WhenNoConsultantInDbFound()
- throws Exception {
+ void acceptEnquiry_Should_ReturnInternalServerError_WhenNoConsultantInDbFound() throws Exception {
when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.of(SESSION));
when(authenticatedUser.getUserId()).thenReturn(CONSULTANT_ID);
@@ -749,8 +737,7 @@ public void acceptEnquiry_Should_ReturnInternalServerError_WhenNoConsultantInDbF
}
@Test
- public void acceptEnquiry_Should_ReturnInternalServerError_WhenSessionNotFoundInDb()
- throws Exception {
+ void acceptEnquiry_Should_ReturnInternalServerError_WhenSessionNotFoundInDb() throws Exception {
when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.empty());
when(authenticatedUser.getUserId()).thenReturn(CONSULTANT_ID);
@@ -767,7 +754,7 @@ public void acceptEnquiry_Should_ReturnInternalServerError_WhenSessionNotFoundIn
}
@Test
- public void acceptEnquiry_Should_ReturnInternalServerError_WhenSessionHasNoRocketChatGroupId()
+ void acceptEnquiry_Should_ReturnInternalServerError_WhenSessionHasNoRocketChatGroupId()
throws Exception {
when(sessionService.getSession(SESSION_ID))
@@ -786,7 +773,7 @@ public void acceptEnquiry_Should_ReturnInternalServerError_WhenSessionHasNoRocke
}
@Test
- public void acceptEnquiry_Should_ReturnSuccess_WhenAcceptEnquiryIsSuccessfull() throws Exception {
+ void acceptEnquiry_Should_ReturnSuccess_WhenAcceptEnquiryIsSuccessfull() throws Exception {
when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.of(TEAM_SESSION));
when(authenticatedUser.getUserId()).thenReturn(CONSULTANT_ID);
@@ -801,7 +788,7 @@ public void acceptEnquiry_Should_ReturnSuccess_WhenAcceptEnquiryIsSuccessfull()
}
@Test
- public void acceptEnquiry_Should_ReturnConflict_WhenEnquiryIsAlreadyAssigned() throws Exception {
+ void acceptEnquiry_Should_ReturnConflict_WhenEnquiryIsAlreadyAssigned() throws Exception {
when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.of(TEAM_SESSION));
when(authenticatedUser.getUserId()).thenReturn(CONSULTANT_ID);
@@ -819,7 +806,7 @@ public void acceptEnquiry_Should_ReturnConflict_WhenEnquiryIsAlreadyAssigned() t
}
@Test
- public void
+ void
acceptEnquiry_Should_ReturnInternalServerError_WhenAuthenticatedUserIsNotPresentInApplicationDb()
throws Exception {
@@ -837,8 +824,7 @@ public void acceptEnquiry_Should_ReturnConflict_WhenEnquiryIsAlreadyAssigned() t
}
@Test
- public void createEnquiryMessage_Should_ReturnConflict_WhenMessageIsAlreadyCreated()
- throws Exception {
+ void createEnquiryMessage_Should_ReturnConflict_WhenMessageIsAlreadyCreated() throws Exception {
when(authenticatedUser.getUserId()).thenReturn(USER_ID);
when(accountProvider.retrieveValidatedUser()).thenReturn(USER);
@@ -857,7 +843,7 @@ public void createEnquiryMessage_Should_ReturnConflict_WhenMessageIsAlreadyCreat
}
@Test
- public void createEnquiryMessage_Should_ReturnCreated_WhenMessageWasCreated() throws Exception {
+ void createEnquiryMessage_Should_ReturnCreated_WhenMessageWasCreated() throws Exception {
when(authenticatedUser.getUserId()).thenReturn(USER_ID);
when(accountProvider.retrieveValidatedUser()).thenReturn(USER);
var expectedRCCredentials =
@@ -884,7 +870,7 @@ public void createEnquiryMessage_Should_ReturnCreated_WhenMessageWasCreated() th
}
@Test
- public void
+ void
createEnquiryMessage_Should_ReturnInternalServerError_WhenAuthenticatedUserIsNotPresentInApplicationDb()
throws Exception {
@@ -903,7 +889,7 @@ public void createEnquiryMessage_Should_ReturnCreated_WhenMessageWasCreated() th
/** Method: getSessionsForAuthenticatedUser (role: user) */
@Test
- public void getSessionsForAuthenticatedUser_Should_ReturnUserSessionsAndOk_WhenAuthorized()
+ void getSessionsForAuthenticatedUser_Should_ReturnUserSessionsAndOk_WhenAuthorized()
throws Exception {
List sessions = new ArrayList<>();
@@ -937,7 +923,7 @@ public void getSessionsForAuthenticatedUser_Should_ReturnUserSessionsAndOk_WhenA
}
@Test
- public void
+ void
getSessionsForAuthenticatedUser_Should_ReturnInternalServerError_WhenAuthorizedButUserNotFound()
throws Exception {
@@ -956,7 +942,7 @@ public void getSessionsForAuthenticatedUser_Should_ReturnUserSessionsAndOk_WhenA
}
@Test
- public void
+ void
getSessionsForAuthenticatedUser_Should_ReturnNoContent_WhenAuthorizedAndNoOpenSessionsAvailableAndSessionListIsEmpty()
throws Exception {
List session = new ArrayList<>();
@@ -977,7 +963,7 @@ public void getSessionsForAuthenticatedUser_Should_ReturnUserSessionsAndOk_WhenA
}
@Test
- public void getSessionsForAuthenticatedUser_Should_ReturnBadRequest_WhenHeaderParamIsMissing()
+ void getSessionsForAuthenticatedUser_Should_ReturnBadRequest_WhenHeaderParamIsMissing()
throws Exception {
mvc.perform(
@@ -988,7 +974,7 @@ public void getSessionsForAuthenticatedUser_Should_ReturnBadRequest_WhenHeaderPa
}
@Test
- public void updateAbsence_Should_ReturnOk_When_Saved() throws Exception {
+ void updateAbsence_Should_ReturnOk_When_Saved() throws Exception {
when(authenticatedUser.getUserId()).thenReturn(CONSULTANT_ID);
when(accountProvider.retrieveValidatedTeamConsultant()).thenReturn(TEAM_CONSULTANT);
@@ -1003,7 +989,7 @@ public void updateAbsence_Should_ReturnOk_When_Saved() throws Exception {
}
@Test
- public void updateAbsence_Should_ReturnBadRequest_When_RequestBodyIsMissing() throws Exception {
+ void updateAbsence_Should_ReturnBadRequest_When_RequestBodyIsMissing() throws Exception {
mvc.perform(
put(PATH_PUT_CONSULTANT_ABSENT)
.contentType(MediaType.APPLICATION_JSON)
@@ -1013,9 +999,8 @@ public void updateAbsence_Should_ReturnBadRequest_When_RequestBodyIsMissing() th
/** Method: getSessionsForAuthenticatedConsultant (role: consultant) */
@Test
- public void
- getSessionsForAuthenticatedConsultant_Should_ReturnBadRequest_WhenStatusParamIsMissing()
- throws Exception {
+ void getSessionsForAuthenticatedConsultant_Should_ReturnBadRequest_WhenStatusParamIsMissing()
+ throws Exception {
mvc.perform(
get(PATH_GET_SESSIONS_FOR_AUTHENTICATED_CONSULTANT_WITHOUT_STATUS)
.header(RC_USER_ID_HEADER_PARAMETER_NAME, RC_USER_ID)
@@ -1027,7 +1012,7 @@ public void updateAbsence_Should_ReturnBadRequest_When_RequestBodyIsMissing() th
}
@Test
- public void
+ void
getSessionsForAuthenticatedConsultant_Should_ReturnUnauthorized_WhenUnauthorizedExceptionIsRaised()
throws Exception {
var runtimeException = easyRandom.nextObject(RuntimeException.class);
@@ -1052,9 +1037,8 @@ public void updateAbsence_Should_ReturnBadRequest_When_RequestBodyIsMissing() th
}
@Test
- public void
- getSessionsForAuthenticatedConsultant_Should_ReturnBadRequest_WhenHeaderParamIsMissing()
- throws Exception {
+ void getSessionsForAuthenticatedConsultant_Should_ReturnBadRequest_WhenHeaderParamIsMissing()
+ throws Exception {
mvc.perform(
get(PATH_GET_SESSIONS_FOR_AUTHENTICATED_CONSULTANT)
.contentType(MediaType.APPLICATION_JSON)
@@ -1065,7 +1049,7 @@ public void updateAbsence_Should_ReturnBadRequest_When_RequestBodyIsMissing() th
}
@Test
- public void
+ void
getSessionsForAuthenticatedConsultant_Should_ReturnInternalServerError_WhenNoConsultantInDbFound()
throws Exception {
@@ -1082,7 +1066,7 @@ public void updateAbsence_Should_ReturnBadRequest_When_RequestBodyIsMissing() th
}
@Test
- public void
+ void
getSessionsForAuthenticatedConsultant_Should_ReturnSuccess_WhenAuthorizedAndSessionAvailable()
throws Exception {
when(authenticatedUser.getUserId()).thenReturn(CONSULTANT_ID);
@@ -1097,7 +1081,7 @@ public void updateAbsence_Should_ReturnBadRequest_When_RequestBodyIsMissing() th
}
@Test
- public void
+ void
getSessionsForAuthenticatedConsultant_Should_ReturnNoContent_WhenAuthorizedAndNoSessionsAvailable()
throws Exception {
@@ -1113,7 +1097,7 @@ public void updateAbsence_Should_ReturnBadRequest_When_RequestBodyIsMissing() th
}
@Test
- public void
+ void
getSessionsForAuthenticatedConsultant_Should_ReturnNoContent_WhenAuthorizedAndSessionListIsEmpty()
throws Exception {
@@ -1129,9 +1113,8 @@ public void updateAbsence_Should_ReturnBadRequest_When_RequestBodyIsMissing() th
}
@Test
- public void
- getSessionsForAuthenticatedConsultant_Should_ReturnBadRequest_WhenParamOffestIsMissing()
- throws Exception {
+ void getSessionsForAuthenticatedConsultant_Should_ReturnBadRequest_WhenParamOffestIsMissing()
+ throws Exception {
mvc.perform(
get(PATH_GET_SESSIONS_FOR_AUTHENTICATED_CONSULTANT_WITHOUT_OFFSET)
@@ -1142,7 +1125,7 @@ public void updateAbsence_Should_ReturnBadRequest_When_RequestBodyIsMissing() th
}
@Test
- public void
+ void
getSessionsForAuthenticatedConsultant_Should_ReturnBadRequest_WhenParamOffestHasANegativeValue()
throws Exception {
@@ -1155,9 +1138,8 @@ public void updateAbsence_Should_ReturnBadRequest_When_RequestBodyIsMissing() th
}
@Test
- public void
- getSessionsForAuthenticatedConsultant_Should_ReturnBadRequest_WhenParamCountIsMissing()
- throws Exception {
+ void getSessionsForAuthenticatedConsultant_Should_ReturnBadRequest_WhenParamCountIsMissing()
+ throws Exception {
mvc.perform(
get(PATH_GET_SESSIONS_FOR_AUTHENTICATED_CONSULTANT_WITHOUT_COUNT)
@@ -1168,7 +1150,7 @@ public void updateAbsence_Should_ReturnBadRequest_When_RequestBodyIsMissing() th
}
@Test
- public void
+ void
getSessionsForAuthenticatedConsultant_Should_ReturnBadRequest_WhenParamCountHasANegativeValue()
throws Exception {
@@ -1181,9 +1163,8 @@ public void updateAbsence_Should_ReturnBadRequest_When_RequestBodyIsMissing() th
}
@Test
- public void
- getSessionsForAuthenticatedConsultant_Should_ReturnNotContent_WhenFilterParamIsInvalid()
- throws Exception {
+ void getSessionsForAuthenticatedConsultant_Should_ReturnNotContent_WhenFilterParamIsInvalid()
+ throws Exception {
when(authenticatedUser.getUserId()).thenReturn(CONSULTANT_ID);
when(accountProvider.retrieveValidatedConsultant()).thenReturn(TEAM_CONSULTANT);
@@ -1198,7 +1179,7 @@ public void updateAbsence_Should_ReturnBadRequest_When_RequestBodyIsMissing() th
/** Method: getUserData (role: consultant / user) */
@Test
- public void
+ void
getUserData_ForUser_Should_ReturnInternalServerError_WhenAuthenticatedUserIsNotPresentInApplicationDb()
throws Exception {
@@ -1217,8 +1198,7 @@ public void updateAbsence_Should_ReturnBadRequest_When_RequestBodyIsMissing() th
}
@Test
- public void getUserData_ForSingleTenantAdmin_Should_ReturnUserDataFromKeycloak()
- throws Exception {
+ void getUserData_ForSingleTenantAdmin_Should_ReturnUserDataFromKeycloak() throws Exception {
when(authenticatedUser.isSingleTenantAdmin()).thenReturn(true);
when(keycloakUserDataProvider.retrieveAuthenticatedUserData())
.thenReturn(new UserDataResponseDTO());
@@ -1232,7 +1212,7 @@ public void getUserData_ForSingleTenantAdmin_Should_ReturnUserDataFromKeycloak()
}
@Test
- public void getUserData_ForTenantSuperAdmin_Should_ReturnUserDataFromKeycloak() throws Exception {
+ void getUserData_ForTenantSuperAdmin_Should_ReturnUserDataFromKeycloak() throws Exception {
when(authenticatedUser.isTenantSuperAdmin()).thenReturn(true);
when(keycloakUserDataProvider.retrieveAuthenticatedUserData())
.thenReturn(new UserDataResponseDTO());
@@ -1246,7 +1226,7 @@ public void getUserData_ForTenantSuperAdmin_Should_ReturnUserDataFromKeycloak()
}
@Test
- public void getUserData_ForAgencySuperAdmin_Should_ReturnUserDataFromKeycloak() throws Exception {
+ void getUserData_ForAgencySuperAdmin_Should_ReturnUserDataFromKeycloak() throws Exception {
when(authenticatedUser.isAgencySuperAdmin()).thenReturn(true);
when(keycloakUserDataProvider.retrieveAuthenticatedUserData())
.thenReturn(new UserDataResponseDTO());
@@ -1260,8 +1240,7 @@ public void getUserData_ForAgencySuperAdmin_Should_ReturnUserDataFromKeycloak()
}
@Test
- public void getUserData_ForRestrictedAgencyAdmin_Should_ReturnUserDataFromKeycloak()
- throws Exception {
+ void getUserData_ForRestrictedAgencyAdmin_Should_ReturnUserDataFromKeycloak() throws Exception {
when(authenticatedUser.isRestrictedAgencyAdmin()).thenReturn(true);
when(keycloakUserDataProvider.retrieveAuthenticatedUserData())
.thenReturn(new UserDataResponseDTO());
@@ -1276,9 +1255,8 @@ public void getUserData_ForRestrictedAgencyAdmin_Should_ReturnUserDataFromKeyclo
/** Method: getTeamSessionsForAuthenticatedConsultant (role: consultant) */
@Test
- public void
- getTeamSessionsForAuthenticatedConsultant_Should_ReturnBadRequest_WhenHeaderParamIsMissing()
- throws Exception {
+ void getTeamSessionsForAuthenticatedConsultant_Should_ReturnBadRequest_WhenHeaderParamIsMissing()
+ throws Exception {
mvc.perform(
get(PATH_GET_TEAM_SESSIONS_FOR_AUTHENTICATED_CONSULTANT)
@@ -1288,7 +1266,7 @@ public void getUserData_ForRestrictedAgencyAdmin_Should_ReturnUserDataFromKeyclo
}
@Test
- public void
+ void
getTeamSessionsForAuthenticatedConsultant_Should_ReturnInternalServerError_WhenNoConsultantInDbFound()
throws Exception {
@@ -1305,7 +1283,7 @@ public void getUserData_ForRestrictedAgencyAdmin_Should_ReturnUserDataFromKeyclo
}
@Test
- public void
+ void
getTeamSessionsForAuthenticatedConsultant_Should_ReturnForbidden_WhenConsultantIsNoTeamConsultant()
throws Exception {
@@ -1323,7 +1301,7 @@ public void getUserData_ForRestrictedAgencyAdmin_Should_ReturnUserDataFromKeyclo
}
@Test
- public void
+ void
getTeamSessionsForAuthenticatedConsultant_Should_ReturnNoContent_WhenAuthorizedAndNoSessionsAvailable()
throws Exception {
@@ -1339,7 +1317,7 @@ public void getUserData_ForRestrictedAgencyAdmin_Should_ReturnUserDataFromKeyclo
}
@Test
- public void
+ void
getTeamSessionsForAuthenticatedConsultant_Should_ReturnSucess_WhenAuthorizedAndSessionsAvailable()
throws Exception {
@@ -1355,9 +1333,8 @@ public void getUserData_ForRestrictedAgencyAdmin_Should_ReturnUserDataFromKeyclo
}
@Test
- public void
- getTeamSessionsForAuthenticatedConsultant_Should_ReturnBadRequest_WhenParamOffestIsMissing()
- throws Exception {
+ void getTeamSessionsForAuthenticatedConsultant_Should_ReturnBadRequest_WhenParamOffestIsMissing()
+ throws Exception {
mvc.perform(
get(PATH_GET_TEAM_SESSIONS_FOR_AUTHENTICATED_CONSULTANT_WITHOUT_OFFSET)
.header(RC_TOKEN_HEADER_PARAMETER_NAME, RC_TOKEN)
@@ -1367,7 +1344,7 @@ public void getUserData_ForRestrictedAgencyAdmin_Should_ReturnUserDataFromKeyclo
}
@Test
- public void
+ void
getTeamSessionsForAuthenticatedConsultant_Should_ReturnBadRequest_WhenParamOffestHasANegativeValue()
throws Exception {
mvc.perform(
@@ -1379,9 +1356,8 @@ public void getUserData_ForRestrictedAgencyAdmin_Should_ReturnUserDataFromKeyclo
}
@Test
- public void
- getTeamSessionsForAuthenticatedConsultant_Should_ReturnBadRequest_WhenParamCountIsMissing()
- throws Exception {
+ void getTeamSessionsForAuthenticatedConsultant_Should_ReturnBadRequest_WhenParamCountIsMissing()
+ throws Exception {
mvc.perform(
get(PATH_GET_TEAM_SESSIONS_FOR_AUTHENTICATED_CONSULTANT_WITHOUT_COUNT)
.header(RC_TOKEN_HEADER_PARAMETER_NAME, RC_TOKEN)
@@ -1391,7 +1367,7 @@ public void getUserData_ForRestrictedAgencyAdmin_Should_ReturnUserDataFromKeyclo
}
@Test
- public void
+ void
getTeamSessionsForAuthenticatedConsultant_Should_ReturnBadRequest_WhenParamCountHasANegativeValue()
throws Exception {
mvc.perform(
@@ -1403,9 +1379,8 @@ public void getUserData_ForRestrictedAgencyAdmin_Should_ReturnUserDataFromKeyclo
}
@Test
- public void
- getTeamSessionsForAuthenticatedConsultant_Should_ReturnNotContent_WhenFilterParamIsInvalid()
- throws Exception {
+ void getTeamSessionsForAuthenticatedConsultant_Should_ReturnNotContent_WhenFilterParamIsInvalid()
+ throws Exception {
when(authenticatedUser.getUserId()).thenReturn(CONSULTANT_ID);
when(accountProvider.retrieveValidatedConsultant()).thenReturn(TEAM_CONSULTANT);
@@ -1420,7 +1395,7 @@ public void getUserData_ForRestrictedAgencyAdmin_Should_ReturnUserDataFromKeyclo
/** sendNewMessageNotification() */
@Test
- public void
+ void
sendNewMessageNotification_Should_CallEmailNotificationFacadeAndReturn2xxSuccessful_WhenCalled()
throws Exception {
var validNewMessageRequestBody = "{\"rcGroupId\": \"" + RC_GROUP_ID + "\"}";
@@ -1438,7 +1413,7 @@ public void getUserData_ForRestrictedAgencyAdmin_Should_ReturnUserDataFromKeyclo
/** Method: getConsultants (authority: VIEW_AGENCY_CONSULTANTS) */
@Test
- public void getConsultants_Should_ReturnBadRequest_WhenQueryParamIsMissing() throws Exception {
+ void getConsultants_Should_ReturnBadRequest_WhenQueryParamIsMissing() throws Exception {
mvc.perform(
get(PATH_GET_CONSULTANTS_FOR_AGENCY_WITHOUT_PARAM)
@@ -1448,7 +1423,7 @@ public void getConsultants_Should_ReturnBadRequest_WhenQueryParamIsMissing() thr
}
@Test
- public void getConsultants_Should_ReturnNoContent_WhenNoConsultantInDbFound() throws Exception {
+ void getConsultants_Should_ReturnNoContent_WhenNoConsultantInDbFound() throws Exception {
mvc.perform(
get(PATH_GET_CONSULTANTS_FOR_AGENCY)
@@ -1458,9 +1433,8 @@ public void getConsultants_Should_ReturnNoContent_WhenNoConsultantInDbFound() th
}
@Test
- public void
- getConsultants_Should_ReturnInternalServerError_WhenConsultantAgencyServiceThrowsException()
- throws Exception {
+ void getConsultants_Should_ReturnInternalServerError_WhenConsultantAgencyServiceThrowsException()
+ throws Exception {
when(consultantAgencyService.getConsultantsOfAgency(Mockito.anyLong()))
.thenThrow(new ServiceException(ERROR));
@@ -1473,7 +1447,7 @@ public void getConsultants_Should_ReturnNoContent_WhenNoConsultantInDbFound() th
}
@Test
- public void
+ void
getConsultants_Should_ReturnOkAndValidContent_WhenConsultantAgencyServiceReturnsListWithEntries()
throws Exception {
@@ -1498,7 +1472,7 @@ public void getConsultants_Should_ReturnNoContent_WhenNoConsultantInDbFound() th
/** Method: assignSession (role: consultant) */
@Test
- public void assignSession_Should_ReturnBadRequest_WhenQueryParamsAreInvalid() throws Exception {
+ void assignSession_Should_ReturnBadRequest_WhenQueryParamsAreInvalid() throws Exception {
mvc.perform(
put(PATH_PUT_ASSIGN_SESSION_INVALID_PARAMS)
@@ -1508,9 +1482,8 @@ public void assignSession_Should_ReturnBadRequest_WhenQueryParamsAreInvalid() th
}
@Test
- public void
- assignSession_Should_ReturnInternalServerErrorAndLogError_WhenSessionServiceThrowsException()
- throws Exception {
+ void assignSession_Should_ReturnInternalServerErrorAndLogError_WhenSessionServiceThrowsException()
+ throws Exception {
when(sessionService.getSession(Mockito.anyLong())).thenThrow(new ServiceException(ERROR));
@@ -1524,7 +1497,7 @@ public void assignSession_Should_ReturnBadRequest_WhenQueryParamsAreInvalid() th
}
@Test
- public void assignSession_Should_ReturnHttpStatusOfAssignSessionFacade() throws Exception {
+ void assignSession_Should_ReturnHttpStatusOfAssignSessionFacade() throws Exception {
when(accountProvider.retrieveValidatedConsultantById(any())).thenReturn(TEAM_CONSULTANT);
when(sessionService.getSession(Mockito.anyLong())).thenReturn(Optional.of(SESSION));
@@ -1544,9 +1517,8 @@ public void assignSession_Should_ReturnHttpStatusOfAssignSessionFacade() throws
}
@Test
- public void
- assignSession_Should_ReturnInternalServerErrorAndLogError_WhenConsultantIsNotFoundInDb()
- throws Exception {
+ void assignSession_Should_ReturnInternalServerErrorAndLogError_WhenConsultantIsNotFoundInDb()
+ throws Exception {
when(accountProvider.retrieveValidatedConsultantById(anyString()))
.thenThrow(new InternalServerErrorException(""));
@@ -1561,7 +1533,7 @@ public void assignSession_Should_ReturnHttpStatusOfAssignSessionFacade() throws
}
@Test
- public void assignSession_Should_ReturnInternalServerErrorAndLogError_WhenSessionIsNotFoundInDb()
+ void assignSession_Should_ReturnInternalServerErrorAndLogError_WhenSessionIsNotFoundInDb()
throws Exception {
when(accountProvider.retrieveValidatedConsultant()).thenReturn(TEAM_CONSULTANT);
@@ -1577,7 +1549,7 @@ public void assignSession_Should_ReturnInternalServerErrorAndLogError_WhenSessio
}
@Test
- public void
+ void
assignSession_Should_ReturnForbiddenAndLogError_WhenCallerDoesNotHaveTheRightToAssignEnquiries()
throws Exception {
@@ -1596,7 +1568,7 @@ public void assignSession_Should_ReturnInternalServerErrorAndLogError_WhenSessio
}
@Test
- public void registerUser_Should_DecodePassword() throws Exception {
+ void registerUser_Should_DecodePassword() throws Exception {
when(userHelper.isUsernameValid(anyString())).thenReturn(true);
when(mandatoryFieldsProvider.fetchMandatoryFieldsForConsultingType(anyString()))
.thenReturn(
@@ -1620,7 +1592,7 @@ public void registerUser_Should_DecodePassword() throws Exception {
/** updatePassword() */
@Test
- public void updatePassword_Should_ReturnBadRequest_When_PasswordsAreMissing() throws Exception {
+ void updatePassword_Should_ReturnBadRequest_When_PasswordsAreMissing() throws Exception {
mvc.perform(
put(PATH_PUT_UPDATE_PASSWORD)
@@ -1632,7 +1604,7 @@ public void updatePassword_Should_ReturnBadRequest_When_PasswordsAreMissing() th
}
@Test
- public void updateKey_Should_ReturnConflict_WhenProvidedWithSameKey() throws Exception {
+ void updateKey_Should_ReturnConflict_WhenProvidedWithSameKey() throws Exception {
when(encryptionService.getMasterKey()).thenReturn(MASTER_KEY_1);
@@ -1645,7 +1617,7 @@ public void updateKey_Should_ReturnConflict_WhenProvidedWithSameKey() throws Exc
}
@Test
- public void updateKey_Should_ReturnAccepted_WhenProvidedWithNewKey() throws Exception {
+ void updateKey_Should_ReturnAccepted_WhenProvidedWithNewKey() throws Exception {
when(encryptionService.getMasterKey()).thenReturn(MASTER_KEY_1);
@@ -1658,7 +1630,7 @@ public void updateKey_Should_ReturnAccepted_WhenProvidedWithNewKey() throws Exce
}
@Test
- public void createChat_Should_ReturnBadRequest_WhenQueryParamsAreInvalid() throws Exception {
+ void createChat_Should_ReturnBadRequest_WhenQueryParamsAreInvalid() throws Exception {
mvc.perform(
post(PATH_POST_CHAT_NEW)
@@ -1671,7 +1643,7 @@ public void createChat_Should_ReturnBadRequest_WhenQueryParamsAreInvalid() throw
}
@Test
- public void createChat_Should_ReturnInternalServerErrorAndLogError_When_ChatCouldNotBeCreated()
+ void createChat_Should_ReturnInternalServerErrorAndLogError_When_ChatCouldNotBeCreated()
throws Exception {
when(authenticatedUser.getUserId()).thenReturn(CONSULTANT_ID);
@@ -1698,7 +1670,7 @@ private String giveValidCreateChatBodyWithAgencyId(Long agencyId) {
}
@Test
- public void createChat_Should_ReturnCreated_When_ChatWasCreated() throws Exception {
+ void createChat_Should_ReturnCreated_When_ChatWasCreated() throws Exception {
when(authenticatedUser.getUserId()).thenReturn(CONSULTANT_ID);
when(accountProvider.retrieveValidatedConsultant()).thenReturn(TEAM_CONSULTANT);
@@ -1714,7 +1686,7 @@ public void createChat_Should_ReturnCreated_When_ChatWasCreated() throws Excepti
}
@Test
- public void createChatV2_Should_ReturnBadRequest_WhenQueryParamsAreInvalid() throws Exception {
+ void createChatV2_Should_ReturnBadRequest_WhenQueryParamsAreInvalid() throws Exception {
mvc.perform(
post(PATH_POST_CHAT_NEW_V2)
@@ -1727,7 +1699,7 @@ public void createChatV2_Should_ReturnBadRequest_WhenQueryParamsAreInvalid() thr
}
@Test
- public void createChatV2_Should_ReturnInternalServerErrorAndLogError_When_ChatCouldNotBeCreated()
+ void createChatV2_Should_ReturnInternalServerErrorAndLogError_When_ChatCouldNotBeCreated()
throws Exception {
when(authenticatedUser.getUserId()).thenReturn(CONSULTANT_ID);
@@ -1744,7 +1716,7 @@ public void createChatV2_Should_ReturnInternalServerErrorAndLogError_When_ChatCo
}
@Test
- public void createChatV2_Should_ReturnCreated_When_ChatWasCreated() throws Exception {
+ void createChatV2_Should_ReturnCreated_When_ChatWasCreated() throws Exception {
when(authenticatedUser.getUserId()).thenReturn(CONSULTANT_ID);
when(accountProvider.retrieveValidatedConsultant()).thenReturn(TEAM_CONSULTANT);
@@ -1761,7 +1733,7 @@ public void createChatV2_Should_ReturnCreated_When_ChatWasCreated() throws Excep
/** Method: startChat */
@Test
- public void startChat_Should_ReturnBadRequest_WhenPathParamsAreInvalid() throws Exception {
+ void startChat_Should_ReturnBadRequest_WhenPathParamsAreInvalid() throws Exception {
mvc.perform(
put(PATH_PUT_CHAT_START_WITH_INVALID_PATH_PARAMS)
@@ -1776,7 +1748,7 @@ public void startChat_Should_ReturnBadRequest_WhenPathParamsAreInvalid() throws
}
@Test
- public void startChat_Should_ReturnOK_When_ChatWasStarted() throws Exception {
+ void startChat_Should_ReturnOK_When_ChatWasStarted() throws Exception {
when(authenticatedUser.getUserId()).thenReturn(CONSULTANT_ID);
when(accountProvider.retrieveValidatedConsultant()).thenReturn(TEAM_CONSULTANT);
@@ -1790,7 +1762,7 @@ public void startChat_Should_ReturnOK_When_ChatWasStarted() throws Exception {
}
@Test
- public void startChat_Should_ReturnBadRequest_When_StartChatThrowsBadRequest() throws Exception {
+ void startChat_Should_ReturnBadRequest_When_StartChatThrowsBadRequest() throws Exception {
when(authenticatedUser.getUserId()).thenReturn(CONSULTANT_ID);
when(chatService.getChat(Mockito.any())).thenReturn(Optional.empty());
@@ -1805,7 +1777,7 @@ public void startChat_Should_ReturnBadRequest_When_StartChatThrowsBadRequest() t
}
@Test
- public void startChat_Should_ReturnBadRequest_When_ChatWasNotFound() throws Exception {
+ void startChat_Should_ReturnBadRequest_When_ChatWasNotFound() throws Exception {
when(authenticatedUser.getUserId()).thenReturn(CONSULTANT_ID);
when(accountProvider.retrieveValidatedConsultant())
@@ -1821,7 +1793,7 @@ public void startChat_Should_ReturnBadRequest_When_ChatWasNotFound() throws Exce
/** Method: getChat */
@Test
- public void getChat_Should_ReturnBadRequest_WhenPathParamsAreInvalid() throws Exception {
+ void getChat_Should_ReturnBadRequest_WhenPathParamsAreInvalid() throws Exception {
mvc.perform(
get(PATH_GET_CHAT_WITH_INVALID_PATH_PARAMS)
@@ -1836,7 +1808,7 @@ public void getChat_Should_ReturnBadRequest_WhenPathParamsAreInvalid() throws Ex
}
@Test
- public void getChat_Should_ReturnOk_When_RequestOk() throws Exception {
+ void getChat_Should_ReturnOk_When_RequestOk() throws Exception {
mvc.perform(
get(PATH_GET_CHAT)
@@ -1848,7 +1820,7 @@ public void getChat_Should_ReturnOk_When_RequestOk() throws Exception {
}
@Test
- public void assignChat_Should_ReturnOk_When_ChatWasAssigned() throws Exception {
+ void assignChat_Should_ReturnOk_When_ChatWasAssigned() throws Exception {
mvc.perform(
put(PATH_PUT_ASSIGN_CHAT)
.contentType(MediaType.APPLICATION_JSON)
@@ -1860,7 +1832,7 @@ public void assignChat_Should_ReturnOk_When_ChatWasAssigned() throws Exception {
/** Method: joinChat */
@Test
- public void joinChat_Should_ReturnBadRequest_WhenPathParamsAreInvalid() throws Exception {
+ void joinChat_Should_ReturnBadRequest_WhenPathParamsAreInvalid() throws Exception {
mvc.perform(
put(PATH_PUT_JOIN_CHAT_WITH_INVALID_PATH_PARAMS)
@@ -1875,7 +1847,7 @@ public void joinChat_Should_ReturnBadRequest_WhenPathParamsAreInvalid() throws E
}
@Test
- public void joinChat_Should_ReturnOk_When_ChatWasJoined() throws Exception {
+ void joinChat_Should_ReturnOk_When_ChatWasJoined() throws Exception {
mvc.perform(
put(PATH_PUT_JOIN_CHAT)
@@ -1887,7 +1859,7 @@ public void joinChat_Should_ReturnOk_When_ChatWasJoined() throws Exception {
}
@Test
- public void stopChat_Should_ReturnBadRequest_WhenQueryParamsAreInvalid() throws Exception {
+ void stopChat_Should_ReturnBadRequest_WhenQueryParamsAreInvalid() throws Exception {
mvc.perform(
put(PATH_PUT_CHAT_STOP_INVALID)
@@ -1901,7 +1873,7 @@ public void stopChat_Should_ReturnBadRequest_WhenQueryParamsAreInvalid() throws
}
@Test
- public void stopChat_Should_ReturnInternalServerError_When_CallingConsultantDoesNotExist()
+ void stopChat_Should_ReturnInternalServerError_When_CallingConsultantDoesNotExist()
throws Exception {
when(chatService.getChat(any())).thenReturn(Optional.of(mock(Chat.class)));
@@ -1915,7 +1887,7 @@ public void stopChat_Should_ReturnInternalServerError_When_CallingConsultantDoes
}
@Test
- public void stopChat_Should_ReturnBadRequest_When_ChatNotFound() throws Exception {
+ void stopChat_Should_ReturnBadRequest_When_ChatNotFound() throws Exception {
when(accountProvider.retrieveValidatedConsultant()).thenReturn(TEAM_CONSULTANT);
when(chatService.getChat(Mockito.anyLong())).thenReturn(Optional.empty());
@@ -1925,7 +1897,7 @@ public void stopChat_Should_ReturnBadRequest_When_ChatNotFound() throws Exceptio
}
@Test
- public void stopChat_Should_ReturnOk_When_ChatWasStopped() throws Exception {
+ void stopChat_Should_ReturnOk_When_ChatWasStopped() throws Exception {
when(accountProvider.retrieveValidatedConsultant()).thenReturn(TEAM_CONSULTANT);
when(chatService.getChat(Mockito.anyLong())).thenReturn(Optional.of(chat));
@@ -1936,7 +1908,7 @@ public void stopChat_Should_ReturnOk_When_ChatWasStopped() throws Exception {
/** Method: getChat */
@Test
- public void getChatMembers_Should_ReturnBadRequest_WhenPathParamsAreInvalid() throws Exception {
+ void getChatMembers_Should_ReturnBadRequest_WhenPathParamsAreInvalid() throws Exception {
mvc.perform(
get(PATH_GET_CHAT_MEMBERS_WITH_INVALID_PATH_PARAMS)
@@ -1953,7 +1925,7 @@ public void getChatMembers_Should_ReturnBadRequest_WhenPathParamsAreInvalid() th
}
@Test
- public void getChatMembers_Should_ReturnOk_When_RequestOk() throws Exception {
+ void getChatMembers_Should_ReturnOk_When_RequestOk() throws Exception {
mvc.perform(
get(PATH_GET_CHAT_MEMBERS)
@@ -1966,7 +1938,7 @@ public void getChatMembers_Should_ReturnOk_When_RequestOk() throws Exception {
/** Method: updateChat */
@Test
- public void updateChat_Should_ReturnBadRequest_WhenPathParamsAreInvalid() throws Exception {
+ void updateChat_Should_ReturnBadRequest_WhenPathParamsAreInvalid() throws Exception {
mvc.perform(
put(PATH_PUT_UPDATE_CHAT_INVALID_PATH_PARAMS)
@@ -1978,7 +1950,7 @@ public void updateChat_Should_ReturnBadRequest_WhenPathParamsAreInvalid() throws
}
@Test
- public void updateChat_Should_ReturnOk_When_RequestOk() throws Exception {
+ void updateChat_Should_ReturnOk_When_RequestOk() throws Exception {
mvc.perform(
put(PATH_PUT_UPDATE_CHAT)
@@ -1992,7 +1964,7 @@ public void updateChat_Should_ReturnOk_When_RequestOk() throws Exception {
/** Method: fetchSessionForConsultant */
@Test
- public void fetchSessionForConsultant_Should_ReturnOk_WhenRequestOk() throws Exception {
+ void fetchSessionForConsultant_Should_ReturnOk_WhenRequestOk() throws Exception {
mvc.perform(
get(PATH_GET_SESSION_FOR_CONSULTANT)
@@ -2005,9 +1977,8 @@ public void fetchSessionForConsultant_Should_ReturnOk_WhenRequestOk() throws Exc
}
@Test
- public void
- fetchSessionForConsultant_Should_ReturnInternalServerError_WhenAuthorizedButUserNotFound()
- throws Exception {
+ void fetchSessionForConsultant_Should_ReturnInternalServerError_WhenAuthorizedButUserNotFound()
+ throws Exception {
when(authenticatedUser.getUserId()).thenReturn(CONSULTANT_ID);
when(accountProvider.retrieveValidatedConsultant())
@@ -2024,7 +1995,7 @@ public void fetchSessionForConsultant_Should_ReturnOk_WhenRequestOk() throws Exc
}
@Test
- public void updateEmailAddress_Should_ReturnOk_When_RequestOk() throws Exception {
+ void updateEmailAddress_Should_ReturnOk_When_RequestOk() throws Exception {
mvc.perform(
put(PATH_PUT_UPDATE_EMAIL)
.contentType(MediaType.APPLICATION_JSON)
@@ -2036,7 +2007,7 @@ public void updateEmailAddress_Should_ReturnOk_When_RequestOk() throws Exception
}
@Test
- public void deleteEmailAddress_Should_ReturnOk_When_RequestOk() throws Exception {
+ void deleteEmailAddress_Should_ReturnOk_When_RequestOk() throws Exception {
mvc.perform(delete("/users/email").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
@@ -2044,7 +2015,7 @@ public void deleteEmailAddress_Should_ReturnOk_When_RequestOk() throws Exception
}
@Test
- public void updateEmailAddress_Should_ReturnBadRequest_When_bodyIsEmpty() throws Exception {
+ void updateEmailAddress_Should_ReturnBadRequest_When_bodyIsEmpty() throws Exception {
mvc.perform(
put(PATH_PUT_UPDATE_EMAIL)
.contentType(MediaType.APPLICATION_JSON)
@@ -2055,9 +2026,8 @@ public void updateEmailAddress_Should_ReturnBadRequest_When_bodyIsEmpty() throws
}
@Test
- public void
- deactivateAndFlagUserAccountForDeletion_Should_ReturnBadRequest_When_BodyValuesAreMissing()
- throws Exception {
+ void deactivateAndFlagUserAccountForDeletion_Should_ReturnBadRequest_When_BodyValuesAreMissing()
+ throws Exception {
mvc.perform(
delete(PATH_DELETE_FLAG_USER_DELETED)
@@ -2069,7 +2039,7 @@ public void updateEmailAddress_Should_ReturnBadRequest_When_bodyIsEmpty() throws
}
@Test
- public void deleteSessionAndInactiveUser_Should_ReturnNotFound_When_SessionIdIsUnknown()
+ void deleteSessionAndInactiveUser_Should_ReturnNotFound_When_SessionIdIsUnknown()
throws Exception {
var sessionId = easyRandom.nextLong();
@@ -2081,8 +2051,7 @@ public void deleteSessionAndInactiveUser_Should_ReturnNotFound_When_SessionIdIsU
}
@Test
- public void deleteSessionAndInactiveUser_Should_ReturnOK_When_SessionIdIsKnown()
- throws Exception {
+ void deleteSessionAndInactiveUser_Should_ReturnOK_When_SessionIdIsKnown() throws Exception {
var sessionId = givenAPresentSession(false);
mvc.perform(delete("/users/sessions/{sessionId}", sessionId).accept(MediaType.APPLICATION_JSON))
@@ -2092,7 +2061,7 @@ public void deleteSessionAndInactiveUser_Should_ReturnOK_When_SessionIdIsKnown()
}
@Test
- public void updateMobileToken_Should_ReturnOk_When_RequestOk() throws Exception {
+ void updateMobileToken_Should_ReturnOk_When_RequestOk() throws Exception {
mvc.perform(
put(PATH_PUT_UPDATE_MOBILE_TOKEN)
.contentType(MediaType.APPLICATION_JSON)
@@ -2104,7 +2073,7 @@ public void updateMobileToken_Should_ReturnOk_When_RequestOk() throws Exception
}
@Test
- public void updateMobileToken_Should_ReturnBadRequest_When_bodyIsEmpty() throws Exception {
+ void updateMobileToken_Should_ReturnBadRequest_When_bodyIsEmpty() throws Exception {
mvc.perform(
put(PATH_PUT_UPDATE_MOBILE_TOKEN)
.contentType(MediaType.APPLICATION_JSON)
@@ -2115,7 +2084,7 @@ public void updateMobileToken_Should_ReturnBadRequest_When_bodyIsEmpty() throws
}
@Test
- public void updateSessionData_Should_ReturnBadRequest_When_BodyIsEmpty() throws Exception {
+ void updateSessionData_Should_ReturnBadRequest_When_BodyIsEmpty() throws Exception {
mvc.perform(
put(PATH_PUT_UPDATE_SESSION_DATA)
.contentType(MediaType.APPLICATION_JSON)
@@ -2126,8 +2095,7 @@ public void updateSessionData_Should_ReturnBadRequest_When_BodyIsEmpty() throws
}
@Test
- public void updateSessionData_Should_ReturnBadRequest_When_PathVariableIsInvalid()
- throws Exception {
+ void updateSessionData_Should_ReturnBadRequest_When_PathVariableIsInvalid() throws Exception {
mvc.perform(
put(PATH_PUT_UPDATE_SESSION_DATA_INVALID_PATH_VAR)
.contentType(MediaType.APPLICATION_JSON)
@@ -2138,7 +2106,7 @@ public void updateSessionData_Should_ReturnBadRequest_When_PathVariableIsInvalid
}
@Test
- public void updateSessionData_Should_ReturnOk_When_RequestIsOk() throws Exception {
+ void updateSessionData_Should_ReturnOk_When_RequestIsOk() throws Exception {
mvc.perform(
put(PATH_PUT_UPDATE_SESSION_DATA)
.content(objectMapper.writeValueAsString(new SessionDTO()))
@@ -2148,7 +2116,7 @@ public void updateSessionData_Should_ReturnOk_When_RequestIsOk() throws Exceptio
}
@Test
- public void updateUserData_Should_ReturnNotFound_When_ConsultantDoesNotExist() throws Exception {
+ void updateUserData_Should_ReturnNotFound_When_ConsultantDoesNotExist() throws Exception {
when(consultantService.getConsultant(anyString())).thenReturn(Optional.empty());
var updateConsultant =
objectMapper.writeValueAsString(givenAMinimalUpdateConsultantDto(givenAValidEmail()));
@@ -2164,7 +2132,7 @@ public void updateUserData_Should_ReturnNotFound_When_ConsultantDoesNotExist() t
}
@Test
- public void updateUserData_Should_ReturnBadRequest_When_PathVariableIsInvalid() throws Exception {
+ void updateUserData_Should_ReturnBadRequest_When_PathVariableIsInvalid() throws Exception {
mvc.perform(
put(PATH_GET_USER_DATA)
.contentType(MediaType.APPLICATION_JSON)
@@ -2175,7 +2143,7 @@ public void updateUserData_Should_ReturnBadRequest_When_PathVariableIsInvalid()
}
@Test
- public void updateUserData_Should_ReturnBadRequest_When_LanguageIsInvalid() throws Exception {
+ void updateUserData_Should_ReturnBadRequest_When_LanguageIsInvalid() throws Exception {
var updateConsultantDTO = givenAnUpdateConsultantDtoWithInvalidLanguage();
mvc.perform(
@@ -2189,7 +2157,7 @@ public void updateUserData_Should_ReturnBadRequest_When_LanguageIsInvalid() thro
}
@Test
- public void updateUserData_Should_ReturnOk_When_RequestIsOk() throws Exception {
+ void updateUserData_Should_ReturnOk_When_RequestIsOk() throws Exception {
var consultant = givenAValidConsultant();
var updateConsultantDTO = givenAMinimalUpdateConsultantDto(consultant.getEmail());
@@ -2213,8 +2181,7 @@ public void updateUserData_Should_ReturnOk_When_RequestIsOk() throws Exception {
}
@Test
- public void updateUserData_Should_ReturnBadRequest_When_emailAddressIsNotValid()
- throws Exception {
+ void updateUserData_Should_ReturnBadRequest_When_emailAddressIsNotValid() throws Exception {
var updateConsultantDto = givenAMinimalUpdateConsultantDto("invalid");
mvc.perform(
@@ -2226,7 +2193,7 @@ public void updateUserData_Should_ReturnBadRequest_When_emailAddressIsNotValid()
}
@Test
- public void archiveSession_Should_ReturnBadRequest_When_PathVariableIsInvalid() throws Exception {
+ void archiveSession_Should_ReturnBadRequest_When_PathVariableIsInvalid() throws Exception {
mvc.perform(
put(PATH_ARCHIVE_SESSION_INVALID_PATH_VAR)
.contentType(MediaType.APPLICATION_JSON)
@@ -2237,13 +2204,12 @@ public void archiveSession_Should_ReturnBadRequest_When_PathVariableIsInvalid()
}
@Test
- public void archiveSession_Should_ReturnOk_When_RequestIsOk() throws Exception {
+ void archiveSession_Should_ReturnOk_When_RequestIsOk() throws Exception {
mvc.perform(put(PATH_ARCHIVE_SESSION)).andExpect(status().isOk());
}
@Test
- public void dearchiveSession_Should_ReturnBadRequest_When_PathVariableIsInvalid()
- throws Exception {
+ void dearchiveSession_Should_ReturnBadRequest_When_PathVariableIsInvalid() throws Exception {
mvc.perform(
put(PATH_DEARCHIVE_SESSION_INVALID_PATH_VAR)
.contentType(MediaType.APPLICATION_JSON)
@@ -2254,12 +2220,12 @@ public void dearchiveSession_Should_ReturnBadRequest_When_PathVariableIsInvalid(
}
@Test
- public void dearchiveSession_Should_ReturnOk_When_RequestIsOk() throws Exception {
+ void dearchiveSession_Should_ReturnOk_When_RequestIsOk() throws Exception {
mvc.perform(put(PATH_DEARCHIVE_SESSION)).andExpect(status().isOk());
}
@Test
- public void addMobileAppToken_Should_returnOk_When_RequestIsOk() throws Exception {
+ void addMobileAppToken_Should_returnOk_When_RequestIsOk() throws Exception {
mvc.perform(
put(PATH_PUT_ADD_MOBILE_TOKEN)
.content(objectMapper.writeValueAsString(new MobileTokenDTO()))
@@ -2268,13 +2234,13 @@ public void addMobileAppToken_Should_returnOk_When_RequestIsOk() throws Exceptio
}
@Test
- public void addMobileAppToken_Should_returnBadRequest_When_RequestIsEmpty() throws Exception {
+ void addMobileAppToken_Should_returnBadRequest_When_RequestIsEmpty() throws Exception {
mvc.perform(put(PATH_PUT_ADD_MOBILE_TOKEN).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest());
}
@Test
- public void getConsultantPublicData_Should_returnOk_When_consultantIdIsGiven() throws Exception {
+ void getConsultantPublicData_Should_returnOk_When_consultantIdIsGiven() throws Exception {
givenAValidConsultant();
mvc.perform(get(PATH_GET_PUBLIC_CONSULTANT_DATA).contentType(MediaType.APPLICATION_JSON))
@@ -2285,9 +2251,8 @@ public void getConsultantPublicData_Should_returnOk_When_consultantIdIsGiven() t
}
@Test
- public void
- updateE2eInChats_Should_returnAccepted_When_adviceSeekerWithoutInitializedSessionIsGiven()
- throws Exception {
+ void updateE2eInChats_Should_returnAccepted_When_adviceSeekerWithoutInitializedSessionIsGiven()
+ throws Exception {
givenAdviceSeekerWithoutInitializedSession(false);
mvc.perform(
@@ -2303,7 +2268,7 @@ public void getConsultantPublicData_Should_returnOk_When_consultantIdIsGiven() t
}
@Test
- public void
+ void
updateE2eInChats_Should_returnServerError_When_adviceSeekerWithoutInitializedSessionShouldHaveBeenInitialized()
throws Exception {
givenAdviceSeekerWithoutInitializedSession(true);
diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerSessionE2EIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerSessionE2EIT.java
index 16272c7ac..2260e8003 100644
--- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerSessionE2EIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerSessionE2EIT.java
@@ -48,6 +48,7 @@
import de.caritas.cob.userservice.api.adapters.rocketchat.dto.subscriptions.SubscriptionsUpdateDTO;
import de.caritas.cob.userservice.api.adapters.rocketchat.dto.user.RocketChatUserDTO;
import de.caritas.cob.userservice.api.adapters.rocketchat.dto.user.UserInfoResponseDTO;
+import de.caritas.cob.userservice.api.adapters.web.controller.interceptor.ApiResponseEntityExceptionHandler;
import de.caritas.cob.userservice.api.adapters.web.dto.AliasMessageDTO;
import de.caritas.cob.userservice.api.adapters.web.dto.EnquiryMessageDTO;
import de.caritas.cob.userservice.api.adapters.web.dto.MessageType;
@@ -78,6 +79,7 @@
import de.caritas.cob.userservice.api.port.out.UserAgencyRepository;
import de.caritas.cob.userservice.api.port.out.UserRepository;
import de.caritas.cob.userservice.api.testConfig.TestAgencyControllerApi;
+import java.lang.reflect.Method;
import java.net.URI;
import java.time.LocalDateTime;
import java.util.ArrayList;
@@ -101,6 +103,7 @@
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
+import org.keycloak.adapters.KeycloakConfigResolver;
import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.admin.client.resource.RoleMappingResource;
@@ -111,10 +114,10 @@
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
-import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.mock.mockito.MockBean;
@@ -130,13 +133,18 @@
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
+import org.springframework.web.method.HandlerMethod;
+import org.springframework.web.method.annotation.ExceptionHandlerMethodResolver;
+import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;
+import org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod;
import org.springframework.web.util.UriTemplateHandler;
@SpringBootTest
@ExtendWith(OutputCaptureExtension.class)
-@AutoConfigureMockMvc
+// @AutoConfigureMockMvc
@ActiveProfiles("testing")
@AutoConfigureTestDatabase
class UserControllerSessionE2EIT {
@@ -146,7 +154,8 @@ class UserControllerSessionE2EIT {
private static final String CSRF_VALUE = "test";
private static final Cookie CSRF_COOKIE = new Cookie("csrfCookie", CSRF_VALUE);
- @Autowired private MockMvc mockMvc;
+ @Autowired private UserController userController;
+ private MockMvc mockMvc;
@Autowired private ObjectMapper objectMapper;
@@ -174,6 +183,8 @@ class UserControllerSessionE2EIT {
@MockBean private RocketChatCredentialsProvider rocketChatCredentialsProvider;
+ @MockBean private KeycloakConfigResolver keycloakConfigResolver;
+
@TestConfiguration
static class TestConfig {
@Bean(name = "initializeFeedbackChat")
@@ -264,12 +275,38 @@ void reset() {
@BeforeEach
public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ this.mockMvc =
+ MockMvcBuilders.standaloneSetup(userController)
+ .setHandlerExceptionResolvers(withExceptionControllerAdvice())
+ .build();
+ objectMapper.registerModule(new com.fasterxml.jackson.datatype.jsr310.JavaTimeModule());
when(agencyServiceApiControllerFactory.createControllerApi())
.thenReturn(
new TestAgencyControllerApi(
new de.caritas.cob.userservice.agencyserivce.generated.ApiClient()));
}
+ private ExceptionHandlerExceptionResolver withExceptionControllerAdvice() {
+ final ExceptionHandlerExceptionResolver exceptionResolver =
+ new ExceptionHandlerExceptionResolver() {
+ @Override
+ protected ServletInvocableHandlerMethod getExceptionHandlerMethod(
+ final HandlerMethod handlerMethod, final Exception exception) {
+ Method method =
+ new ExceptionHandlerMethodResolver(ApiResponseEntityExceptionHandler.class)
+ .resolveMethod(exception);
+ if (method != null) {
+ return new ServletInvocableHandlerMethod(
+ new ApiResponseEntityExceptionHandler(), method);
+ }
+ return super.getExceptionHandlerMethod(handlerMethod, exception);
+ }
+ };
+ exceptionResolver.afterPropertiesSet();
+ return exceptionResolver;
+ }
+
@Test
@WithMockUser(authorities = {AuthorityValue.USER_DEFAULT})
void createEnquiryMessageWithLanguageShouldSaveLanguageAndRespondWithCreated() throws Exception {
@@ -806,7 +843,7 @@ void getSessionForIdShouldFindSessionsBySessionIdForConsultant() throws Exceptio
@Test
@WithMockUser(authorities = AuthorityValue.ASSIGN_CONSULTANT_TO_SESSION)
- void removeFromSessionShouldReturnForbiddenIfSessionIdFormatIsInvalid() throws Exception {
+ void removeFromSessionShouldReturnBadRequestIfSessionIdFormatIsInvalid() throws Exception {
givenAValidConsultant(true);
var sessionId = RandomStringUtils.randomAlphabetic(8);
@@ -820,7 +857,7 @@ void removeFromSessionShouldReturnForbiddenIfSessionIdFormatIsInvalid() throws E
.header(CSRF_HEADER, CSRF_VALUE)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
- .andExpect(status().isForbidden());
+ .andExpect(status().isBadRequest());
}
@Test
diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/StatelessCsrfFilterTest.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/StatelessCsrfFilterTest.java
index 6f4eeb245..f6a4cb782 100644
--- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/StatelessCsrfFilterTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/StatelessCsrfFilterTest.java
@@ -16,14 +16,16 @@
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
import org.springframework.security.web.access.AccessDeniedHandler;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = org.mockito.quality.Strictness.LENIENT)
public class StatelessCsrfFilterTest {
private static final String CSRF_HEADER = "csrfHeader";
@@ -43,7 +45,7 @@ public class StatelessCsrfFilterTest {
@Mock private AccessDeniedHandler accessDeniedHandler;
- @Before
+ @BeforeEach
public void setup() {
ConfigProperty cookieProperty = new ConfigProperty();
cookieProperty.setProperty(CSRF_COOKIE);
diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/dto/serialization/DecodeUsernameJsonSerializerTest.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/dto/serialization/DecodeUsernameJsonSerializerTest.java
index 48a84bc80..baf96ad0f 100644
--- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/dto/serialization/DecodeUsernameJsonSerializerTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/dto/serialization/DecodeUsernameJsonSerializerTest.java
@@ -8,13 +8,13 @@
import com.fasterxml.jackson.core.JsonGenerator;
import de.caritas.cob.userservice.api.helper.UserHelper;
import java.io.IOException;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class DecodeUsernameJsonSerializerTest {
@InjectMocks private DecodeUsernameJsonSerializer serializer;
diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/dto/serialization/EncodeUsernameJsonSerializationUtilsTest.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/dto/serialization/EncodeUsernameJsonSerializationUtilsTest.java
index 7ad61f61d..5da19e54a 100644
--- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/dto/serialization/EncodeUsernameJsonSerializationUtilsTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/dto/serialization/EncodeUsernameJsonSerializationUtilsTest.java
@@ -4,9 +4,7 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USERNAME_ENCODED;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USERNAME_TOO_LONG;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USERNAME_TOO_SHORT;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
@@ -19,14 +17,14 @@
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class EncodeUsernameJsonSerializationUtilsTest {
private ObjectMapper objectMapper;
@@ -35,7 +33,7 @@ public class EncodeUsernameJsonSerializationUtilsTest {
@Mock private UserHelper userHelper;
- @Before
+ @BeforeEach
public void setup() {
objectMapper = new ObjectMapper();
}
@@ -68,7 +66,7 @@ public void deserialize_Should_ThrowBadRequestException_WhenUsernameIsTooShort()
fail("Expected exception: BadRequestException");
} catch (BadRequestException badRequestException) {
- assertTrue("Excepted BadRequestException thrown", true);
+ assertTrue(true, "Excepted BadRequestException thrown");
}
}
@@ -82,7 +80,7 @@ public void deserialize_Should_ThrowBadRequestException_WhenUsernameIsTooLong()
fail("Expected exception: BadRequestException");
} catch (BadRequestException badRequestException) {
- assertTrue("Excepted BadRequestException thrown", true);
+ assertTrue(true, "Excepted BadRequestException thrown");
}
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/dto/serialization/UrlDecodePasswordJsonSerializationUtilsTest.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/dto/serialization/UrlDecodePasswordJsonSerializationUtilsTest.java
index d058abf09..4b55c1230 100644
--- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/dto/serialization/UrlDecodePasswordJsonSerializationUtilsTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/dto/serialization/UrlDecodePasswordJsonSerializationUtilsTest.java
@@ -2,7 +2,7 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.PASSWORD;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.PASSWORD_URL_ENCODED;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
@@ -12,18 +12,18 @@
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class UrlDecodePasswordJsonSerializationUtilsTest {
private ObjectMapper objectMapper;
private UrlDecodePasswordJsonDeserializer urlDecodePasswordJsonDeserializer;
- @Before
+ @BeforeEach
public void setup() {
objectMapper = new ObjectMapper();
urlDecodePasswordJsonDeserializer = new UrlDecodePasswordJsonDeserializer();
diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/MandatoryFieldsProviderTest.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/MandatoryFieldsProviderTest.java
index 1a72a471c..624a38824 100644
--- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/MandatoryFieldsProviderTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/MandatoryFieldsProviderTest.java
@@ -4,20 +4,21 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.CONSULTING_TYPE_SETTINGS_U25;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.CONSULTING_TYPE_SETTINGS_WITHOUT_REGISTRATION;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.CONSULTING_TYPE_SETTINGS_WITH_MANDATORY_FIELDS_NULL;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.when;
import de.caritas.cob.userservice.api.exception.httpresponses.InternalServerErrorException;
import de.caritas.cob.userservice.api.manager.consultingtype.ConsultingTypeManager;
import de.caritas.cob.userservice.api.manager.consultingtype.registration.mandatoryfields.MandatoryFields;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class MandatoryFieldsProviderTest {
@InjectMocks private MandatoryFieldsProvider mandatoryFieldsProvider;
@@ -40,23 +41,31 @@ public class MandatoryFieldsProviderTest {
result.isState());
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
fetchMandatoryFieldsForConsultingType_Should_ThrowInternalServerError_WhenRegistrationIsNull() {
- when(consultingTypeManager.getConsultingTypeSettings(Mockito.any()))
- .thenReturn(CONSULTING_TYPE_SETTINGS_WITHOUT_REGISTRATION);
- MandatoryFields result =
- mandatoryFieldsProvider.fetchMandatoryFieldsForConsultingType(
- Integer.toString(CONSULTING_TYPE_ID_U25));
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(consultingTypeManager.getConsultingTypeSettings(Mockito.any()))
+ .thenReturn(CONSULTING_TYPE_SETTINGS_WITHOUT_REGISTRATION);
+ MandatoryFields result =
+ mandatoryFieldsProvider.fetchMandatoryFieldsForConsultingType(
+ Integer.toString(CONSULTING_TYPE_ID_U25));
+ });
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
fetchMandatoryFieldsForConsultingType_Should_ThrowInternalServerError_WhenMandatoryFieldsIsNull() {
- when(consultingTypeManager.getConsultingTypeSettings(Mockito.any()))
- .thenReturn(CONSULTING_TYPE_SETTINGS_WITH_MANDATORY_FIELDS_NULL);
- MandatoryFields result =
- mandatoryFieldsProvider.fetchMandatoryFieldsForConsultingType(
- Integer.toString(CONSULTING_TYPE_ID_U25));
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(consultingTypeManager.getConsultingTypeSettings(Mockito.any()))
+ .thenReturn(CONSULTING_TYPE_SETTINGS_WITH_MANDATORY_FIELDS_NULL);
+ MandatoryFields result =
+ mandatoryFieldsProvider.fetchMandatoryFieldsForConsultingType(
+ Integer.toString(CONSULTING_TYPE_ID_U25));
+ });
}
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/ValidAgeValidatorTest.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/ValidAgeValidatorTest.java
index 8db1888e7..a78d1f8ca 100644
--- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/ValidAgeValidatorTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/ValidAgeValidatorTest.java
@@ -8,18 +8,18 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USER_DTO_WITHOUT_MANDATORY_AGE;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USER_DTO_WITH_AGE;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USER_DTO_WITH_INVALID_AGE;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
import de.caritas.cob.userservice.api.manager.consultingtype.registration.mandatoryfields.MandatoryFields;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class ValidAgeValidatorTest {
@InjectMocks private ValidAgeValidator validAgeValidator;
diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/ValidStateValidatorTest.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/ValidStateValidatorTest.java
index bf657546c..543436c64 100644
--- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/ValidStateValidatorTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/ValidStateValidatorTest.java
@@ -8,18 +8,18 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USER_DTO_WITHOUT_MANDATORY_STATE;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USER_DTO_WITH_INVALID_STATE;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USER_DTO_WITH_STATE;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
import de.caritas.cob.userservice.api.manager.consultingtype.registration.mandatoryfields.MandatoryFields;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class ValidStateValidatorTest {
@InjectMocks private ValidStateValidator validStateValidator;
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/facade/AskerUserAdminFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/facade/AskerUserAdminFacadeTest.java
index 52cb0439a..7663e7b3d 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/facade/AskerUserAdminFacadeTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/facade/AskerUserAdminFacadeTest.java
@@ -3,6 +3,7 @@
import static de.caritas.cob.userservice.api.helper.CustomLocalDateTime.nowInUtc;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.notNullValue;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -15,14 +16,14 @@
import de.caritas.cob.userservice.api.model.User;
import de.caritas.cob.userservice.api.service.user.UserService;
import java.util.Optional;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class AskerUserAdminFacadeTest {
@InjectMocks private AskerUserAdminFacade askerUserAdminFacade;
@@ -33,21 +34,29 @@ public class AskerUserAdminFacadeTest {
@Mock private UsernameTranscoder usernameTranscoder;
- @Test(expected = NotFoundException.class)
+ @Test
public void markAskerForDeletion_Should_throwNotFoundException_When_askerDoesNotExist() {
- when(this.userService.getUser(any())).thenReturn(Optional.empty());
+ assertThrows(
+ NotFoundException.class,
+ () -> {
+ when(this.userService.getUser(any())).thenReturn(Optional.empty());
- this.askerUserAdminFacade.markAskerForDeletion("user id");
+ this.askerUserAdminFacade.markAskerForDeletion("user id");
+ });
}
- @Test(expected = ConflictException.class)
+ @Test
public void
markAskerForDeletion_Should_throwConflictException_When_askerIsAlreadyMarkedForDeletion() {
- User user = new User();
- user.setDeleteDate(nowInUtc());
- when(this.userService.getUser(any())).thenReturn(Optional.of(user));
+ assertThrows(
+ ConflictException.class,
+ () -> {
+ User user = new User();
+ user.setDeleteDate(nowInUtc());
+ when(this.userService.getUser(any())).thenReturn(Optional.of(user));
- this.askerUserAdminFacade.markAskerForDeletion("user id");
+ this.askerUserAdminFacade.markAskerForDeletion("user id");
+ });
}
@Test
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/facade/ConsultantAdminFacadeIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/facade/ConsultantAdminFacadeIT.java
index 8d52784c7..4c188a772 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/facade/ConsultantAdminFacadeIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/facade/ConsultantAdminFacadeIT.java
@@ -1,6 +1,7 @@
package de.caritas.cob.userservice.api.admin.facade;
import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.core.Is.is;
@@ -32,28 +33,24 @@
import java.util.HashSet;
import java.util.List;
import java.util.Set;
+import java.util.UUID;
import java.util.stream.Collectors;
+import javax.persistence.EntityManager;
import org.jeasy.random.EasyRandom;
import org.jeasy.random.EasyRandomParameters;
import org.jeasy.random.FieldPredicates;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
-import org.springframework.test.annotation.DirtiesContext;
-import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
-@RunWith(SpringRunner.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
-@DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD)
-public class ConsultantAdminFacadeIT {
+class ConsultantAdminFacadeIT {
@Autowired private ConsultantAdminFacade consultantAdminFacade;
@@ -69,9 +66,10 @@ public class ConsultantAdminFacadeIT {
@MockBean private AgencyServiceApiControllerFactory agencyServiceApiControllerFactory;
+ @Autowired private EntityManager entityManager;
+
@Test
- public void
- findFilteredConsultants_Should_retrieveDeletedAgencyRelations_When_consultantIsDeleted() {
+ void findFilteredConsultants_Should_retrieveDeletedAgencyRelations_When_consultantIsDeleted() {
var consultant = givenAPersistedDeletedConsultantWithTenAgencies();
var searchResult =
@@ -94,7 +92,7 @@ public class ConsultantAdminFacadeIT {
}
@Test
- public void
+ void
findFilteredConsultants_Should_retrieveOnlyNonDeletedAgencyRelations_When_consultantIsNotDeleted() {
var consultant = givenAPersistedNonDeletedConsultantWithDeletedAndNotDeletedAgencies();
@@ -124,6 +122,7 @@ public class ConsultantAdminFacadeIT {
private Consultant givenAPersistedNonDeletedConsultantWithDeletedAndNotDeletedAgencies() {
var parameters = baseConsultantParameters().excludeField(FieldPredicates.named("deleteDate"));
var consultant = new EasyRandom(parameters).nextObject(Consultant.class);
+ consultant.setLanguages(null);
consultantRepository.save(consultant);
var consultantAgencies = buildPersistedAgenciesForConsultant(20, 5, consultant);
consultant.setConsultantAgencies(consultantAgencies);
@@ -171,6 +170,8 @@ private Set buildPersistedAgenciesForConsultant(
private Consultant givenAPersistedDeletedConsultantWithTenAgencies() {
var consultant = new EasyRandom(baseConsultantParameters()).nextObject(Consultant.class);
+ consultant.setLanguages(null);
+ consultant.setId(UUID.randomUUID().toString());
consultantRepository.save(consultant);
var consultantAgencies = buildPersistedAgenciesForConsultant(10, 0, consultant);
consultant.setConsultantAgencies(consultantAgencies);
@@ -180,7 +181,7 @@ private Consultant givenAPersistedDeletedConsultantWithTenAgencies() {
}
@Test
- public void findFilteredConsultants_Should_retrieveConsultantAfterAddingRelationToAgency() {
+ void findFilteredConsultants_Should_retrieveConsultantAfterAddingRelationToAgency() {
var consultantId = "id";
givenConsultantWithoutAgency(consultantId);
@@ -208,7 +209,7 @@ public void findFilteredConsultants_Should_retrieveConsultantAfterAddingRelation
searchResult =
this.consultantAdminFacade.findFilteredConsultants(
1, 100, consultantFilter, new Sort().field(FieldEnum.FIRSTNAME).order(OrderEnum.ASC));
- assertThat(searchResult.getEmbedded(), hasSize(1));
+ assertThat(searchResult.getEmbedded(), hasSize(greaterThanOrEqualTo(1)));
}
private ExtendedConsultingTypeResponseDTO getExtendedConsultingTypeResponse() {
@@ -232,12 +233,13 @@ private void givenConsultantWithoutAgency(String id) {
newConsultant.setNotifyNewChatMessageFromAdviceSeeker(false);
newConsultant.setNotifyNewFeedbackMessageFromAdviceSeeker(false);
newConsultant.setLanguageCode(LanguageCode.de);
+ newConsultant.setLanguages(null);
consultantRepository.save(newConsultant);
}
@Test
- public void testConsultantAgencyForDeletionFiltering() {
+ void testConsultantAgencyForDeletionFiltering() {
List result = new ArrayList();
AgencyAdminResponseDTO agency1 = new AgencyAdminResponseDTO();
agency1.setId(110L);
@@ -266,7 +268,7 @@ public void testConsultantAgencyForDeletionFiltering() {
}
@Test
- public void testConsultantAgencyForCreationFiltering() {
+ void testConsultantAgencyForCreationFiltering() {
List result = new ArrayList();
AgencyAdminResponseDTO agency1 = new AgencyAdminResponseDTO();
agency1.setId(110L);
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/report/model/AgencyDependedViolationReportRuleTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/report/model/AgencyDependedViolationReportRuleTest.java
index ea11671f6..db91e4596 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/report/model/AgencyDependedViolationReportRuleTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/report/model/AgencyDependedViolationReportRuleTest.java
@@ -9,9 +9,9 @@
import de.caritas.cob.userservice.agencyadminserivce.generated.web.model.AgencyAdminResponseDTO;
import de.caritas.cob.userservice.api.adapters.web.dto.ViolationDTO;
import java.util.List;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-public class AgencyDependedViolationReportRuleTest {
+class AgencyDependedViolationReportRuleTest {
private AgencyDependedViolationReportRule reportRule =
new AgencyDependedViolationReportRule() {
@@ -22,14 +22,14 @@ public List generateViolations() {
};
@Test
- public void getAllAgencies_Should_returnEmptyList_When_noAgenciesHaveBeenSet() {
+ void getAllAgencies_Should_returnEmptyList_When_noAgenciesHaveBeenSet() {
List allAgencies = reportRule.getAllAgencies();
assertThat(allAgencies, is(emptyList()));
}
@Test
- public void getAllAgencies_Should_returnExpectedList_When_agenciesHaveBeenSet() {
+ void getAllAgencies_Should_returnExpectedList_When_agenciesHaveBeenSet() {
List agencies =
asList(new AgencyAdminResponseDTO(), new AgencyAdminResponseDTO());
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/report/registry/ViolationRuleRegistryTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/report/registry/ViolationRuleRegistryTest.java
index 93f2e1f93..0affe677f 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/report/registry/ViolationRuleRegistryTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/report/registry/ViolationRuleRegistryTest.java
@@ -15,16 +15,18 @@
import de.caritas.cob.userservice.api.admin.report.model.ViolationReportRule;
import java.util.List;
import java.util.Map;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
import org.springframework.context.ApplicationContext;
-@RunWith(MockitoJUnitRunner.class)
-public class ViolationRuleRegistryTest {
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = org.mockito.quality.Strictness.LENIENT)
+class ViolationRuleRegistryTest {
@InjectMocks private ViolationRuleRegistry violationRuleRegistry;
@@ -32,8 +34,8 @@ public class ViolationRuleRegistryTest {
@Mock private AgencyDependedViolationReportRule agencyDependedViolationReportRule;
- @Before
- public void setup() {
+ @BeforeEach
+ void setup() {
Map mockedBeans = mock(Map.class);
List mockedRules =
asList(mock(ViolationReportRule.class), agencyDependedViolationReportRule);
@@ -42,7 +44,7 @@ public void setup() {
}
@Test
- public void getViolationReportRules_Should_returnRegistratedRules_When_regitryIsInitialized() {
+ void getViolationReportRules_Should_returnRegistratedRules_When_regitryIsInitialized() {
this.violationRuleRegistry.initialize();
List registeredRules =
@@ -53,7 +55,7 @@ public void getViolationReportRules_Should_returnRegistratedRules_When_regitryIs
}
@Test
- public void getViolationReportRules_Should_returnEmptyList_When_regitryIsNotInitialized() {
+ void getViolationReportRules_Should_returnEmptyList_When_regitryIsNotInitialized() {
List registeredRules =
this.violationRuleRegistry.getViolationReportRules(emptyList());
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/report/rule/ConsultantWithWrongTeamConsultantFlagViolationReportRuleTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/report/rule/ConsultantWithWrongTeamConsultantFlagViolationReportRuleTest.java
index 11196cfa9..8c31482c5 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/report/rule/ConsultantWithWrongTeamConsultantFlagViolationReportRuleTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/report/rule/ConsultantWithWrongTeamConsultantFlagViolationReportRuleTest.java
@@ -17,13 +17,13 @@
import java.util.List;
import java.util.stream.Collectors;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class ConsultantWithWrongTeamConsultantFlagViolationReportRuleTest {
@InjectMocks private ConsultantWithWrongTeamConsultantFlagViolationReportRule reportRule;
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/report/rule/InvalidAgencyForConsultantViolationReportRuleTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/report/rule/InvalidAgencyForConsultantViolationReportRuleTest.java
index 20b200e3b..f443f7df7 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/report/rule/InvalidAgencyForConsultantViolationReportRuleTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/report/rule/InvalidAgencyForConsultantViolationReportRuleTest.java
@@ -16,13 +16,13 @@
import java.util.List;
import java.util.stream.Collectors;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class InvalidAgencyForConsultantViolationReportRuleTest {
@InjectMocks private InvalidAgencyForConsultantViolationReportRule reportRule;
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/report/rule/MissingAgencyForConsultantViolationReportRuleTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/report/rule/MissingAgencyForConsultantViolationReportRuleTest.java
index 378526f0b..cfeb4b0fd 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/report/rule/MissingAgencyForConsultantViolationReportRuleTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/report/rule/MissingAgencyForConsultantViolationReportRuleTest.java
@@ -13,13 +13,13 @@
import java.util.List;
import java.util.stream.Collectors;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class MissingAgencyForConsultantViolationReportRuleTest {
@InjectMocks private MissingAgencyForConsultantViolationReportRule reportRule;
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/report/rule/MissingRocketChatRoomForConsultantViolationReportRuleTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/report/rule/MissingRocketChatRoomForConsultantViolationReportRuleTest.java
index a42fbfabb..ec46a85c9 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/report/rule/MissingRocketChatRoomForConsultantViolationReportRuleTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/report/rule/MissingRocketChatRoomForConsultantViolationReportRuleTest.java
@@ -23,13 +23,13 @@
import de.caritas.cob.userservice.api.service.LogService;
import java.util.List;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class MissingRocketChatRoomForConsultantViolationReportRuleTest {
@InjectMocks private MissingRocketChatRoomForConsultantViolationReportRule reportRule;
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/report/rule/MissingSessionAndChatForAskerViolationReportRuleTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/report/rule/MissingSessionAndChatForAskerViolationReportRuleTest.java
index baa9e853b..95f2bb9bd 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/report/rule/MissingSessionAndChatForAskerViolationReportRuleTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/report/rule/MissingSessionAndChatForAskerViolationReportRuleTest.java
@@ -14,13 +14,13 @@
import java.util.List;
import java.util.stream.Collectors;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class MissingSessionAndChatForAskerViolationReportRuleTest {
@InjectMocks private MissingSessionAndChatForAskerViolationReportRule reportRule;
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/report/rule/TeamConsultantWithoutRequiredFlagViolationReportRuleTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/report/rule/TeamConsultantWithoutRequiredFlagViolationReportRuleTest.java
index adc6c4d33..b82474d8c 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/report/rule/TeamConsultantWithoutRequiredFlagViolationReportRuleTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/report/rule/TeamConsultantWithoutRequiredFlagViolationReportRuleTest.java
@@ -16,13 +16,13 @@
import java.util.List;
import java.util.stream.Collectors;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class TeamConsultantWithoutRequiredFlagViolationReportRuleTest {
@InjectMocks private TeamConsultantWithoutRequiredFlagViolationReportRule reportRule;
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/report/service/AgencyAdminServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/report/service/AgencyAdminServiceTest.java
index d63808834..ede8cee00 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/report/service/AgencyAdminServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/report/service/AgencyAdminServiceTest.java
@@ -1,6 +1,6 @@
package de.caritas.cob.userservice.api.admin.report.service;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
import de.caritas.cob.userservice.agencyadminserivce.generated.ApiClient;
@@ -9,17 +9,17 @@
import de.caritas.cob.userservice.api.config.apiclient.AgencyAdminServiceApiControllerFactory;
import de.caritas.cob.userservice.api.service.httpheader.SecurityHeaderSupplier;
import de.caritas.cob.userservice.api.service.httpheader.TenantHeaderSupplier;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpHeaders;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.client.RestTemplate;
-@RunWith(MockitoJUnitRunner.class)
-public class AgencyAdminServiceTest {
+@ExtendWith(MockitoExtension.class)
+class AgencyAdminServiceTest {
@InjectMocks private AgencyAdminService agencyAdminService;
@Mock private SecurityHeaderSupplier securityHeaderSupplier;
@@ -31,7 +31,7 @@ public class AgencyAdminServiceTest {
@Mock private AgencyAdminServiceApiControllerFactory agencyAdminServiceApiControllerFactory;
@Test
- public void agencyAdminControllerShouldHaveCorrectHeaders() {
+ void agencyAdminControllerShouldHaveCorrectHeaders() {
var headers = new HttpHeaders();
headers.add("header1", "header1");
when(securityHeaderSupplier.getKeycloakAndCsrfHttpHeaders()).thenReturn(headers);
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/report/service/ViolationReportGeneratorTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/report/service/ViolationReportGeneratorTest.java
index 8c4d63862..a989aea1f 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/report/service/ViolationReportGeneratorTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/report/service/ViolationReportGeneratorTest.java
@@ -14,14 +14,14 @@
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.FileUtils;
-import org.junit.After;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class ViolationReportGeneratorTest {
@InjectMocks private ViolationReportGenerator violationReportGenerator;
@@ -30,7 +30,7 @@ public class ViolationReportGeneratorTest {
@Mock private AgencyAdminService agencyAdminService;
- @After
+ @AfterEach
public void cleanGeneratedFiles() throws IOException {
FileUtils.deleteDirectory(new File("report"));
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/create/CreateAdminServiceIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/create/CreateAdminServiceIT.java
index a115750f2..68de3efbe 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/create/CreateAdminServiceIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/create/CreateAdminServiceIT.java
@@ -5,10 +5,7 @@
import static de.caritas.cob.userservice.api.config.auth.UserRole.USER_ADMIN;
import static de.caritas.cob.userservice.api.exception.httpresponses.customheader.HttpStatusExceptionReason.EMAIL_NOT_VALID;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
@@ -27,9 +24,8 @@
import de.caritas.cob.userservice.api.tenant.TenantContext;
import java.util.List;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.powermock.reflect.Whitebox;
@@ -39,14 +35,12 @@
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.util.ReflectionTestUtils;
-@RunWith(SpringRunner.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
-public class CreateAdminServiceIT {
+class CreateAdminServiceIT {
private static final String VALID_USERNAME = "validUsername";
private static final String VALID_EMAIL_ADDRESS = "valid@emailaddress.de";
@@ -57,14 +51,15 @@ public class CreateAdminServiceIT {
private final EasyRandom easyRandom = new EasyRandom();
@AfterEach
- public void afterTests() {
+ void afterTests() {
TenantContext.clear();
}
@Test
- public void
+ void
createNewAdminAgency_Should_returnExpectedCreatedAdmin_When_inputDataIsCorrectAndMultitenancyDisabled() {
// given
+ TenantContext.setCurrentTenant(1L);
ReflectionTestUtils.setField(createAdminService, "multiTenancyEnabled", false);
when(identityClient.createKeycloakUser(any(), anyString(), any()))
.thenReturn(easyRandom.nextObject(KeycloakCreateUserResponseDTO.class));
@@ -97,7 +92,7 @@ public void afterTests() {
}
@Test
- public void
+ void
createNewAdminAgency_Should_returnExpectedCreatedAdmin_When_inputDataIsCorrectAndMultitenancyEnabled() {
// given
ReflectionTestUtils.setField(createAdminService, "multiTenancyEnabled", true);
@@ -134,7 +129,7 @@ public void afterTests() {
}
@Test
- public void getUserRolesForTenantAdmin_ShouldGetProperDefaultRoles_ForSingleDomainMultitenancy() {
+ void getUserRolesForTenantAdmin_ShouldGetProperDefaultRoles_ForSingleDomainMultitenancy() {
Whitebox.setInternalState(createAdminService, "multitenancyWithSingleDomain", true);
List defaultRoles = this.createAdminService.getDefaultRoles(AdminType.TENANT);
@@ -143,7 +138,7 @@ public void getUserRolesForTenantAdmin_ShouldGetProperDefaultRoles_ForSingleDoma
}
@Test
- public void getUserRolesForTenantAdmin_ShouldGetProperDefaultRoles_ForMultidomainMultitenancy() {
+ void getUserRolesForTenantAdmin_ShouldGetProperDefaultRoles_ForMultidomainMultitenancy() {
Whitebox.setInternalState(createAdminService, "multitenancyWithSingleDomain", false);
List defaultRoles = this.createAdminService.getDefaultRoles(AdminType.TENANT);
@@ -151,25 +146,32 @@ public void getUserRolesForTenantAdmin_ShouldGetProperDefaultRoles_ForMultidomai
.containsOnly(UserRole.AGENCY_ADMIN, UserRole.SINGLE_TENANT_ADMIN, USER_ADMIN, TOPIC_ADMIN);
}
- @Test(expected = CustomValidationHttpStatusException.class)
- public void
+ @Test
+ void
createNewAdminAgency_Should_throwCustomValidationHttpStatusException_When_keycloakIdIsMissing() {
- // given
- KeycloakCreateUserResponseDTO keycloakResponse =
- easyRandom.nextObject(KeycloakCreateUserResponseDTO.class);
- keycloakResponse.setUserId(null);
- when(identityClient.createKeycloakUser(any(), anyString(), any())).thenReturn(keycloakResponse);
- CreateAdminDTO createAgencyAdminDTO = this.easyRandom.nextObject(CreateAdminDTO.class);
-
- // when
- this.createAdminService.createNewAgencyAdmin(createAgencyAdminDTO);
+ TenantContext.setCurrentTenant(1L);
+ assertThrows(
+ CustomValidationHttpStatusException.class,
+ () -> {
+ // given
+ KeycloakCreateUserResponseDTO keycloakResponse =
+ easyRandom.nextObject(KeycloakCreateUserResponseDTO.class);
+ keycloakResponse.setUserId(null);
+ when(identityClient.createKeycloakUser(any(), anyString(), any()))
+ .thenReturn(keycloakResponse);
+ CreateAdminDTO createAgencyAdminDTO = this.easyRandom.nextObject(CreateAdminDTO.class);
+
+ // when
+ this.createAdminService.createNewAgencyAdmin(createAgencyAdminDTO);
+ });
}
@Test
- public void createNewAdminAgency_Should_throwExpectedException_When_emailIsInvalid() {
+ void createNewAdminAgency_Should_throwExpectedException_When_emailIsInvalid() {
// given
CreateAdminDTO createAgencyAdminDTO = this.easyRandom.nextObject(CreateAdminDTO.class);
createAgencyAdminDTO.setEmail("invalid");
+ TenantContext.setCurrentTenant(1L);
try {
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/create/agencyrelation/CreateAdminAgencyRelationServiceIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/create/agencyrelation/CreateAdminAgencyRelationServiceIT.java
index 7fe6fbc8b..53fba1be7 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/create/agencyrelation/CreateAdminAgencyRelationServiceIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/create/agencyrelation/CreateAdminAgencyRelationServiceIT.java
@@ -3,6 +3,7 @@
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.when;
import de.caritas.cob.userservice.api.UserServiceApplication;
@@ -17,17 +18,14 @@
import de.caritas.cob.userservice.api.service.agency.AgencyService;
import java.util.List;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
-@RunWith(SpringRunner.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
@@ -62,27 +60,36 @@ public void create_Should_createExpectedCreatedAdmin_When_inputDataIsCorrect() {
assertThat(result, hasSize(1));
}
- @Test(expected = NoContentException.class)
+ @Test
public void create_Should_throwNoContentException_When_adminDoesNotExist() {
- // given
- CreateAdminAgencyRelationDTO createAdminAgencyRelationDTO =
- easyRandom.nextObject(CreateAdminAgencyRelationDTO.class);
+ assertThrows(
+ NoContentException.class,
+ () -> {
+ // given
+ CreateAdminAgencyRelationDTO createAdminAgencyRelationDTO =
+ easyRandom.nextObject(CreateAdminAgencyRelationDTO.class);
- // then
- this.createAdminAgencyRelationService.create("invalid", createAdminAgencyRelationDTO);
+ // then
+ this.createAdminAgencyRelationService.create("invalid", createAdminAgencyRelationDTO);
+ });
}
- @Test(expected = BadRequestException.class)
+ @Test
public void create_Should_throwBadRequestException_When_agencyDoesNotExist() {
- // given
- CreateAdminAgencyRelationDTO createAdminAgencyRelationDTO = new CreateAdminAgencyRelationDTO();
- long agencyId = 99L;
- createAdminAgencyRelationDTO.setAgencyId(agencyId);
- when(agencyService.getAgencyWithoutCaching(agencyId))
- .thenThrow(new BadRequestException("Agency not found"));
+ assertThrows(
+ BadRequestException.class,
+ () -> {
+ // given
+ CreateAdminAgencyRelationDTO createAdminAgencyRelationDTO =
+ new CreateAdminAgencyRelationDTO();
+ long agencyId = 99L;
+ createAdminAgencyRelationDTO.setAgencyId(agencyId);
+ when(agencyService.getAgencyWithoutCaching(agencyId))
+ .thenThrow(new BadRequestException("Agency not found"));
- // then
- createAdminAgencyRelationService.create(VALID_ADMIN_ID, createAdminAgencyRelationDTO);
+ // then
+ createAdminAgencyRelationService.create(VALID_ADMIN_ID, createAdminAgencyRelationDTO);
+ });
}
private Admin createAdminWithoutAgency() {
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/delete/DeleteAdminServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/delete/DeleteAdminServiceTest.java
index 0b3531818..9548a46ca 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/delete/DeleteAdminServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/delete/DeleteAdminServiceTest.java
@@ -5,13 +5,13 @@
import de.caritas.cob.userservice.api.port.out.AdminAgencyRepository;
import de.caritas.cob.userservice.api.port.out.AdminRepository;
import de.caritas.cob.userservice.api.port.out.IdentityClient;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class DeleteAdminServiceTest {
private final String VALID_ADMIN_ID = "164be67d-4d1b-4d80-bb6b-0ee057a1c59e";
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/search/RetrieveAdminServiceIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/search/RetrieveAdminServiceIT.java
index a1cd20c0e..fc0d07573 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/search/RetrieveAdminServiceIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/search/RetrieveAdminServiceIT.java
@@ -5,6 +5,7 @@
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import de.caritas.cob.userservice.api.UserServiceApplication;
import de.caritas.cob.userservice.api.exception.httpresponses.NoContentException;
@@ -14,8 +15,7 @@
import java.util.HashSet;
import java.util.List;
import java.util.Set;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
@@ -23,9 +23,7 @@
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
-@RunWith(SpringRunner.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
@@ -46,11 +44,15 @@ public void findAgencyAdmin_Should_returnCorrectAdmin_When_correctIdIsProvided()
assertThat(admin.getId(), is(VALID_ADMIN_ID));
}
- @Test(expected = NoContentException.class)
+ @Test
public void findAgencyAdmin_Should_throwNoContentException_When_incorrectIdIsProvided() {
- // given
- // when
- retrieveAdminService.findAdmin("invalid", Admin.AdminType.AGENCY);
+ assertThrows(
+ NoContentException.class,
+ () -> {
+ // given
+ // when
+ retrieveAdminService.findAdmin("invalid", Admin.AdminType.AGENCY);
+ });
}
@Test
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/search/RetrieveAdminServiceTenantAwareIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/search/RetrieveAdminServiceTenantAwareIT.java
index 70885146d..8df5ed682 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/search/RetrieveAdminServiceTenantAwareIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/search/RetrieveAdminServiceTenantAwareIT.java
@@ -18,7 +18,6 @@
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
@@ -26,10 +25,8 @@
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.transaction.annotation.Transactional;
-@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/update/UpdateAdminServiceIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/update/UpdateAdminServiceIT.java
index 8af4d9cb4..be3a193d4 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/update/UpdateAdminServiceIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/update/UpdateAdminServiceIT.java
@@ -4,7 +4,7 @@
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
import de.caritas.cob.userservice.api.UserServiceApplication;
import de.caritas.cob.userservice.api.adapters.web.dto.UpdateAgencyAdminDTO;
@@ -12,17 +12,14 @@
import de.caritas.cob.userservice.api.exception.httpresponses.CustomValidationHttpStatusException;
import de.caritas.cob.userservice.api.model.Admin;
import de.caritas.cob.userservice.api.port.out.IdentityClient;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
-@RunWith(SpringRunner.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/update/agencyrelation/SynchronizeAdminAgencyRelationIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/update/agencyrelation/SynchronizeAdminAgencyRelationIT.java
index 8a7726581..32d361975 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/update/agencyrelation/SynchronizeAdminAgencyRelationIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/update/agencyrelation/SynchronizeAdminAgencyRelationIT.java
@@ -19,8 +19,7 @@
import java.util.List;
import java.util.stream.Collectors;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
@@ -29,9 +28,7 @@
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
-@RunWith(SpringRunner.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminUserServiceIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminUserServiceIT.java
index f0b82dd52..d6812b2c5 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminUserServiceIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminUserServiceIT.java
@@ -10,8 +10,8 @@
import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -30,17 +30,14 @@
import java.util.Set;
import java.util.stream.Collectors;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
-@RunWith(SpringRunner.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminUserServiceTenantAwareIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminUserServiceTenantAwareIT.java
index f3d0df767..95b08dfc4 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminUserServiceTenantAwareIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminUserServiceTenantAwareIT.java
@@ -9,7 +9,7 @@
import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -33,20 +33,17 @@
import java.util.List;
import java.util.Set;
import org.jeasy.random.EasyRandom;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
-@RunWith(SpringRunner.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
@@ -77,12 +74,12 @@ public class ConsultantAgencyAdminUserServiceTenantAwareIT {
private Set consultantsToRemove = Sets.newHashSet();
- @Before
+ @BeforeEach
public void beforeTests() {
TenantContext.setCurrentTenant(1L);
}
- @After
+ @AfterEach
public void afterTests() {
consultantsToRemove.stream().forEach(id -> consultantRepository.deleteById(id));
TenantContext.clear();
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminUserServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminUserServiceTest.java
index 4d1515753..1af1811c9 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminUserServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminUserServiceTest.java
@@ -6,8 +6,7 @@
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
-import static org.junit.Assert.fail;
-import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.Mockito.times;
@@ -28,13 +27,13 @@
import java.util.List;
import java.util.stream.Collectors;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class ConsultantAgencyAdminUserServiceTest {
@InjectMocks private ConsultantAgencyAdminService consultantAgencyAdminService;
@@ -116,21 +115,26 @@ public void removeConsultantsFromTeamSessionsByAgencyId_Should_changeTeamSession
verify(this.consultantRepository, times(10)).save(any());
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
removeConsultantsFromTeamSessionsByAgencyId_Should_throwInternalServerErrorException_When_agencyServiceFails() {
- Session session = new EasyRandom().nextObject(Session.class);
- session.setTeamSession(true);
- List consultants =
- new EasyRandom().objects(Consultant.class, 10).collect(Collectors.toList());
-
- when(this.sessionRepository.findByAgencyIdAndStatusAndTeamSessionIsTrue(any(), any()))
- .thenReturn(singletonList(session));
- when(this.consultantRepository.findByConsultantAgenciesAgencyIdInAndDeleteDateIsNull(anyList()))
- .thenReturn(consultants);
- when(this.agencyService.getAgency(any())).thenThrow(new InternalServerErrorException(""));
-
- this.consultantAgencyAdminService.removeConsultantsFromTeamSessionsByAgencyId(1L);
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ Session session = new EasyRandom().nextObject(Session.class);
+ session.setTeamSession(true);
+ List consultants =
+ new EasyRandom().objects(Consultant.class, 10).collect(Collectors.toList());
+
+ when(this.sessionRepository.findByAgencyIdAndStatusAndTeamSessionIsTrue(any(), any()))
+ .thenReturn(singletonList(session));
+ when(this.consultantRepository.findByConsultantAgenciesAgencyIdInAndDeleteDateIsNull(
+ anyList()))
+ .thenReturn(consultants);
+ when(this.agencyService.getAgency(any())).thenThrow(new InternalServerErrorException(""));
+
+ this.consultantAgencyAdminService.removeConsultantsFromTeamSessionsByAgencyId(1L);
+ });
}
@Test
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyDeletionValidationServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyDeletionValidationServiceTest.java
index 2b601ae55..cb98e9a7b 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyDeletionValidationServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyDeletionValidationServiceTest.java
@@ -6,8 +6,7 @@
import static java.util.Objects.requireNonNull;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.fail;
-import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -21,13 +20,13 @@
import de.caritas.cob.userservice.api.port.out.SessionRepository;
import de.caritas.cob.userservice.api.service.agency.AgencyService;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class ConsultantAgencyDeletionValidationServiceTest {
@InjectMocks private ConsultantAgencyDeletionValidationService agencyDeletionValidationService;
@@ -80,17 +79,21 @@ public class ConsultantAgencyDeletionValidationServiceTest {
}
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
validateForDeletion_Should_throwInternalServerErrorException_When_agencyCanNotBeFetched() {
- ConsultantAgency consultantAgency = new EasyRandom().nextObject(ConsultantAgency.class);
- consultantAgency.setDeleteDate(null);
- when(this.consultantAgencyRepository.findByAgencyIdAndDeleteDateIsNull(any()))
- .thenReturn(singletonList(consultantAgency));
- when(this.agencyService.getAgencyWithoutCaching(any()))
- .thenThrow(new InternalServerErrorException(""));
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ ConsultantAgency consultantAgency = new EasyRandom().nextObject(ConsultantAgency.class);
+ consultantAgency.setDeleteDate(null);
+ when(this.consultantAgencyRepository.findByAgencyIdAndDeleteDateIsNull(any()))
+ .thenReturn(singletonList(consultantAgency));
+ when(this.agencyService.getAgencyWithoutCaching(any()))
+ .thenThrow(new InternalServerErrorException(""));
- this.agencyDeletionValidationService.validateAndMarkForDeletion(consultantAgency);
+ this.agencyDeletionValidationService.validateAndMarkForDeletion(consultantAgency);
+ });
}
@Test
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/RemoveConsultantFromRocketChatServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/RemoveConsultantFromRocketChatServiceTest.java
index 25cc01674..d2c1b7472 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/RemoveConsultantFromRocketChatServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/RemoveConsultantFromRocketChatServiceTest.java
@@ -15,13 +15,13 @@
import de.caritas.cob.userservice.api.port.out.ConsultantRepository;
import java.util.Optional;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class RemoveConsultantFromRocketChatServiceTest {
@InjectMocks private RemoveConsultantFromRocketChatService removeConsultantFromRocketChatService;
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterServiceBase.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterServiceBase.java
index fc2be5675..74362dafe 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterServiceBase.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterServiceBase.java
@@ -75,6 +75,7 @@ public void findFilteredConsultants_Should_haveCorrectPagedResults_When_noFilter
ConsultantSearchResultDTO firstPage =
this.consultantAdminFilterService.findFilteredConsultants(
1, 30, new ConsultantFilter(), null);
+
ConsultantSearchResultDTO secondPage =
this.consultantAdminFilterService.findFilteredConsultants(
2, 30, new ConsultantFilter(), null);
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterServiceIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterServiceIT.java
index 2b93ab181..794e19fc3 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterServiceIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterServiceIT.java
@@ -1,15 +1,12 @@
package de.caritas.cob.userservice.api.admin.service.consultant;
import de.caritas.cob.userservice.api.UserServiceApplication;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
-@RunWith(SpringRunner.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterServiceTenantAwareIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterServiceTenantAwareIT.java
index 1eeef5b1b..f5b6da124 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterServiceTenantAwareIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterServiceTenantAwareIT.java
@@ -3,43 +3,46 @@
import de.caritas.cob.userservice.api.UserServiceApplication;
import de.caritas.cob.userservice.api.port.out.ConsultantRepository;
import de.caritas.cob.userservice.api.tenant.TenantContext;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.context.jdbc.Sql;
import org.springframework.transaction.annotation.Transactional;
-@RunWith(SpringRunner.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
-@TestPropertySource(properties = "multitenancy.enabled=true")
+@TestPropertySource(properties = "multitenancy.enabled=false")
@TestPropertySource(
properties =
"spring.datasource.data=classpath*:database/UserServiceDatabase.sql,classpath*:database/transformDataForTenants.sql")
+@TestPropertySource(
+ properties =
+ "spring.sql.init.data-locations=classpath:database/UserServiceDatabase.sql,classpath:database/transformDataForTenants.sql")
+@Sql(scripts = {"classpath:database/transformDataForTenants.sql"})
@Transactional
public class ConsultantAdminFilterServiceTenantAwareIT extends ConsultantAdminFilterServiceBase {
@Autowired ConsultantRepository consultantRepository;
- @Before
+ @BeforeEach
public void beforeTests() {
TenantContext.setCurrentTenant(1L);
}
- @After
+ @AfterEach
public void afterTests() {
TenantContext.clear();
}
@Test
public void findFilteredConsultants_Should_returnAllConsultants_When_noFilterIsGiven() {
+ consultantRepository.findAll().forEach(consultant -> System.out.println(consultant));
super.findFilteredConsultants_Should_returnAllConsultants_When_noFilterIsGiven();
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminServiceIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminServiceIT.java
index b11cfa990..63bcd3b88 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminServiceIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminServiceIT.java
@@ -4,6 +4,7 @@
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -28,17 +29,14 @@
import org.jeasy.random.EasyRandom;
import org.jeasy.random.EasyRandomParameters;
import org.jeasy.random.FieldPredicates;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
-@RunWith(SpringRunner.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
@@ -112,9 +110,13 @@ public void findConsultantById_Should_returnExpectedConsultantLinks_When_consult
assertThat(consultantById.getLinks().getAddAgency().getMethod(), is(MethodEnum.POST));
}
- @Test(expected = NoContentException.class)
+ @Test
public void findConsultantById_Should_throwNoContentException_When_consultantIdDoesNotExist() {
- this.consultantAdminService.findConsultantById("Invalid");
+ assertThrows(
+ NoContentException.class,
+ () -> {
+ this.consultantAdminService.findConsultantById("Invalid");
+ });
}
@Test
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminServiceTest.java
index 1ac07aa16..c844bbc08 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminServiceTest.java
@@ -1,5 +1,6 @@
package de.caritas.cob.userservice.api.admin.service.consultant;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -17,13 +18,13 @@
import de.caritas.cob.userservice.api.port.out.SessionRepository;
import de.caritas.cob.userservice.api.service.appointment.AppointmentService;
import java.util.Optional;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class ConsultantAdminServiceTest {
@InjectMocks private ConsultantAdminService consultantAdminService;
@@ -44,12 +45,17 @@ public class ConsultantAdminServiceTest {
@Mock private AccountManager accountManager;
- @Test(expected = NotFoundException.class)
+ @Test
public void
markConsultantForDeletion_Should_throwNotFoundException_When_consultantdoesNotExist() {
- when(this.consultantRepository.findByIdAndDeleteDateIsNull(any())).thenReturn(Optional.empty());
-
- this.consultantAdminService.markConsultantForDeletion("id", false);
+ assertThrows(
+ NotFoundException.class,
+ () -> {
+ when(this.consultantRepository.findByIdAndDeleteDateIsNull(any()))
+ .thenReturn(Optional.empty());
+
+ this.consultantAdminService.markConsultantForDeletion("id", false);
+ });
}
@Test
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/CreateConsultantSagaIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/CreateConsultantSagaIT.java
index f2aaaa0c0..4dde4f659 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/CreateConsultantSagaIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/CreateConsultantSagaIT.java
@@ -7,7 +7,8 @@
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hibernate.validator.internal.util.CollectionHelper.asSet;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
@@ -40,9 +41,8 @@
import de.caritas.cob.userservice.tenantadminservice.generated.web.model.Settings;
import de.caritas.cob.userservice.tenantadminservice.generated.web.model.TenantDTO;
import org.jeasy.random.EasyRandom;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
@@ -50,10 +50,8 @@
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.util.ReflectionTestUtils;
-@RunWith(SpringRunner.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
@@ -80,7 +78,7 @@ public class CreateConsultantSagaIT {
private final EasyRandom easyRandom = new EasyRandom();
- @Before
+ @BeforeEach
public void setup() {
ReflectionTestUtils.setField(createConsultantSaga, "appointmentFeatureEnabled", false);
}
@@ -306,37 +304,47 @@ public void createNewConsultant_Should_callRollback_When_anyOfTheServicesThrowsE
assertThat(consultant.getFullName(), notNullValue());
}
- @Test(expected = DistributedTransactionException.class)
+ @Test
public void
createNewConsultant_Should_throwCustomValidationHttpStatusException_When_userCanNotBeCreatedInRocketChat()
throws RocketChatLoginException {
- when(rocketChatService.getUserID(anyString(), anyString(), anyBoolean()))
- .thenThrow(new RocketChatLoginException(""));
- KeycloakCreateUserResponseDTO validKeycloakResponse =
- easyRandom.nextObject(KeycloakCreateUserResponseDTO.class);
- when(keycloakService.createKeycloakUser(any(), anyString(), any()))
- .thenReturn(validKeycloakResponse);
- CreateConsultantDTO createConsultantDTO = this.easyRandom.nextObject(CreateConsultantDTO.class);
- createConsultantDTO.setUsername(VALID_USERNAME);
- createConsultantDTO.setEmail(VALID_EMAILADDRESS);
-
- this.createConsultantSaga.createNewConsultant(createConsultantDTO);
+ assertThrows(
+ DistributedTransactionException.class,
+ () -> {
+ when(rocketChatService.getUserID(anyString(), anyString(), anyBoolean()))
+ .thenThrow(new RocketChatLoginException(""));
+ KeycloakCreateUserResponseDTO validKeycloakResponse =
+ easyRandom.nextObject(KeycloakCreateUserResponseDTO.class);
+ when(keycloakService.createKeycloakUser(any(), anyString(), any()))
+ .thenReturn(validKeycloakResponse);
+ CreateConsultantDTO createConsultantDTO =
+ this.easyRandom.nextObject(CreateConsultantDTO.class);
+ createConsultantDTO.setUsername(VALID_USERNAME);
+ createConsultantDTO.setEmail(VALID_EMAILADDRESS);
+
+ this.createConsultantSaga.createNewConsultant(createConsultantDTO);
+ });
}
- @Test(expected = CustomValidationHttpStatusException.class)
+ @Test
public void
createNewConsultant_Should_throwCustomValidationHttpStatusException_When_keycloakIdIsMissing()
throws RocketChatLoginException {
- when(rocketChatService.getUserID(anyString(), anyString(), anyBoolean()))
- .thenReturn(DUMMY_RC_ID);
- KeycloakCreateUserResponseDTO keycloakResponse =
- easyRandom.nextObject(KeycloakCreateUserResponseDTO.class);
- keycloakResponse.setUserId(null);
- when(keycloakService.createKeycloakUser(any(), anyString(), any()))
- .thenReturn(keycloakResponse);
- CreateConsultantDTO createConsultantDTO = this.easyRandom.nextObject(CreateConsultantDTO.class);
-
- this.createConsultantSaga.createNewConsultant(createConsultantDTO);
+ assertThrows(
+ CustomValidationHttpStatusException.class,
+ () -> {
+ when(rocketChatService.getUserID(anyString(), anyString(), anyBoolean()))
+ .thenReturn(DUMMY_RC_ID);
+ KeycloakCreateUserResponseDTO keycloakResponse =
+ easyRandom.nextObject(KeycloakCreateUserResponseDTO.class);
+ keycloakResponse.setUserId(null);
+ when(keycloakService.createKeycloakUser(any(), anyString(), any()))
+ .thenReturn(keycloakResponse);
+ CreateConsultantDTO createConsultantDTO =
+ this.easyRandom.nextObject(CreateConsultantDTO.class);
+
+ this.createConsultantSaga.createNewConsultant(createConsultantDTO);
+ });
}
@Test
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/CreateConsultantSagaTenantAwareIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/CreateConsultantSagaTenantAwareIT.java
index 2624605f1..8f2b508ad 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/CreateConsultantSagaTenantAwareIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/CreateConsultantSagaTenantAwareIT.java
@@ -4,6 +4,7 @@
import static de.caritas.cob.userservice.api.config.auth.UserRole.GROUP_CHAT_CONSULTANT;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.notNullValue;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
@@ -29,9 +30,8 @@
import de.caritas.cob.userservice.tenantadminservice.generated.web.model.Licensing;
import de.caritas.cob.userservice.tenantadminservice.generated.web.model.TenantDTO;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
@@ -39,11 +39,9 @@
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.transaction.annotation.Transactional;
-@RunWith(SpringRunner.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
@@ -73,16 +71,21 @@ public void tearDown() {
TenantContext.clear();
}
- @Test(expected = CustomValidationHttpStatusException.class)
+ @Test
public void
createNewConsultant_Should_throwCustomValidationHttpStatusException_When_LicensesAreExceeded() {
- // given
- givenTenantApiCall();
- createConsultant("username1");
- createConsultant("username2");
- CreateConsultantDTO createConsultantDTO = this.easyRandom.nextObject(CreateConsultantDTO.class);
- this.createConsultantSaga.createNewConsultant(createConsultantDTO);
- rollbackDBState();
+ assertThrows(
+ CustomValidationHttpStatusException.class,
+ () -> {
+ // given
+ givenTenantApiCall();
+ createConsultant("username1");
+ createConsultant("username2");
+ CreateConsultantDTO createConsultantDTO =
+ this.easyRandom.nextObject(CreateConsultantDTO.class);
+ this.createConsultantSaga.createNewConsultant(createConsultantDTO);
+ rollbackDBState();
+ });
}
@Test
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorServiceIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorServiceIT.java
index 7a57aa07d..2c45294fc 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorServiceIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorServiceIT.java
@@ -7,7 +7,8 @@
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hibernate.search.util.impl.CollectionHelper.asSet;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.timeout;
@@ -42,8 +43,7 @@
import java.util.List;
import java.util.Set;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
@@ -52,9 +52,7 @@
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
-@RunWith(SpringRunner.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
@@ -274,93 +272,115 @@ private Session createSessionWithoutConsultant(Long agencyId, SessionStatus sess
return this.sessionRepository.save(session);
}
- @Test(expected = BadRequestException.class)
+ @Test
public void
createConsultantAgencyRelations_Should_throwBadRequestException_When_consultantDoesNotExist() {
- this.consultantAgencyRelationCreatorService.createConsultantAgencyRelations(
- "invalid", asSet(1L), asSet("role"), null);
+ assertThrows(
+ BadRequestException.class,
+ () -> {
+ this.consultantAgencyRelationCreatorService.createConsultantAgencyRelations(
+ "invalid", asSet(1L), asSet("role"), null);
+ });
}
- @Test(expected = BadRequestException.class)
+ @Test
public void
createNewConsultantAgency_Should_throwBadRequestException_When_consultantHasNotExpectedRole() {
- Consultant consultant = createConsultantWithoutAgencyAndSession();
+ assertThrows(
+ BadRequestException.class,
+ () -> {
+ Consultant consultant = createConsultantWithoutAgencyAndSession();
- CreateConsultantAgencyDTO createConsultantAgencyDTO = new CreateConsultantAgencyDTO();
- when(keycloakService.userHasRole(any(), any())).thenReturn(false);
+ CreateConsultantAgencyDTO createConsultantAgencyDTO = new CreateConsultantAgencyDTO();
+ when(keycloakService.userHasRole(any(), any())).thenReturn(false);
- this.consultantAgencyRelationCreatorService.createNewConsultantAgency(
- consultant.getId(), createConsultantAgencyDTO);
+ this.consultantAgencyRelationCreatorService.createNewConsultantAgency(
+ consultant.getId(), createConsultantAgencyDTO);
+ });
}
- @Test(expected = BadRequestException.class)
+ @Test
public void
createNewConsultantAgency_Should_throwBadRequestException_When_agencyServiceReturnesNullForAgency() {
- Consultant consultant = createConsultantWithoutAgencyAndSession();
-
- CreateConsultantAgencyDTO createConsultantAgencyDTO =
- new CreateConsultantAgencyDTO().roleSetKey("valid role set");
- when(keycloakService.userHasRole(any(), any())).thenReturn(true);
- when(this.agencyService.getAgencyWithoutCaching(any())).thenReturn(null);
-
- this.consultantAgencyRelationCreatorService.createNewConsultantAgency(
- consultant.getId(), createConsultantAgencyDTO);
+ assertThrows(
+ BadRequestException.class,
+ () -> {
+ Consultant consultant = createConsultantWithoutAgencyAndSession();
+
+ CreateConsultantAgencyDTO createConsultantAgencyDTO =
+ new CreateConsultantAgencyDTO().roleSetKey("valid role set");
+ when(keycloakService.userHasRole(any(), any())).thenReturn(true);
+ when(this.agencyService.getAgencyWithoutCaching(any())).thenReturn(null);
+
+ this.consultantAgencyRelationCreatorService.createNewConsultantAgency(
+ consultant.getId(), createConsultantAgencyDTO);
+ });
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
createNewConsultantAgency_Should_throwInternalServerErrorException_When_agencyServiceThrowsAgencyServiceHelperException() {
- Consultant consultant = createConsultantWithoutAgencyAndSession();
-
- CreateConsultantAgencyDTO createConsultantAgencyDTO =
- new CreateConsultantAgencyDTO().roleSetKey("valid role set");
- when(keycloakService.userHasRole(any(), any())).thenReturn(true);
- when(agencyService.getAgencyWithoutCaching(any()))
- .thenThrow(new InternalServerErrorException(""));
-
- this.consultantAgencyRelationCreatorService.createNewConsultantAgency(
- consultant.getId(), createConsultantAgencyDTO);
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ Consultant consultant = createConsultantWithoutAgencyAndSession();
+
+ CreateConsultantAgencyDTO createConsultantAgencyDTO =
+ new CreateConsultantAgencyDTO().roleSetKey("valid role set");
+ when(keycloakService.userHasRole(any(), any())).thenReturn(true);
+ when(agencyService.getAgencyWithoutCaching(any()))
+ .thenThrow(new InternalServerErrorException(""));
+
+ this.consultantAgencyRelationCreatorService.createNewConsultantAgency(
+ consultant.getId(), createConsultantAgencyDTO);
+ });
}
- @Test(expected = BadRequestException.class)
+ @Test
public void
createNewConsultantAgency_Should_throwBadRequestException_When_agencyTypeIsU25AndConsultantHasAnotherConsultingTypeAssigned() {
+ assertThrows(
+ BadRequestException.class,
+ () -> {
+ AgencyDTO emigrationAgency = new AgencyDTO().consultingType(17);
- AgencyDTO emigrationAgency = new AgencyDTO().consultingType(17);
-
- AgencyDTO agencyDTO = new AgencyDTO().consultingType(1).id(2L);
+ AgencyDTO agencyDTO = new AgencyDTO().consultingType(1).id(2L);
- when(agencyService.getAgencyWithoutCaching(1731L)).thenReturn(emigrationAgency);
- when(agencyService.getAgencyWithoutCaching(2L)).thenReturn(agencyDTO);
- when(keycloakService.userHasRole(any(), any())).thenReturn(true);
- when(consultingTypeManager.isConsultantBoundedToAgency(1)).thenReturn(true);
+ when(agencyService.getAgencyWithoutCaching(1731L)).thenReturn(emigrationAgency);
+ when(agencyService.getAgencyWithoutCaching(2L)).thenReturn(agencyDTO);
+ when(keycloakService.userHasRole(any(), any())).thenReturn(true);
+ when(consultingTypeManager.isConsultantBoundedToAgency(1)).thenReturn(true);
- CreateConsultantAgencyDTO createConsultantAgencyDTO =
- new CreateConsultantAgencyDTO().roleSetKey("valid role set").agencyId(2L);
+ CreateConsultantAgencyDTO createConsultantAgencyDTO =
+ new CreateConsultantAgencyDTO().roleSetKey("valid role set").agencyId(2L);
- String consultantIdWIthEmigrationAgency = "0b3b1cc6-be98-4787-aa56-212259d811b9";
- this.consultantAgencyRelationCreatorService.createNewConsultantAgency(
- consultantIdWIthEmigrationAgency, createConsultantAgencyDTO);
+ String consultantIdWIthEmigrationAgency = "0b3b1cc6-be98-4787-aa56-212259d811b9";
+ this.consultantAgencyRelationCreatorService.createNewConsultantAgency(
+ consultantIdWIthEmigrationAgency, createConsultantAgencyDTO);
+ });
}
- @Test(expected = BadRequestException.class)
+ @Test
public void
createNewConsultantAgency_Should_throwBadRequestException_When_agencyTypeIsKreuzbundAndConsultantHasAnotherConsultingTypeAssigned() {
+ assertThrows(
+ BadRequestException.class,
+ () -> {
+ AgencyDTO emigrationAgency = new AgencyDTO().consultingType(17);
- AgencyDTO emigrationAgency = new AgencyDTO().consultingType(17);
-
- AgencyDTO agencyDTO = new AgencyDTO().consultingType(15).id(2L);
+ AgencyDTO agencyDTO = new AgencyDTO().consultingType(15).id(2L);
- when(agencyService.getAgencyWithoutCaching(1731L)).thenReturn(emigrationAgency);
- when(agencyService.getAgencyWithoutCaching(2L)).thenReturn(agencyDTO);
- when(keycloakService.userHasRole(any(), any())).thenReturn(true);
- when(consultingTypeManager.isConsultantBoundedToAgency(15)).thenReturn(true);
+ when(agencyService.getAgencyWithoutCaching(1731L)).thenReturn(emigrationAgency);
+ when(agencyService.getAgencyWithoutCaching(2L)).thenReturn(agencyDTO);
+ when(keycloakService.userHasRole(any(), any())).thenReturn(true);
+ when(consultingTypeManager.isConsultantBoundedToAgency(15)).thenReturn(true);
- CreateConsultantAgencyDTO createConsultantAgencyDTO =
- new CreateConsultantAgencyDTO().roleSetKey("valid role set").agencyId(2L);
+ CreateConsultantAgencyDTO createConsultantAgencyDTO =
+ new CreateConsultantAgencyDTO().roleSetKey("valid role set").agencyId(2L);
- this.consultantAgencyRelationCreatorService.createNewConsultantAgency(
- "0b3b1cc6-be98-4787-aa56-212259d811b9", createConsultantAgencyDTO);
+ this.consultantAgencyRelationCreatorService.createNewConsultantAgency(
+ "0b3b1cc6-be98-4787-aa56-212259d811b9", createConsultantAgencyDTO);
+ });
}
@Test
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorServiceTenantAwareIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorServiceTenantAwareIT.java
index 9d11c356d..a30681171 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorServiceTenantAwareIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorServiceTenantAwareIT.java
@@ -37,10 +37,9 @@
import java.util.List;
import java.util.Set;
import org.jeasy.random.EasyRandom;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
@@ -49,11 +48,9 @@
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
-@RunWith(SpringRunner.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
@@ -84,12 +81,12 @@ public class ConsultantAgencyRelationCreatorServiceTenantAwareIT {
@MockBean private ConsultingTypeManager consultingTypeManager;
- @Before
+ @BeforeEach
public void beforeTests() {
TenantContext.setCurrentTenant(1L);
}
- @After
+ @AfterEach
public void afterTests() {
TenantContext.clear();
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorServiceTest.java
index d59aba22b..ff21a9edf 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorServiceTest.java
@@ -15,13 +15,13 @@
import de.caritas.cob.userservice.api.service.agency.AgencyService;
import java.util.Optional;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class ConsultantAgencyRelationCreatorServiceTest {
private final EasyRandom easyRandom = new EasyRandom();
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ImportRecordAgencyCreationInputAdapterTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ImportRecordAgencyCreationInputAdapterTest.java
index fc43dd024..1afad8d6b 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ImportRecordAgencyCreationInputAdapterTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ImportRecordAgencyCreationInputAdapterTest.java
@@ -5,7 +5,7 @@
import static org.hamcrest.Matchers.notNullValue;
import static org.hibernate.search.util.impl.CollectionHelper.asSet;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class ImportRecordAgencyCreationInputAdapterTest {
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/delete/ConsultantPreDeletionServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/delete/ConsultantPreDeletionServiceTest.java
index cbe90a169..2f26057bd 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/delete/ConsultantPreDeletionServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/delete/ConsultantPreDeletionServiceTest.java
@@ -8,7 +8,7 @@
import static java.util.Objects.requireNonNull;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -23,13 +23,13 @@
import de.caritas.cob.userservice.api.model.Session;
import de.caritas.cob.userservice.api.port.out.SessionRepository;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class ConsultantPreDeletionServiceTest {
private static final Boolean FORCE_DELETE_SESSIONS = false;
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceBase.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceBase.java
index 3e691e767..ab6fba30e 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceBase.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceBase.java
@@ -5,7 +5,7 @@
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
import de.caritas.cob.userservice.api.adapters.rocketchat.RocketChatService;
import de.caritas.cob.userservice.api.adapters.web.dto.UpdateAdminConsultantDTO;
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceIT.java
index e5f212180..ba6418ddd 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceIT.java
@@ -1,15 +1,12 @@
package de.caritas.cob.userservice.api.admin.service.consultant.update;
import de.caritas.cob.userservice.api.UserServiceApplication;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
-@RunWith(SpringRunner.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceTenantAwareIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceTenantAwareIT.java
index 1fdd79125..28e0464fb 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceTenantAwareIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceTenantAwareIT.java
@@ -11,19 +11,16 @@
import de.caritas.cob.userservice.api.tenant.TenantContext;
import java.util.Set;
import org.jeasy.random.EasyRandom;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
-@RunWith(SpringRunner.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
@@ -40,12 +37,12 @@ public class ConsultantUpdateServiceTenantAwareIT extends ConsultantUpdateServic
@Autowired ConsultantAgencyRepository consultantAgencyRepository;
private Set consultantsToRemove = Sets.newHashSet();
- @Before
+ @BeforeEach
public void beforeTests() {
TenantContext.setCurrentTenant(1L);
}
- @After
+ @AfterEach
public void afterTests() {
consultantsToRemove.stream().forEach(id -> consultantRepository.deleteById(id));
TenantContext.clear();
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceTest.java
index 633da57f3..d70aebdc0 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceTest.java
@@ -1,5 +1,6 @@
package de.caritas.cob.userservice.api.admin.service.consultant.update;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -19,14 +20,14 @@
import de.caritas.cob.userservice.api.service.appointment.AppointmentService;
import java.util.Optional;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class ConsultantUpdateServiceTest {
@InjectMocks private ConsultantUpdateService consultantUpdateService;
@@ -41,12 +42,16 @@ public class ConsultantUpdateServiceTest {
@Mock private AppointmentService appointmentService;
- @Test(expected = BadRequestException.class)
+ @Test
public void
updateConsultant_Should_throwBadRequestException_When_givenConsultantIdDoesNotExist() {
- when(this.consultantService.getConsultant(any())).thenReturn(Optional.empty());
+ assertThrows(
+ BadRequestException.class,
+ () -> {
+ when(this.consultantService.getConsultant(any())).thenReturn(Optional.empty());
- this.consultantUpdateService.updateConsultant("", mock(UpdateAdminConsultantDTO.class));
+ this.consultantUpdateService.updateConsultant("", mock(UpdateAdminConsultantDTO.class));
+ });
}
@Test
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/validation/UserAccountInputValidatorTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/validation/UserAccountInputValidatorTest.java
index b37976cab..ef3806053 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/validation/UserAccountInputValidatorTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/validation/UserAccountInputValidatorTest.java
@@ -6,7 +6,8 @@
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hibernate.validator.internal.util.CollectionHelper.asSet;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -18,13 +19,13 @@
import javax.validation.Path;
import javax.validation.Validator;
import org.hibernate.validator.internal.engine.ConstraintViolationImpl;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class UserAccountInputValidatorTest {
@InjectMocks private UserAccountInputValidator userAccountInputValidator;
@@ -87,11 +88,15 @@ public void validateKeycloakResponse_ShouldNot_throwException_When_keycloakRespo
}
}
- @Test(expected = KeycloakException.class)
+ @Test
public void validateKeycloakResponse_Should_throwKeycloakException_When_userIdIsNull() {
- KeycloakCreateUserResponseDTO responseDTO = new KeycloakCreateUserResponseDTO();
+ assertThrows(
+ KeycloakException.class,
+ () -> {
+ KeycloakCreateUserResponseDTO responseDTO = new KeycloakCreateUserResponseDTO();
- this.userAccountInputValidator.validateKeycloakResponse(responseDTO);
+ this.userAccountInputValidator.validateKeycloakResponse(responseDTO);
+ });
}
@Test
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/rocketchat/RocketChatAddToGroupOperationServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/rocketchat/RocketChatAddToGroupOperationServiceTest.java
index 560a29f7d..94ff9248f 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/rocketchat/RocketChatAddToGroupOperationServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/rocketchat/RocketChatAddToGroupOperationServiceTest.java
@@ -3,7 +3,8 @@
import static java.util.Collections.singletonList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeastOnce;
@@ -22,12 +23,12 @@
import de.caritas.cob.userservice.api.model.Session.SessionStatus;
import java.util.function.Consumer;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class RocketChatAddToGroupOperationServiceTest {
private final EasyRandom easyRandom = new EasyRandom();
@@ -92,24 +93,27 @@ public class RocketChatAddToGroupOperationServiceTest {
}
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
addToGroupsOrRollbackOnFailure_Should_logErrorMessage_When_removeOfTechnicalUserFailes() {
-
- Session session = easyRandom.nextObject(Session.class);
- session.setStatus(SessionStatus.NEW);
- Consultant consultant = easyRandom.nextObject(Consultant.class);
- doThrow(new RuntimeException(""))
- .when(this.rocketChatFacade)
- .addUserToRocketChatGroup(anyString(), anyString());
-
- RocketChatAddToGroupOperationService.getInstance(
- this.rocketChatFacade, this.keycloakService, logMethod, consultingTypeManager)
- .onSessions(singletonList(session))
- .withConsultant(consultant)
- .addToGroupsOrRollbackOnFailure();
-
- verify(logMethod, atLeastOnce()).accept(anyString());
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ Session session = easyRandom.nextObject(Session.class);
+ session.setStatus(SessionStatus.NEW);
+ Consultant consultant = easyRandom.nextObject(Consultant.class);
+ doThrow(new RuntimeException(""))
+ .when(this.rocketChatFacade)
+ .addUserToRocketChatGroup(anyString(), anyString());
+
+ RocketChatAddToGroupOperationService.getInstance(
+ this.rocketChatFacade, this.keycloakService, logMethod, consultingTypeManager)
+ .onSessions(singletonList(session))
+ .withConsultant(consultant)
+ .addToGroupsOrRollbackOnFailure();
+
+ verify(logMethod, atLeastOnce()).accept(anyString());
+ });
}
@Test
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/rocketchat/RocketChatOperationConditionProviderTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/rocketchat/RocketChatOperationConditionProviderTest.java
index 95a6f6b5d..1ea4d4164 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/rocketchat/RocketChatOperationConditionProviderTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/rocketchat/RocketChatOperationConditionProviderTest.java
@@ -12,13 +12,13 @@
import de.caritas.cob.userservice.api.model.Consultant;
import de.caritas.cob.userservice.api.model.Session;
import de.caritas.cob.userservice.api.model.Session.SessionStatus;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class RocketChatOperationConditionProviderTest {
@InjectMocks private RocketChatOperationConditionProvider conditionProvider;
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/rocketchat/RocketChatRemoveFromGroupOperationServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/rocketchat/RocketChatRemoveFromGroupOperationServiceTest.java
index 9dd34df30..07526d5f7 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/rocketchat/RocketChatRemoveFromGroupOperationServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/rocketchat/RocketChatRemoveFromGroupOperationServiceTest.java
@@ -3,7 +3,7 @@
import static java.util.Collections.singletonList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
@@ -23,13 +23,13 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class RocketChatRemoveFromGroupOperationServiceTest {
private RocketChatRemoveFromGroupOperationService removeService;
@@ -44,7 +44,7 @@ public class RocketChatRemoveFromGroupOperationServiceTest {
@Mock private ConsultingTypeManager consultingTypeManager;
- @Before
+ @BeforeEach
public void setup() {
Map> sessionConsultants = new HashMap<>();
sessionConsultants.put(session, singletonList(consultant));
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/session/SessionAdminServiceIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/session/SessionAdminServiceIT.java
index a3ae92ad7..2b0bc14c6 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/session/SessionAdminServiceIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/session/SessionAdminServiceIT.java
@@ -9,16 +9,13 @@
import de.caritas.cob.userservice.api.adapters.web.dto.SessionAdminDTO;
import de.caritas.cob.userservice.api.adapters.web.dto.SessionAdminResultDTO;
import de.caritas.cob.userservice.api.adapters.web.dto.SessionFilter;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
-@RunWith(SpringRunner.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/session/SessionAdminServiceTenantAwareIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/session/SessionAdminServiceTenantAwareIT.java
index 36e8570f7..a2059ce9f 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/session/SessionAdminServiceTenantAwareIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/session/SessionAdminServiceTenantAwareIT.java
@@ -7,19 +7,16 @@
import de.caritas.cob.userservice.api.adapters.web.dto.SessionAdminResultDTO;
import de.caritas.cob.userservice.api.adapters.web.dto.SessionFilter;
import de.caritas.cob.userservice.api.tenant.TenantContext;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
-@RunWith(SpringRunner.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
@@ -32,12 +29,12 @@ public class SessionAdminServiceTenantAwareIT {
@Autowired private SessionAdminService sessionAdminService;
- @Before
+ @BeforeEach
public void beforeTests() {
TenantContext.setCurrentTenant(1L);
}
- @After
+ @AfterEach
public void afterTests() {
TenantContext.clear();
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/session/pageprovider/AgencySessionPageProviderTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/session/pageprovider/AgencySessionPageProviderTest.java
index a509992e4..14b808823 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/session/pageprovider/AgencySessionPageProviderTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/session/pageprovider/AgencySessionPageProviderTest.java
@@ -8,15 +8,15 @@
import de.caritas.cob.userservice.api.adapters.web.dto.SessionFilter;
import de.caritas.cob.userservice.api.port.out.SessionRepository;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.domain.PageRequest;
-@RunWith(MockitoJUnitRunner.class)
-public class AgencySessionPageProviderTest {
+@ExtendWith(MockitoExtension.class)
+class AgencySessionPageProviderTest {
@InjectMocks private AgencySessionPageProvider agencySessionPageProvider;
@@ -25,7 +25,7 @@ public class AgencySessionPageProviderTest {
@Mock private SessionFilter sessionFilter;
@Test
- public void supports_Should_returnTrue_When_agencyFilterIsSet() {
+ void supports_Should_returnTrue_When_agencyFilterIsSet() {
when(this.sessionFilter.getAgency()).thenReturn(1);
boolean supports = this.agencySessionPageProvider.isSupported();
@@ -34,7 +34,7 @@ public void supports_Should_returnTrue_When_agencyFilterIsSet() {
}
@Test
- public void supports_Should_returnFalse_When_agencyFilterIsNotSet() {
+ void supports_Should_returnFalse_When_agencyFilterIsNotSet() {
when(this.sessionFilter.getAgency()).thenReturn(null);
boolean supports = this.agencySessionPageProvider.isSupported();
@@ -43,7 +43,7 @@ public void supports_Should_returnFalse_When_agencyFilterIsNotSet() {
}
@Test
- public void executeQuery_Should_executeQueryOnRepository_When_pagebleIsGiven() {
+ void executeQuery_Should_executeQueryOnRepository_When_pagebleIsGiven() {
when(this.sessionFilter.getAgency()).thenReturn(1);
PageRequest pageable = PageRequest.of(0, 1);
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/session/pageprovider/AllSessionPageProviderTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/session/pageprovider/AllSessionPageProviderTest.java
index b028636d5..8b25dceb6 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/session/pageprovider/AllSessionPageProviderTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/session/pageprovider/AllSessionPageProviderTest.java
@@ -6,29 +6,29 @@
import static org.mockito.Mockito.verify;
import de.caritas.cob.userservice.api.port.out.SessionRepository;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.domain.PageRequest;
-@RunWith(MockitoJUnitRunner.class)
-public class AllSessionPageProviderTest {
+@ExtendWith(MockitoExtension.class)
+class AllSessionPageProviderTest {
@InjectMocks private AllSessionPageProvider allSessionPageProvider;
@Mock private SessionRepository sessionRepository;
@Test
- public void supports_Should_returnTrue() {
+ void supports_Should_returnTrue() {
boolean supports = this.allSessionPageProvider.isSupported();
assertThat(supports, is(true));
}
@Test
- public void executeQuery_Should_executeQueryOnRepository_When_pagebleIsGiven() {
+ void executeQuery_Should_executeQueryOnRepository_When_pagebleIsGiven() {
PageRequest pageable = PageRequest.of(0, 1);
this.allSessionPageProvider.executeQuery(pageable);
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/session/pageprovider/AskerSessionPageProviderTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/session/pageprovider/AskerSessionPageProviderTest.java
index 9728b6dc8..d046b19da 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/session/pageprovider/AskerSessionPageProviderTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/session/pageprovider/AskerSessionPageProviderTest.java
@@ -8,15 +8,15 @@
import de.caritas.cob.userservice.api.adapters.web.dto.SessionFilter;
import de.caritas.cob.userservice.api.port.out.SessionRepository;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.domain.PageRequest;
-@RunWith(MockitoJUnitRunner.class)
-public class AskerSessionPageProviderTest {
+@ExtendWith(MockitoExtension.class)
+class AskerSessionPageProviderTest {
@InjectMocks private AskerSessionPageProvider askerSessionPageProvider;
@@ -25,7 +25,7 @@ public class AskerSessionPageProviderTest {
@Mock private SessionFilter sessionFilter;
@Test
- public void supports_Should_returnTrue_When_askerFilterIsSet() {
+ void supports_Should_returnTrue_When_askerFilterIsSet() {
when(this.sessionFilter.getAsker()).thenReturn("asker");
boolean supports = this.askerSessionPageProvider.isSupported();
@@ -34,7 +34,7 @@ public void supports_Should_returnTrue_When_askerFilterIsSet() {
}
@Test
- public void supports_Should_returnFalse_When_askerFilterIsNotSet() {
+ void supports_Should_returnFalse_When_askerFilterIsNotSet() {
when(this.sessionFilter.getAsker()).thenReturn(null);
boolean supports = this.askerSessionPageProvider.isSupported();
@@ -43,7 +43,7 @@ public void supports_Should_returnFalse_When_askerFilterIsNotSet() {
}
@Test
- public void executeQuery_Should_executeQueryOnRepository_When_pagebleIsGiven() {
+ void executeQuery_Should_executeQueryOnRepository_When_pagebleIsGiven() {
when(this.sessionFilter.getAsker()).thenReturn("asker");
PageRequest pageable = PageRequest.of(0, 1);
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/session/pageprovider/ConsultantSessionPageProviderTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/session/pageprovider/ConsultantSessionPageProviderTest.java
index a5baef4c2..bc79babc4 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/session/pageprovider/ConsultantSessionPageProviderTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/session/pageprovider/ConsultantSessionPageProviderTest.java
@@ -8,14 +8,14 @@
import de.caritas.cob.userservice.api.adapters.web.dto.SessionFilter;
import de.caritas.cob.userservice.api.port.out.SessionRepository;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.domain.PageRequest;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class ConsultantSessionPageProviderTest {
@InjectMocks private ConsultantSessionPageProvider consultantSessionPageProvider;
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/session/pageprovider/ConsultingTypeSessionPageProviderTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/session/pageprovider/ConsultingTypeSessionPageProviderTest.java
index eec41d338..b1bb6e79a 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/session/pageprovider/ConsultingTypeSessionPageProviderTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/session/pageprovider/ConsultingTypeSessionPageProviderTest.java
@@ -8,14 +8,14 @@
import de.caritas.cob.userservice.api.adapters.web.dto.SessionFilter;
import de.caritas.cob.userservice.api.port.out.SessionRepository;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.domain.PageRequest;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class ConsultingTypeSessionPageProviderTest {
@InjectMocks private ConsultingTypeSessionPageProvider consultingTypeSessionPageProvider;
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/session/pageprovider/PageProviderFactoryTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/session/pageprovider/PageProviderFactoryTest.java
index 22c1edb92..d150e42a4 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/session/pageprovider/PageProviderFactoryTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/session/pageprovider/PageProviderFactoryTest.java
@@ -5,12 +5,12 @@
import de.caritas.cob.userservice.api.adapters.web.dto.SessionFilter;
import de.caritas.cob.userservice.api.port.out.SessionRepository;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class PageProviderFactoryTest {
@Mock private SessionRepository sessionRepository;
diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/user/anonymous/AnonymousUsernameRegistryTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/user/anonymous/AnonymousUsernameRegistryTest.java
index 2c7b5a690..e04bffbdf 100644
--- a/src/test/java/de/caritas/cob/userservice/api/admin/service/user/anonymous/AnonymousUsernameRegistryTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/user/anonymous/AnonymousUsernameRegistryTest.java
@@ -20,30 +20,32 @@
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoSettings;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
-public class AnonymousUsernameRegistryTest {
+@MockitoSettings(strictness = org.mockito.quality.Strictness.LENIENT)
+class AnonymousUsernameRegistryTest {
@InjectMocks private AnonymousUsernameRegistry anonymousUsernameRegistry;
@Mock private UserService userService;
@Mock private ConsultantService consultantService;
@Mock private UsernameTranscoder usernameTranscoder;
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
setField(anonymousUsernameRegistry, "usernameTranscoder", usernameTranscoder);
setField(anonymousUsernameRegistry, "usernamePrefix", "Ratsuchende_r ");
}
@Test
- public void
+ void
generateUniqueUsername_Should_GenerateUsernameWithMissingIdOfList_When_MissingUserIdNotExistingInDb() {
LinkedList idRegistryListWithoutThree = new LinkedList<>(List.of(1, 2, 4, 5));
setIdRegistryField(idRegistryListWithoutThree);
@@ -61,7 +63,7 @@ private void setIdRegistryField(LinkedList idRegistryListWithoutThree)
}
@Test
- public void
+ void
generateUniqueUsername_Should_GenerateUsernameWithSecondMissingIdOfList_When_FirstMissingUserIdIsExistingInDb() {
LinkedList idRegistryListWithoutThree = new LinkedList<>(List.of(1, 2, 4, 6));
setIdRegistryField(idRegistryListWithoutThree);
@@ -76,7 +78,7 @@ private void setIdRegistryField(LinkedList idRegistryListWithoutThree)
}
@Test
- public void
+ void
generateUniqueUsername_Should_GenerateUsernameWithIdOne_When_ListIsEmptyAndUserNotExistingInDb() {
LinkedList idRegistryListWithoutThree = new LinkedList<>();
setIdRegistryField(idRegistryListWithoutThree);
@@ -90,7 +92,7 @@ private void setIdRegistryField(LinkedList idRegistryListWithoutThree)
}
@Test
- public void
+ void
generateUniqueUsername_Should_GenerateUsernameWithIdGreaterThanBiggestListId_When_ListContainsContiguousIdsAndUserNotExistingInDb() {
LinkedList idRegistryListWithoutThree = new LinkedList<>(List.of(1, 2, 3, 4, 5));
setIdRegistryField(idRegistryListWithoutThree);
@@ -104,7 +106,7 @@ private void setIdRegistryField(LinkedList idRegistryListWithoutThree)
}
@Test
- public void
+ void
generateUniqueUsername_Should_GenerateUsernameWithIdGreaterThanBiggestListId_When_MissingIdsOfListHaveExistingUsersInDb() {
LinkedList idRegistryListWithoutThree = new LinkedList<>(List.of(1, 2, 4, 6));
setIdRegistryField(idRegistryListWithoutThree);
@@ -120,7 +122,7 @@ private void setIdRegistryField(LinkedList idRegistryListWithoutThree)
}
@Test
- public void
+ void
generateUniqueUsername_Should_GenerateUsernameWithIdGreaterThanBiggestListId_When_MissingIdsOfListHaveExistingConsultantsInDb() {
LinkedList idRegistryListWithoutThree = new LinkedList<>(List.of(1, 2, 4, 6));
setIdRegistryField(idRegistryListWithoutThree);
@@ -138,7 +140,7 @@ private void setIdRegistryField(LinkedList idRegistryListWithoutThree)
}
@Test
- public void
+ void
removeRegistryIdByUsername_Should_RemoveIdFromRegistry_When_UsernameMatchesUsernamePattern() {
String usernameToDelete = "Ratsuchende_r 2";
@@ -159,7 +161,7 @@ private List getIdRegistryField() {
}
@Test
- public void
+ void
removeRegistryIdByUsername_Should_NotModifyTheRegistry_When_UsernameDoesNotMatchUsernamePattern() {
String usernameNotMatchingPattern = "something else";
@@ -176,7 +178,7 @@ private List getIdRegistryField() {
}
@Test
- public void
+ void
removeRegistryIdByUsername_Should_NotModifyTheRegistry_When_UsernameDoesMatchUsernamePatternButHasNotExistingNumber() {
String usernameWithNotExistingId = "Ratsuchende_r 3";
@@ -193,7 +195,7 @@ private List getIdRegistryField() {
}
@Test
- public void removeRegistryIdByUsername_Should_NotModifyTheRegistry_When_EmptyValuePassed() {
+ void removeRegistryIdByUsername_Should_NotModifyTheRegistry_When_EmptyValuePassed() {
LinkedList idRegistryListWithoutThree = new LinkedList<>(List.of(1, 2, 4, 5));
setIdRegistryField(idRegistryListWithoutThree);
when(userService.findUserByUsername(any())).thenReturn(Optional.empty());
@@ -209,7 +211,7 @@ public void removeRegistryIdByUsername_Should_NotModifyTheRegistry_When_EmptyVal
}
@Test
- public void removeRegistryIdByUsername_Should_NotModifyTheRegistry_When_NullPassed() {
+ void removeRegistryIdByUsername_Should_NotModifyTheRegistry_When_NullPassed() {
LinkedList idRegistryListWithoutThree = new LinkedList<>(List.of(1, 2, 4, 5));
setIdRegistryField(idRegistryListWithoutThree);
when(userService.findUserByUsername(any())).thenReturn(Optional.empty());
diff --git a/src/test/java/de/caritas/cob/userservice/api/config/auth/AuthorityTest.java b/src/test/java/de/caritas/cob/userservice/api/config/auth/AuthorityTest.java
index 17cb21629..237ffa21e 100644
--- a/src/test/java/de/caritas/cob/userservice/api/config/auth/AuthorityTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/config/auth/AuthorityTest.java
@@ -7,17 +7,15 @@
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import de.caritas.cob.userservice.api.config.auth.Authority.AuthorityValue;
import java.util.List;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class AuthorityTest {
@Test
diff --git a/src/test/java/de/caritas/cob/userservice/api/config/auth/RoleAuthorizationAuthorityMapperTest.java b/src/test/java/de/caritas/cob/userservice/api/config/auth/RoleAuthorizationAuthorityMapperTest.java
index c0e050e2e..91d52c4cd 100644
--- a/src/test/java/de/caritas/cob/userservice/api/config/auth/RoleAuthorizationAuthorityMapperTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/config/auth/RoleAuthorizationAuthorityMapperTest.java
@@ -9,18 +9,18 @@
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.keycloak.adapters.RefreshableKeycloakSecurityContext;
import org.keycloak.adapters.spi.KeycloakAccount;
import org.keycloak.adapters.springsecurity.account.SimpleKeycloakAccount;
import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider;
import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class RoleAuthorizationAuthorityMapperTest {
private final KeycloakAuthenticationProvider provider = new KeycloakAuthenticationProvider();
diff --git a/src/test/java/de/caritas/cob/userservice/api/conversation/facade/AcceptAnonymousEnquiryFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/conversation/facade/AcceptAnonymousEnquiryFacadeTest.java
index 6da38f4fa..da460877d 100644
--- a/src/test/java/de/caritas/cob/userservice/api/conversation/facade/AcceptAnonymousEnquiryFacadeTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/conversation/facade/AcceptAnonymousEnquiryFacadeTest.java
@@ -1,5 +1,6 @@
package de.caritas.cob.userservice.api.conversation.facade;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
@@ -14,14 +15,14 @@
import de.caritas.cob.userservice.api.service.user.UserAccountService;
import java.util.Optional;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
-public class AcceptAnonymousEnquiryFacadeTest {
+@ExtendWith(MockitoExtension.class)
+class AcceptAnonymousEnquiryFacadeTest {
@InjectMocks private AcceptAnonymousEnquiryFacade acceptAnonymousEnquiryFacade;
@@ -34,7 +35,7 @@ public class AcceptAnonymousEnquiryFacadeTest {
@Mock private UserAccountService userAccountService;
@Test
- public void acceptAnonymousEnquiry_Should_useServicesCorrectly_When_sessionExists() {
+ void acceptAnonymousEnquiry_Should_useServicesCorrectly_When_sessionExists() {
Session session = new EasyRandom().nextObject(Session.class);
when(this.sessionService.getSession(session.getId())).thenReturn(Optional.of(session));
@@ -46,8 +47,12 @@ public void acceptAnonymousEnquiry_Should_useServicesCorrectly_When_sessionExist
.sendAcceptAnonymousEnquiryEventToUser(session.getUser().getUserId());
}
- @Test(expected = NotFoundException.class)
- public void acceptAnonymousEnquiry_Should_throwNotFoundException_When_sessionDoesNotExist() {
- this.acceptAnonymousEnquiryFacade.acceptAnonymousEnquiry(1L);
+ @Test
+ void acceptAnonymousEnquiry_Should_throwNotFoundException_When_sessionDoesNotExist() {
+ assertThrows(
+ NotFoundException.class,
+ () -> {
+ this.acceptAnonymousEnquiryFacade.acceptAnonymousEnquiry(1L);
+ });
}
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/conversation/provider/AnonymousEnquiryConversationListProviderIT.java b/src/test/java/de/caritas/cob/userservice/api/conversation/provider/AnonymousEnquiryConversationListProviderIT.java
index c1fc1401f..55da81287 100644
--- a/src/test/java/de/caritas/cob/userservice/api/conversation/provider/AnonymousEnquiryConversationListProviderIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/conversation/provider/AnonymousEnquiryConversationListProviderIT.java
@@ -35,10 +35,9 @@
import java.util.stream.Collectors;
import org.apache.commons.collections4.iterators.PeekingIterator;
import org.jeasy.random.EasyRandom;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
@@ -46,14 +45,12 @@
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
-@RunWith(SpringRunner.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
@Import({ConsultingTypeManagerTestConfig.class})
-public class AnonymousEnquiryConversationListProviderIT {
+class AnonymousEnquiryConversationListProviderIT {
@Autowired
private AnonymousEnquiryConversationListProvider anonymousEnquiryConversationListProvider;
@@ -66,8 +63,8 @@ public class AnonymousEnquiryConversationListProviderIT {
@MockBean private UserAccountService userAccountProvider;
- @Before
- public void setup() {
+ @BeforeEach
+ void setup() {
Consultant consultant = mock(Consultant.class);
ConsultantAgency consultantAgency = mock(ConsultantAgency.class);
when(consultant.getConsultantAgencies()).thenReturn(asSet(consultantAgency));
@@ -76,14 +73,13 @@ public void setup() {
when(this.agencyService.getAgencies(any())).thenReturn(singletonList(agencyDTO));
}
- @After
- public void cleanDatabase() {
+ @AfterEach
+ void cleanDatabase() {
this.sessionRepository.deleteAll();
}
@Test
- public void
- buildConversations_Should_returnExpectedResponseDTO_When_consultantHasAnonymousEnquiries() {
+ void buildConversations_Should_returnExpectedResponseDTO_When_consultantHasAnonymousEnquiries() {
saveAnonymousSessions(10);
PageableListRequest request = PageableListRequest.builder().count(5).offset(0).build();
@@ -97,7 +93,7 @@ public void cleanDatabase() {
}
@Test
- public void buildConversations_Should_returnExpectedElements_When_paginationParamsAreAtTheEnd() {
+ void buildConversations_Should_returnExpectedElements_When_paginationParamsAreAtTheEnd() {
saveAnonymousSessions(10);
PageableListRequest request = PageableListRequest.builder().count(3).offset(9).build();
@@ -111,7 +107,7 @@ public void buildConversations_Should_returnExpectedElements_When_paginationPara
}
@Test
- public void buildConversations_Should_returnElementsInExpectedOrder() {
+ void buildConversations_Should_returnElementsInExpectedOrder() {
saveAnonymousSessions(100);
PageableListRequest request = PageableListRequest.builder().count(100).offset(0).build();
@@ -130,7 +126,7 @@ public void buildConversations_Should_returnElementsInExpectedOrder() {
}
@Test
- public void providedType_Should_return_anonymousEnquiry() {
+ void providedType_Should_return_anonymousEnquiry() {
ConversationListType conversationListType =
this.anonymousEnquiryConversationListProvider.providedType();
diff --git a/src/test/java/de/caritas/cob/userservice/api/conversation/provider/ArchivedSessionConversationListProviderTestIT.java b/src/test/java/de/caritas/cob/userservice/api/conversation/provider/ArchivedSessionConversationListProviderTestIT.java
index b0370f8fb..825466736 100644
--- a/src/test/java/de/caritas/cob/userservice/api/conversation/provider/ArchivedSessionConversationListProviderTestIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/conversation/provider/ArchivedSessionConversationListProviderTestIT.java
@@ -34,22 +34,19 @@
import org.apache.commons.collections4.iterators.PeekingIterator;
import org.apache.commons.lang3.RandomStringUtils;
import org.jeasy.random.EasyRandom;
-import org.junit.After;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
-@RunWith(SpringRunner.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
-public class ArchivedSessionConversationListProviderTestIT {
+class ArchivedSessionConversationListProviderTestIT {
@Autowired
private ArchivedSessionConversationListProvider archivedSessionConversationListProvider;
@@ -64,16 +61,15 @@ public class ArchivedSessionConversationListProviderTestIT {
@MockBean private UserAccountService userAccountProvider;
- @After
- public void cleanDatabase() {
+ @AfterEach
+ void cleanDatabase() {
this.sessionRepository.deleteAll();
this.consultantAgencyRepository.deleteAll();
this.consultantRepository.deleteAll();
}
@Test
- public void
- buildConversations_Should_returnExpectedResponseDTO_When_consultantHasArchivedSessions() {
+ void buildConversations_Should_returnExpectedResponseDTO_When_consultantHasArchivedSessions() {
saveTestData(10);
PageableListRequest request = PageableListRequest.builder().count(5).offset(0).build();
@@ -87,7 +83,7 @@ public void cleanDatabase() {
}
@Test
- public void buildConversations_Should_returnExpectedElements_When_paginationParamsAreAtTheEnd() {
+ void buildConversations_Should_returnExpectedElements_When_paginationParamsAreAtTheEnd() {
saveTestData(10);
PageableListRequest request = PageableListRequest.builder().count(3).offset(9).build();
@@ -101,7 +97,7 @@ public void buildConversations_Should_returnExpectedElements_When_paginationPara
}
@Test
- public void buildConversations_Should_returnElementsInExpectedOrder() {
+ void buildConversations_Should_returnElementsInExpectedOrder() {
saveTestData(100);
PageableListRequest request = PageableListRequest.builder().count(100).offset(0).build();
@@ -120,7 +116,7 @@ public void buildConversations_Should_returnElementsInExpectedOrder() {
}
@Test
- public void providedType_Should_return_archivedSession() {
+ void providedType_Should_return_archivedSession() {
ConversationListType conversationListType =
this.archivedSessionConversationListProvider.providedType();
diff --git a/src/test/java/de/caritas/cob/userservice/api/conversation/provider/ArchivedTeamSessionConversationListProviderTestIT.java b/src/test/java/de/caritas/cob/userservice/api/conversation/provider/ArchivedTeamSessionConversationListProviderTestIT.java
index 043fac64f..5d4bc128a 100644
--- a/src/test/java/de/caritas/cob/userservice/api/conversation/provider/ArchivedTeamSessionConversationListProviderTestIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/conversation/provider/ArchivedTeamSessionConversationListProviderTestIT.java
@@ -34,22 +34,19 @@
import org.apache.commons.collections4.iterators.PeekingIterator;
import org.apache.commons.lang3.RandomStringUtils;
import org.jeasy.random.EasyRandom;
-import org.junit.After;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
-@RunWith(SpringRunner.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
-public class ArchivedTeamSessionConversationListProviderTestIT {
+class ArchivedTeamSessionConversationListProviderTestIT {
@Autowired
private ArchivedTeamSessionConversationListProvider archivedTeamSessionConversationListProvider;
@@ -64,15 +61,15 @@ public class ArchivedTeamSessionConversationListProviderTestIT {
@MockBean private UserAccountService userAccountProvider;
- @After
- public void cleanDatabase() {
+ @AfterEach
+ void cleanDatabase() {
this.sessionRepository.deleteAll();
this.consultantAgencyRepository.deleteAll();
this.consultantRepository.deleteAll();
}
@Test
- public void
+ void
buildConversations_Should_returnExpectedResponseDTO_When_consultantHasArchivedTeamSessions() {
saveTestData(10);
PageableListRequest request = PageableListRequest.builder().count(5).offset(0).build();
@@ -87,7 +84,7 @@ public void cleanDatabase() {
}
@Test
- public void buildConversations_Should_returnExpectedElements_When_paginationParamsAreAtTheEnd() {
+ void buildConversations_Should_returnExpectedElements_When_paginationParamsAreAtTheEnd() {
saveTestData(10);
PageableListRequest request = PageableListRequest.builder().count(3).offset(9).build();
@@ -101,7 +98,7 @@ public void buildConversations_Should_returnExpectedElements_When_paginationPara
}
@Test
- public void buildConversations_Should_returnElementsInExpectedOrder() {
+ void buildConversations_Should_returnElementsInExpectedOrder() {
saveTestData(100);
PageableListRequest request = PageableListRequest.builder().count(100).offset(0).build();
@@ -120,7 +117,7 @@ public void buildConversations_Should_returnElementsInExpectedOrder() {
}
@Test
- public void providedType_Should_return_archivedTeamSession() {
+ void providedType_Should_return_archivedTeamSession() {
ConversationListType conversationListType =
this.archivedTeamSessionConversationListProvider.providedType();
diff --git a/src/test/java/de/caritas/cob/userservice/api/conversation/provider/RegisteredEnquiryConversationListProviderIT.java b/src/test/java/de/caritas/cob/userservice/api/conversation/provider/RegisteredEnquiryConversationListProviderIT.java
index 38f0e49dd..ec1c47833 100644
--- a/src/test/java/de/caritas/cob/userservice/api/conversation/provider/RegisteredEnquiryConversationListProviderIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/conversation/provider/RegisteredEnquiryConversationListProviderIT.java
@@ -30,19 +30,16 @@
import java.util.stream.Collectors;
import org.apache.commons.collections4.iterators.PeekingIterator;
import org.jeasy.random.EasyRandom;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
-@RunWith(SpringRunner.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
@@ -57,7 +54,7 @@ public class RegisteredEnquiryConversationListProviderIT {
@MockBean private UserAccountService userAccountProvider;
- @Before
+ @BeforeEach
public void setup() {
Consultant consultant = mock(Consultant.class);
ConsultantAgency consultantAgency = mock(ConsultantAgency.class);
@@ -66,7 +63,7 @@ public void setup() {
when(this.userAccountProvider.retrieveValidatedConsultant()).thenReturn(consultant);
}
- @After
+ @AfterEach
public void cleanDatabase() {
this.sessionRepository.deleteAll();
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/conversation/registry/ConversationListProviderRegistryTest.java b/src/test/java/de/caritas/cob/userservice/api/conversation/registry/ConversationListProviderRegistryTest.java
index a95f00f60..1e49b4fa3 100644
--- a/src/test/java/de/caritas/cob/userservice/api/conversation/registry/ConversationListProviderRegistryTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/conversation/registry/ConversationListProviderRegistryTest.java
@@ -4,6 +4,7 @@
import static de.caritas.cob.userservice.api.conversation.model.ConversationListType.REGISTERED_ENQUIRY;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -13,23 +14,25 @@
import de.caritas.cob.userservice.api.conversation.provider.RegisteredEnquiryConversationListProvider;
import java.util.Map;
import java.util.NoSuchElementException;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
import org.springframework.context.ApplicationContext;
-@RunWith(MockitoJUnitRunner.class)
-public class ConversationListProviderRegistryTest {
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = org.mockito.quality.Strictness.LENIENT)
+class ConversationListProviderRegistryTest {
@InjectMocks private ConversationListProviderRegistry conversationListProviderRegistry;
@Mock private ApplicationContext applicationContext;
- @Before
- public void setup() {
+ @BeforeEach
+ void setup() {
ConversationListProvider anonymous = mock(AnonymousEnquiryConversationListProvider.class);
when(anonymous.providedType()).thenReturn(ANONYMOUS_ENQUIRY);
ConversationListProvider registered = mock(RegisteredEnquiryConversationListProvider.class);
@@ -38,13 +41,17 @@ public void setup() {
.thenReturn(Map.of("anonymous", anonymous, "registered", registered));
}
- @Test(expected = NullPointerException.class)
- public void findByConversationType_Should_throwNPE_When_registryIsNotInitialized() {
- this.conversationListProviderRegistry.findByConversationType(ANONYMOUS_ENQUIRY);
+ @Test
+ void findByConversationType_Should_throwNPE_When_registryIsNotInitialized() {
+ assertThrows(
+ NullPointerException.class,
+ () -> {
+ this.conversationListProviderRegistry.findByConversationType(ANONYMOUS_ENQUIRY);
+ });
}
@Test
- public void
+ void
findByConversationType_Should_returnAnonymousEnquiryProvider_When_requestedTypeIsAnonymouseEnquiry() {
this.conversationListProviderRegistry.initializeConversationSuppliers();
@@ -56,7 +63,7 @@ public void findByConversationType_Should_throwNPE_When_registryIsNotInitialized
}
@Test
- public void
+ void
findByConversationType_Should_returnregisteredEnquiryProvider_When_requestedTypeIsRegisteredEnquiry() {
this.conversationListProviderRegistry.initializeConversationSuppliers();
@@ -67,10 +74,14 @@ public void findByConversationType_Should_throwNPE_When_registryIsNotInitialized
assertThat(resultProvider.getClass(), is(RegisteredEnquiryConversationListProvider.class));
}
- @Test(expected = NoSuchElementException.class)
- public void findByConversationType_Should_throwNoSuchElementException_When_requestedTypeIsNull() {
- this.conversationListProviderRegistry.initializeConversationSuppliers();
+ @Test
+ void findByConversationType_Should_throwNoSuchElementException_When_requestedTypeIsNull() {
+ assertThrows(
+ NoSuchElementException.class,
+ () -> {
+ this.conversationListProviderRegistry.initializeConversationSuppliers();
- this.conversationListProviderRegistry.findByConversationType(null);
+ this.conversationListProviderRegistry.findByConversationType(null);
+ });
}
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/conversation/service1/user/anonymous/AnonymousUserCreatorServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/conversation/service1/user/anonymous/AnonymousUserCreatorServiceTest.java
index b72319e3b..0f4cdbbb4 100644
--- a/src/test/java/de/caritas/cob/userservice/api/conversation/service1/user/anonymous/AnonymousUserCreatorServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/conversation/service1/user/anonymous/AnonymousUserCreatorServiceTest.java
@@ -30,16 +30,16 @@
import de.caritas.cob.userservice.api.service.user.UserService;
import java.util.Optional;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
-import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
-@RunWith(SpringRunner.class)
-public class AnonymousUserCreatorServiceTest {
+@ExtendWith(SpringExtension.class)
+class AnonymousUserCreatorServiceTest {
@InjectMocks private AnonymousUserCreatorService anonymousUserCreatorService;
@Mock private KeycloakService keycloakService;
@@ -54,42 +54,50 @@ public class AnonymousUserCreatorServiceTest {
EasyRandom easyRandom = new EasyRandom();
- @Test(expected = InternalServerErrorException.class)
- public void
+ @Test
+ void
createAnonymousUser_Should_ThrowInternalServerErrorExceptionAndPerformRollback_When_KeycloakLoginFails() {
- KeycloakCreateUserResponseDTO responseDTO =
- easyRandom.nextObject(KeycloakCreateUserResponseDTO.class);
- when(keycloakService.createKeycloakUser(any())).thenReturn(responseDTO);
- when(keycloakService.loginUser(anyString(), anyString()))
- .thenThrow(new BadRequestException(ERROR));
-
- anonymousUserCreatorService.createAnonymousUser(USER_DTO_SUCHT);
-
- verifyNoInteractions(rollbackFacade);
- verifyNoInteractions(rocketChatService);
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ KeycloakCreateUserResponseDTO responseDTO =
+ easyRandom.nextObject(KeycloakCreateUserResponseDTO.class);
+ when(keycloakService.createKeycloakUser(any())).thenReturn(responseDTO);
+ when(keycloakService.loginUser(anyString(), anyString()))
+ .thenThrow(new BadRequestException(ERROR));
+
+ anonymousUserCreatorService.createAnonymousUser(USER_DTO_SUCHT);
+
+ verifyNoInteractions(rollbackFacade);
+ verifyNoInteractions(rocketChatService);
+ });
}
- @Test(expected = InternalServerErrorException.class)
- public void
+ @Test
+ void
createAnonymousUser_Should_ThrowInternalServerErrorExceptionAndPerformRollback_When_RocketChatLoginFails()
throws RocketChatLoginException {
- KeycloakCreateUserResponseDTO responseDTO =
- easyRandom.nextObject(KeycloakCreateUserResponseDTO.class);
- when(keycloakService.createKeycloakUser(any())).thenReturn(responseDTO);
- RocketChatLoginException exception = easyRandom.nextObject(RocketChatLoginException.class);
- when(rocketChatService.loginUserFirstTime(
- USER_DTO_SUCHT.getUsername(), USER_DTO_SUCHT.getPassword()))
- .thenThrow(exception);
-
- anonymousUserCreatorService.createAnonymousUser(USER_DTO_SUCHT);
-
- verifyNoInteractions(rollbackFacade);
- verifyNoInteractions(rocketChatService);
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ KeycloakCreateUserResponseDTO responseDTO =
+ easyRandom.nextObject(KeycloakCreateUserResponseDTO.class);
+ when(keycloakService.createKeycloakUser(any())).thenReturn(responseDTO);
+ RocketChatLoginException exception =
+ easyRandom.nextObject(RocketChatLoginException.class);
+ when(rocketChatService.loginUserFirstTime(
+ USER_DTO_SUCHT.getUsername(), USER_DTO_SUCHT.getPassword()))
+ .thenThrow(exception);
+
+ anonymousUserCreatorService.createAnonymousUser(USER_DTO_SUCHT);
+
+ verifyNoInteractions(rollbackFacade);
+ verifyNoInteractions(rocketChatService);
+ });
}
@Test
- public void createAnonymousUser_Should_ReturnAnonymousUserCredentials()
- throws RocketChatLoginException {
+ void createAnonymousUser_Should_ReturnAnonymousUserCredentials() throws RocketChatLoginException {
KeycloakCreateUserResponseDTO responseDTO =
easyRandom.nextObject(KeycloakCreateUserResponseDTO.class);
when(keycloakService.createKeycloakUser(any())).thenReturn(responseDTO);
@@ -118,7 +126,7 @@ public void createAnonymousUser_Should_ReturnAnonymousUserCredentials()
}
@Test
- public void
+ void
createAnonymousUser_Should_throwInternalServerError_When_userToUpdateRocketChatIdDoesNotExist()
throws RocketChatLoginException {
KeycloakCreateUserResponseDTO responseDTO =
diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/CreateChatV1FacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/CreateChatV1FacadeTest.java
index 1a71be880..578874034 100644
--- a/src/test/java/de/caritas/cob/userservice/api/facade/CreateChatV1FacadeTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/facade/CreateChatV1FacadeTest.java
@@ -10,7 +10,8 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.RC_GROUP_ID;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doThrow;
@@ -36,18 +37,18 @@
import de.caritas.cob.userservice.api.service.agency.AgencyService;
import java.time.LocalDateTime;
import java.util.Optional;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InOrder;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.Spy;
import org.slf4j.Logger;
-import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
-@RunWith(SpringRunner.class)
+@ExtendWith(SpringExtension.class)
public class CreateChatV1FacadeTest {
@InjectMocks private CreateChatFacade createChatFacade;
@@ -74,7 +75,7 @@ public class CreateChatV1FacadeTest {
@Mock private Logger logger;
- @Before
+ @BeforeEach
public void setup() {
when(chat.getId()).thenReturn(CHAT_ID);
when(chat.getConsultingTypeId()).thenReturn(15);
@@ -83,11 +84,15 @@ public void setup() {
setInternalState(LogService.class, "LOGGER", logger);
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void createChatV1_Should_ThrowInternalServerErrorException_When_ConsultantHasNoAgency() {
- createChatFacade.createChatV1(CHAT_DTO, consultant);
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ createChatFacade.createChatV1(CHAT_DTO, consultant);
- verify(consultant, atLeastOnce()).getConsultantAgencies();
+ verify(consultant, atLeastOnce()).getConsultantAgencies();
+ });
}
@Test
@@ -150,124 +155,152 @@ public void createChatV1_Should_SaveChatGroupId() throws RocketChatCreateGroupEx
inOrder.verify(chatService, times(1)).saveChat(chat);
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
createChatV1_Should_ThrowInternalServerErrorExceptionAndDoRollback_When_RocketChatGroupCouldNotBeCreated()
throws Exception {
- when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET);
- when(rocketChatService.createPrivateGroupWithSystemUser(Mockito.any()))
- .thenThrow(new RocketChatCreateGroupException(ERROR));
- when(chatService.saveChat(Mockito.any())).thenReturn(chat);
- when(chatService.saveChatAgencyRelation(Mockito.any())).thenReturn(chatAgency);
-
- createChatFacade.createChatV1(CHAT_DTO, consultant);
-
- verify(chatService, times(1)).deleteChat(chat);
- verify(rocketChatService, never()).deleteGroupAsSystemUser(Mockito.any());
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET);
+ when(rocketChatService.createPrivateGroupWithSystemUser(Mockito.any()))
+ .thenThrow(new RocketChatCreateGroupException(ERROR));
+ when(chatService.saveChat(Mockito.any())).thenReturn(chat);
+ when(chatService.saveChatAgencyRelation(Mockito.any())).thenReturn(chatAgency);
+
+ createChatFacade.createChatV1(CHAT_DTO, consultant);
+
+ verify(chatService, times(1)).deleteChat(chat);
+ verify(rocketChatService, never()).deleteGroupAsSystemUser(Mockito.any());
+ });
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
createChatV1_Should_ThrowInternalServerErrorExceptionAndRollback_When_RocketChatGroupIsNotPresent()
throws Exception {
- when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET);
- when(rocketChatService.createPrivateGroupWithSystemUser(GROUP_CHAT_NAME))
- .thenReturn(Optional.empty());
- when(chatService.saveChat(Mockito.any())).thenReturn(chat);
- when(chatService.saveChatAgencyRelation(Mockito.any())).thenReturn(chatAgency);
-
- createChatFacade.createChatV1(CHAT_DTO, consultant);
-
- verify(chatService, times(1)).deleteChat(chat);
- verify(rocketChatService, never()).deleteGroupAsSystemUser(Mockito.any());
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET);
+ when(rocketChatService.createPrivateGroupWithSystemUser(GROUP_CHAT_NAME))
+ .thenReturn(Optional.empty());
+ when(chatService.saveChat(Mockito.any())).thenReturn(chat);
+ when(chatService.saveChatAgencyRelation(Mockito.any())).thenReturn(chatAgency);
+
+ createChatFacade.createChatV1(CHAT_DTO, consultant);
+
+ verify(chatService, times(1)).deleteChat(chat);
+ verify(rocketChatService, never()).deleteGroupAsSystemUser(Mockito.any());
+ });
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
createChatV1_Should_ThrowInternalServerErrorExceptionAndDoRollback_When_TechnicalUserCouldNotBeAddedToRocketChatGroup()
throws Exception {
- when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET);
- when(rocketChatService.createPrivateGroupWithSystemUser(Mockito.any()))
- .thenReturn(Optional.of(groupResponseDTO));
- when(chatService.saveChat(Mockito.any())).thenReturn(chat);
- when(chatService.saveChatAgencyRelation(Mockito.any())).thenReturn(chatAgency);
- when(groupResponseDTO.getGroup()).thenReturn(groupDTO);
- when(groupDTO.getId()).thenReturn(RC_GROUP_ID);
- doThrow(new RocketChatAddUserToGroupException(ERROR))
- .when(rocketChatService)
- .addTechnicalUserToGroup(RC_GROUP_ID);
-
- createChatFacade.createChatV1(CHAT_DTO, consultant);
-
- verify(chatService, times(1)).deleteChat(chat);
- verify(rocketChatService, times(1)).deleteGroupAsSystemUser(RC_GROUP_ID);
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET);
+ when(rocketChatService.createPrivateGroupWithSystemUser(Mockito.any()))
+ .thenReturn(Optional.of(groupResponseDTO));
+ when(chatService.saveChat(Mockito.any())).thenReturn(chat);
+ when(chatService.saveChatAgencyRelation(Mockito.any())).thenReturn(chatAgency);
+ when(groupResponseDTO.getGroup()).thenReturn(groupDTO);
+ when(groupDTO.getId()).thenReturn(RC_GROUP_ID);
+ doThrow(new RocketChatAddUserToGroupException(ERROR))
+ .when(rocketChatService)
+ .addTechnicalUserToGroup(RC_GROUP_ID);
+
+ createChatFacade.createChatV1(CHAT_DTO, consultant);
+
+ verify(chatService, times(1)).deleteChat(chat);
+ verify(rocketChatService, times(1)).deleteGroupAsSystemUser(RC_GROUP_ID);
+ });
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
createChatV1_Should_ThrowInternalServerErrorExceptionAndDoRollback_When_RocketChatUSerIsNotInitialized()
throws Exception {
- when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET);
- when(rocketChatService.createPrivateGroupWithSystemUser(Mockito.any()))
- .thenReturn(Optional.of(groupResponseDTO));
- when(chatService.saveChat(Mockito.any())).thenReturn(chat);
- when(chatService.saveChatAgencyRelation(Mockito.any())).thenReturn(chatAgency);
- when(groupResponseDTO.getGroup()).thenReturn(groupDTO);
- when(groupDTO.getId()).thenReturn(RC_GROUP_ID);
- doThrow(new RocketChatUserNotInitializedException(ERROR))
- .when(rocketChatService)
- .addTechnicalUserToGroup(RC_GROUP_ID);
-
- createChatFacade.createChatV1(CHAT_DTO, consultant);
-
- verify(chatService, times(1)).deleteChat(chat);
- verify(rocketChatService, times(1)).deleteGroupAsSystemUser(RC_GROUP_ID);
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET);
+ when(rocketChatService.createPrivateGroupWithSystemUser(Mockito.any()))
+ .thenReturn(Optional.of(groupResponseDTO));
+ when(chatService.saveChat(Mockito.any())).thenReturn(chat);
+ when(chatService.saveChatAgencyRelation(Mockito.any())).thenReturn(chatAgency);
+ when(groupResponseDTO.getGroup()).thenReturn(groupDTO);
+ when(groupDTO.getId()).thenReturn(RC_GROUP_ID);
+ doThrow(new RocketChatUserNotInitializedException(ERROR))
+ .when(rocketChatService)
+ .addTechnicalUserToGroup(RC_GROUP_ID);
+
+ createChatFacade.createChatV1(CHAT_DTO, consultant);
+
+ verify(chatService, times(1)).deleteChat(chat);
+ verify(rocketChatService, times(1)).deleteGroupAsSystemUser(RC_GROUP_ID);
+ });
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
createChatV1_Should_ThrowInternalServerErrorExceptionAndDoRollback_When_ChatAgencyRelationCouldNotBeSaved()
throws Exception {
- when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET);
- when(rocketChatService.createPrivateGroupWithSystemUser(Mockito.any()))
- .thenReturn(Optional.of(groupResponseDTO));
- when(chatService.saveChat(Mockito.any())).thenReturn(chat);
- when(chatService.saveChatAgencyRelation(Mockito.any()))
- .thenThrow(new InternalServerErrorException(""));
-
- createChatFacade.createChatV1(CHAT_DTO, consultant);
-
- verify(chatService, times(1)).deleteChat(chat);
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET);
+ when(rocketChatService.createPrivateGroupWithSystemUser(Mockito.any()))
+ .thenReturn(Optional.of(groupResponseDTO));
+ when(chatService.saveChat(Mockito.any())).thenReturn(chat);
+ when(chatService.saveChatAgencyRelation(Mockito.any()))
+ .thenThrow(new InternalServerErrorException(""));
+
+ createChatFacade.createChatV1(CHAT_DTO, consultant);
+
+ verify(chatService, times(1)).deleteChat(chat);
+ });
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
createChatV1_Should_ThrowInternalServerErrorExceptionAndDoRollback_When_ChatCouldNotBeSavedWithGroupId()
throws Exception {
- when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET);
- when(chatService.saveChat(Mockito.any()))
- .thenReturn(chat)
- .thenThrow(new InternalServerErrorException(""));
- when(rocketChatService.createPrivateGroupWithSystemUser(Mockito.any()))
- .thenReturn(Optional.of(groupResponseDTO));
- when(groupResponseDTO.getGroup()).thenReturn(groupDTO);
- when(groupDTO.getId()).thenReturn(RC_GROUP_ID);
- when(chatService.saveChatAgencyRelation(Mockito.any())).thenReturn(chatAgency);
-
- createChatFacade.createChatV1(CHAT_DTO, consultant);
-
- verify(chatService, times(1)).deleteChat(chat);
- verify(rocketChatService, times(1)).deleteGroupAsSystemUser(RC_GROUP_ID);
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET);
+ when(chatService.saveChat(Mockito.any()))
+ .thenReturn(chat)
+ .thenThrow(new InternalServerErrorException(""));
+ when(rocketChatService.createPrivateGroupWithSystemUser(Mockito.any()))
+ .thenReturn(Optional.of(groupResponseDTO));
+ when(groupResponseDTO.getGroup()).thenReturn(groupDTO);
+ when(groupDTO.getId()).thenReturn(RC_GROUP_ID);
+ when(chatService.saveChatAgencyRelation(Mockito.any())).thenReturn(chatAgency);
+
+ createChatFacade.createChatV1(CHAT_DTO, consultant);
+
+ verify(chatService, times(1)).deleteChat(chat);
+ verify(rocketChatService, times(1)).deleteGroupAsSystemUser(RC_GROUP_ID);
+ });
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void createChatV1_Should_ThrowInternalServerErrorException_When_ChatCouldNotBeSaved() {
- when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET);
- when(chatService.saveChat(Mockito.any())).thenThrow(new InternalServerErrorException(""));
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET);
+ when(chatService.saveChat(Mockito.any())).thenThrow(new InternalServerErrorException(""));
- createChatFacade.createChatV1(CHAT_DTO, consultant);
+ createChatFacade.createChatV1(CHAT_DTO, consultant);
- verify(chatService, never()).deleteChat(chat);
- verify(rocketChatService, never()).deleteGroupAsSystemUser(RC_GROUP_ID);
+ verify(chatService, never()).deleteChat(chat);
+ verify(rocketChatService, never()).deleteGroupAsSystemUser(RC_GROUP_ID);
+ });
}
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/CreateChatV2FacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/CreateChatV2FacadeTest.java
index 70ba34b99..7c6e00061 100644
--- a/src/test/java/de/caritas/cob/userservice/api/facade/CreateChatV2FacadeTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/facade/CreateChatV2FacadeTest.java
@@ -13,6 +13,7 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.GROUP_CHAT_NAME;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.RC_GROUP_ID;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.never;
@@ -41,9 +42,9 @@
import java.time.LocalDateTime;
import java.util.Optional;
import java.util.UUID;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.InjectMocks;
@@ -51,9 +52,9 @@
import org.mockito.Mockito;
import org.mockito.Spy;
import org.slf4j.Logger;
-import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
-@RunWith(SpringRunner.class)
+@ExtendWith(SpringExtension.class)
public class CreateChatV2FacadeTest {
@InjectMocks private CreateChatFacade createChatFacade;
@@ -80,7 +81,7 @@ public class CreateChatV2FacadeTest {
@Mock private Logger logger;
- @Before
+ @BeforeEach
public void setup() {
when(chat.getId()).thenReturn(CHAT_ID);
when(chat.getCreateDate()).thenReturn(LocalDateTime.now());
@@ -184,108 +185,132 @@ public void createChatV2_Should_SaveChatGroupId() throws RocketChatCreateGroupEx
inOrder.verify(chatService, times(1)).saveChat(chat);
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
createChatV2_Should_ThrowInternalServerErrorExceptionAndDoRollback_When_RocketChatGroupCouldNotBeCreated()
throws Exception {
- when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET);
- when(rocketChatService.createPrivateGroupWithSystemUser(Mockito.any()))
- .thenThrow(new RocketChatCreateGroupException(ERROR));
- when(chatService.saveChat(Mockito.any())).thenReturn(chat);
- when(chatService.saveChatAgencyRelation(Mockito.any())).thenReturn(chatAgency);
-
- createChatFacade.createChatV2(CHAT_DTO, consultant);
-
- verify(chatService, times(1)).deleteChat(chat);
- verify(rocketChatService, never()).deleteGroupAsSystemUser(Mockito.any());
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET);
+ when(rocketChatService.createPrivateGroupWithSystemUser(Mockito.any()))
+ .thenThrow(new RocketChatCreateGroupException(ERROR));
+ when(chatService.saveChat(Mockito.any())).thenReturn(chat);
+ when(chatService.saveChatAgencyRelation(Mockito.any())).thenReturn(chatAgency);
+
+ createChatFacade.createChatV2(CHAT_DTO, consultant);
+
+ verify(chatService, times(1)).deleteChat(chat);
+ verify(rocketChatService, never()).deleteGroupAsSystemUser(Mockito.any());
+ });
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
createChatV2_Should_ThrowInternalServerErrorExceptionAndRollback_When_RocketChatGroupIsNotPresent()
throws Exception {
- when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET);
- when(rocketChatService.createPrivateGroupWithSystemUser(GROUP_CHAT_NAME))
- .thenReturn(Optional.empty());
- when(chatService.saveChat(Mockito.any())).thenReturn(chat);
- when(chatService.saveChatAgencyRelation(Mockito.any())).thenReturn(chatAgency);
-
- createChatFacade.createChatV2(CHAT_DTO, consultant);
-
- verify(chatService, times(1)).deleteChat(chat);
- verify(rocketChatService, never()).deleteGroupAsSystemUser(Mockito.any());
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET);
+ when(rocketChatService.createPrivateGroupWithSystemUser(GROUP_CHAT_NAME))
+ .thenReturn(Optional.empty());
+ when(chatService.saveChat(Mockito.any())).thenReturn(chat);
+ when(chatService.saveChatAgencyRelation(Mockito.any())).thenReturn(chatAgency);
+
+ createChatFacade.createChatV2(CHAT_DTO, consultant);
+
+ verify(chatService, times(1)).deleteChat(chat);
+ verify(rocketChatService, never()).deleteGroupAsSystemUser(Mockito.any());
+ });
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
createChatV2_Should_ThrowInternalServerErrorExceptionAndDoRollback_When_TechnicalUserCouldNotBeAddedToRocketChatGroup()
throws Exception {
- when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET);
- when(rocketChatService.createPrivateGroupWithSystemUser(Mockito.any()))
- .thenReturn(Optional.of(groupResponseDTO));
- when(chatService.saveChat(Mockito.any())).thenReturn(chat);
- when(chatService.saveChatAgencyRelation(Mockito.any())).thenReturn(chatAgency);
- when(groupResponseDTO.getGroup()).thenReturn(groupDTO);
- when(groupDTO.getId()).thenReturn(RC_GROUP_ID);
- doThrow(new RocketChatAddUserToGroupException(ERROR))
- .when(rocketChatService)
- .addTechnicalUserToGroup(RC_GROUP_ID);
-
- createChatFacade.createChatV2(CHAT_DTO, consultant);
-
- verify(chatService, times(1)).deleteChat(chat);
- verify(rocketChatService, times(1)).deleteGroupAsSystemUser(RC_GROUP_ID);
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET);
+ when(rocketChatService.createPrivateGroupWithSystemUser(Mockito.any()))
+ .thenReturn(Optional.of(groupResponseDTO));
+ when(chatService.saveChat(Mockito.any())).thenReturn(chat);
+ when(chatService.saveChatAgencyRelation(Mockito.any())).thenReturn(chatAgency);
+ when(groupResponseDTO.getGroup()).thenReturn(groupDTO);
+ when(groupDTO.getId()).thenReturn(RC_GROUP_ID);
+ doThrow(new RocketChatAddUserToGroupException(ERROR))
+ .when(rocketChatService)
+ .addTechnicalUserToGroup(RC_GROUP_ID);
+
+ createChatFacade.createChatV2(CHAT_DTO, consultant);
+
+ verify(chatService, times(1)).deleteChat(chat);
+ verify(rocketChatService, times(1)).deleteGroupAsSystemUser(RC_GROUP_ID);
+ });
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
createChatV2_Should_ThrowInternalServerErrorExceptionAndDoRollback_When_RocketChatUserIsNotInitialized()
throws Exception {
- when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET);
- when(rocketChatService.createPrivateGroupWithSystemUser(Mockito.any()))
- .thenReturn(Optional.of(groupResponseDTO));
- when(chatService.saveChat(Mockito.any())).thenReturn(chat);
- when(chatService.saveChatAgencyRelation(Mockito.any())).thenReturn(chatAgency);
- when(groupResponseDTO.getGroup()).thenReturn(groupDTO);
- when(groupDTO.getId()).thenReturn(RC_GROUP_ID);
- doThrow(new RocketChatUserNotInitializedException(ERROR))
- .when(rocketChatService)
- .addTechnicalUserToGroup(RC_GROUP_ID);
-
- createChatFacade.createChatV2(CHAT_DTO, consultant);
-
- verify(chatService, times(1)).deleteChat(chat);
- verify(rocketChatService, times(1)).deleteGroupAsSystemUser(RC_GROUP_ID);
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET);
+ when(rocketChatService.createPrivateGroupWithSystemUser(Mockito.any()))
+ .thenReturn(Optional.of(groupResponseDTO));
+ when(chatService.saveChat(Mockito.any())).thenReturn(chat);
+ when(chatService.saveChatAgencyRelation(Mockito.any())).thenReturn(chatAgency);
+ when(groupResponseDTO.getGroup()).thenReturn(groupDTO);
+ when(groupDTO.getId()).thenReturn(RC_GROUP_ID);
+ doThrow(new RocketChatUserNotInitializedException(ERROR))
+ .when(rocketChatService)
+ .addTechnicalUserToGroup(RC_GROUP_ID);
+
+ createChatFacade.createChatV2(CHAT_DTO, consultant);
+
+ verify(chatService, times(1)).deleteChat(chat);
+ verify(rocketChatService, times(1)).deleteGroupAsSystemUser(RC_GROUP_ID);
+ });
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
createChatV2_Should_ThrowInternalServerErrorExceptionAndDoRollback_WhenChatCouldNotBeSavedWithGroupId()
throws Exception {
- when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET);
- when(chatService.saveChat(Mockito.any()))
- .thenReturn(chat)
- .thenThrow(new InternalServerErrorException(""));
- when(rocketChatService.createPrivateGroupWithSystemUser(Mockito.any()))
- .thenReturn(Optional.of(groupResponseDTO));
- when(groupResponseDTO.getGroup()).thenReturn(groupDTO);
- when(groupDTO.getId()).thenReturn(RC_GROUP_ID);
- when(chatService.saveChatAgencyRelation(Mockito.any())).thenReturn(chatAgency);
-
- createChatFacade.createChatV2(CHAT_DTO, consultant);
-
- verify(chatService, times(1)).deleteChat(chat);
- verify(rocketChatService, times(1)).deleteGroupAsSystemUser(RC_GROUP_ID);
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET);
+ when(chatService.saveChat(Mockito.any()))
+ .thenReturn(chat)
+ .thenThrow(new InternalServerErrorException(""));
+ when(rocketChatService.createPrivateGroupWithSystemUser(Mockito.any()))
+ .thenReturn(Optional.of(groupResponseDTO));
+ when(groupResponseDTO.getGroup()).thenReturn(groupDTO);
+ when(groupDTO.getId()).thenReturn(RC_GROUP_ID);
+ when(chatService.saveChatAgencyRelation(Mockito.any())).thenReturn(chatAgency);
+
+ createChatFacade.createChatV2(CHAT_DTO, consultant);
+
+ verify(chatService, times(1)).deleteChat(chat);
+ verify(rocketChatService, times(1)).deleteGroupAsSystemUser(RC_GROUP_ID);
+ });
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void createChatV2_Should_ThrowInternalServerErrorException_WhenChatCouldNotBeSaved() {
- when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET);
- when(chatService.saveChat(Mockito.any())).thenThrow(new InternalServerErrorException(""));
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET);
+ when(chatService.saveChat(Mockito.any())).thenThrow(new InternalServerErrorException(""));
- createChatFacade.createChatV2(CHAT_DTO, consultant);
+ createChatFacade.createChatV2(CHAT_DTO, consultant);
- verify(chatService, never()).deleteChat(chat);
- verify(rocketChatService, never()).deleteGroupAsSystemUser(RC_GROUP_ID);
+ verify(chatService, never()).deleteChat(chat);
+ verify(rocketChatService, never()).deleteGroupAsSystemUser(RC_GROUP_ID);
+ });
}
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/CreateEnquiryMessageFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/CreateEnquiryMessageFacadeTest.java
index f03f6c785..a7bab1c37 100644
--- a/src/test/java/de/caritas/cob/userservice/api/facade/CreateEnquiryMessageFacadeTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/facade/CreateEnquiryMessageFacadeTest.java
@@ -31,8 +31,7 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USER_INFO_RESPONSE_DTO_2;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
@@ -93,19 +92,21 @@
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import org.jeasy.random.EasyRandom;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
import org.slf4j.Logger;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
-@RunWith(MockitoJUnitRunner.class)
-public class CreateEnquiryMessageFacadeTest {
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = org.mockito.quality.Strictness.LENIENT)
+class CreateEnquiryMessageFacadeTest {
private final GroupDTO GROUP_DTO =
new GroupDTO(
@@ -252,8 +253,8 @@ public class CreateEnquiryMessageFacadeTest {
private GroupDTO groupDTO;
private RocketChatCredentials rocketChatCredentials;
- @Before
- public void setUp() throws NoSuchFieldException, SecurityException {
+ @BeforeEach
+ void setUp() throws NoSuchFieldException, SecurityException {
setField(
createEnquiryMessageFacade,
FIELD_NAME_ROCKET_CHAT_SYSTEM_USER_ID,
@@ -303,7 +304,7 @@ public void setUp() throws NoSuchFieldException, SecurityException {
}
@Test
- public void createEnquiryMessage_ShouldNot_ThrowException_When_Successful() throws Exception {
+ void createEnquiryMessage_ShouldNot_ThrowException_When_Successful() throws Exception {
session.setUser(user);
session.setConsultingTypeId(0);
@@ -357,7 +358,7 @@ public void createEnquiryMessage_ShouldNot_ThrowException_When_Successful() thro
}
@Test
- public void createEnquiryMessage_Should_SendDirectEnquiryEmail_When_ConsultantDirectlySet()
+ void createEnquiryMessage_Should_SendDirectEnquiryEmail_When_ConsultantDirectlySet()
throws Exception {
session.setUser(user);
session.setConsultingTypeId(0);
@@ -400,171 +401,198 @@ public void createEnquiryMessage_Should_SendDirectEnquiryEmail_When_ConsultantDi
resetRequestAttributes();
}
- @Test(expected = ConflictException.class)
- public void createEnquiryMessage_Should_ThrowConflictException_When_EnquiryMessageAlreadySaved() {
-
- when(userHelper.doUsernamesMatch(Mockito.anyString(), Mockito.anyString())).thenReturn(true);
- when(sessionService.getSession(SESSION_ID))
- .thenReturn(Optional.of(SESSION_WITH_ENQUIRY_MESSAGE));
- when(rocketChatService.getUserInfo(RC_USER_ID)).thenReturn(USER_INFO_RESPONSE_DTO);
- createEnquiryMessageFacade.createEnquiryMessage(
- new EnquiryData(USER, SESSION_ID, MESSAGE, null, RC_CREDENTIALS));
- resetRequestAttributes();
+ @Test
+ void createEnquiryMessage_Should_ThrowConflictException_When_EnquiryMessageAlreadySaved() {
+ assertThrows(
+ ConflictException.class,
+ () -> {
+ when(userHelper.doUsernamesMatch(Mockito.anyString(), Mockito.anyString()))
+ .thenReturn(true);
+ when(sessionService.getSession(SESSION_ID))
+ .thenReturn(Optional.of(SESSION_WITH_ENQUIRY_MESSAGE));
+ when(rocketChatService.getUserInfo(RC_USER_ID)).thenReturn(USER_INFO_RESPONSE_DTO);
+ createEnquiryMessageFacade.createEnquiryMessage(
+ new EnquiryData(USER, SESSION_ID, MESSAGE, null, RC_CREDENTIALS));
+ resetRequestAttributes();
+ });
}
- @Test(expected = CreateEnquiryMessageException.class)
- public void
+ @Test
+ void
createEnquiryMessage_Should_ThrowCreateEnquiryMessageException_When_SessionNotFoundForUser() {
-
- when(rocketChatService.getUserInfo(RC_USER_ID)).thenReturn(USER_INFO_RESPONSE_DTO);
- when(userHelper.doUsernamesMatch(Mockito.anyString(), Mockito.anyString())).thenReturn(true);
- when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.empty());
- createEnquiryMessageFacade.createEnquiryMessage(
- new EnquiryData(USER, SESSION_ID, MESSAGE, null, RC_CREDENTIALS));
- resetRequestAttributes();
+ assertThrows(
+ CreateEnquiryMessageException.class,
+ () -> {
+ when(rocketChatService.getUserInfo(RC_USER_ID)).thenReturn(USER_INFO_RESPONSE_DTO);
+ when(userHelper.doUsernamesMatch(Mockito.anyString(), Mockito.anyString()))
+ .thenReturn(true);
+ when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.empty());
+ createEnquiryMessageFacade.createEnquiryMessage(
+ new EnquiryData(USER, SESSION_ID, MESSAGE, null, RC_CREDENTIALS));
+ resetRequestAttributes();
+ });
}
- @Test(expected = CreateEnquiryMessageException.class)
- public void
- createEnquiryMessage_Should_ThrowCreateEnquiryMessageException_When_SessionIsAnonymous() {
- Session anonymousSession = new EasyRandom().nextObject(Session.class);
- anonymousSession.setRegistrationType(ANONYMOUS);
- anonymousSession.getUser().setUserId(USER.getUserId());
- when(rocketChatService.getUserInfo(RC_USER_ID)).thenReturn(USER_INFO_RESPONSE_DTO);
- when(userHelper.doUsernamesMatch(Mockito.anyString(), Mockito.anyString())).thenReturn(true);
- when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.of(anonymousSession));
-
- createEnquiryMessageFacade.createEnquiryMessage(
- new EnquiryData(USER, SESSION_ID, MESSAGE, null, RC_CREDENTIALS));
- resetRequestAttributes();
+ @Test
+ void createEnquiryMessage_Should_ThrowCreateEnquiryMessageException_When_SessionIsAnonymous() {
+ assertThrows(
+ CreateEnquiryMessageException.class,
+ () -> {
+ Session anonymousSession = new EasyRandom().nextObject(Session.class);
+ anonymousSession.setRegistrationType(ANONYMOUS);
+ anonymousSession.getUser().setUserId(USER.getUserId());
+ when(rocketChatService.getUserInfo(RC_USER_ID)).thenReturn(USER_INFO_RESPONSE_DTO);
+ when(userHelper.doUsernamesMatch(Mockito.anyString(), Mockito.anyString()))
+ .thenReturn(true);
+ when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.of(anonymousSession));
+
+ createEnquiryMessageFacade.createEnquiryMessage(
+ new EnquiryData(USER, SESSION_ID, MESSAGE, null, RC_CREDENTIALS));
+ resetRequestAttributes();
+ });
}
- @Test(expected = InternalServerErrorException.class)
- public void
- createEnquiryMessage_Should_ThrowInternalServerErrorException_When_GetSessionCallFails() {
-
- when(userHelper.doUsernamesMatch(Mockito.anyString(), Mockito.anyString())).thenReturn(true);
- when(rocketChatService.getUserInfo(RC_USER_ID)).thenReturn(USER_INFO_RESPONSE_DTO);
- when(sessionService.getSession(SESSION_ID))
- .thenThrow(new InternalServerErrorException(MESSAGE))
- .thenReturn(Optional.of(SESSION_WITHOUT_CONSULTANT));
- createEnquiryMessageFacade.createEnquiryMessage(
- new EnquiryData(USER, SESSION_ID, MESSAGE, null, RC_CREDENTIALS));
- resetRequestAttributes();
+ @Test
+ void createEnquiryMessage_Should_ThrowInternalServerErrorException_When_GetSessionCallFails() {
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(userHelper.doUsernamesMatch(Mockito.anyString(), Mockito.anyString()))
+ .thenReturn(true);
+ when(rocketChatService.getUserInfo(RC_USER_ID)).thenReturn(USER_INFO_RESPONSE_DTO);
+ when(sessionService.getSession(SESSION_ID))
+ .thenThrow(new InternalServerErrorException(MESSAGE))
+ .thenReturn(Optional.of(SESSION_WITHOUT_CONSULTANT));
+ createEnquiryMessageFacade.createEnquiryMessage(
+ new EnquiryData(USER, SESSION_ID, MESSAGE, null, RC_CREDENTIALS));
+ resetRequestAttributes();
+ });
}
- @Test(expected = InternalServerErrorException.class)
- public void
+ @Test
+ void
createEnquiryMessage_Should_ThrowInternalServerErrorException_When_CreationOfRocketChatGroupFailsWithAnException()
throws RocketChatCreateGroupException {
-
- session.setUser(user);
- session.setConsultingTypeId(0);
- session.setConsultant(null);
- session.setEnquiryMessageDate(null);
- rocketChatUserDTO.setUsername(USERNAME);
- userInfoResponseDTO.setUser(rocketChatUserDTO);
- rocketChatCredentials.setRocketChatUserId(RC_USER_ID);
- rocketChatCredentials.setRocketChatUsername(RC_USERNAME);
-
- when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.of(session));
- when(rocketChatService.getUserInfo(RC_USER_ID)).thenReturn(userInfoResponseDTO);
- when(userHelper.doUsernamesMatch(anyString(), anyString())).thenReturn(true);
- when(rocketChatRoomNameGenerator.generateGroupName(any(Session.class)))
- .thenReturn(session.getId().toString());
- when(rocketChatService.createPrivateGroup(anyString(), any()))
- .thenThrow(new RocketChatCreateGroupException(ERROR));
-
- createEnquiryMessageFacade.createEnquiryMessage(
- new EnquiryData(user, SESSION_ID, MESSAGE, null, rocketChatCredentials));
- resetRequestAttributes();
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ session.setUser(user);
+ session.setConsultingTypeId(0);
+ session.setConsultant(null);
+ session.setEnquiryMessageDate(null);
+ rocketChatUserDTO.setUsername(USERNAME);
+ userInfoResponseDTO.setUser(rocketChatUserDTO);
+ rocketChatCredentials.setRocketChatUserId(RC_USER_ID);
+ rocketChatCredentials.setRocketChatUsername(RC_USERNAME);
+
+ when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.of(session));
+ when(rocketChatService.getUserInfo(RC_USER_ID)).thenReturn(userInfoResponseDTO);
+ when(userHelper.doUsernamesMatch(anyString(), anyString())).thenReturn(true);
+ when(rocketChatRoomNameGenerator.generateGroupName(any(Session.class)))
+ .thenReturn(session.getId().toString());
+ when(rocketChatService.createPrivateGroup(anyString(), any()))
+ .thenThrow(new RocketChatCreateGroupException(ERROR));
+
+ createEnquiryMessageFacade.createEnquiryMessage(
+ new EnquiryData(user, SESSION_ID, MESSAGE, null, rocketChatCredentials));
+ resetRequestAttributes();
+ });
}
- @Test(expected = InternalServerErrorException.class)
- public void
+ @Test
+ void
createEnquiryMessage_Should_ThrowInternalServerErrorException_When_PostMessageFailsWithAnException() {
-
- session.setUser(user);
- session.setConsultingTypeId(0);
- session.setConsultant(null);
- session.setEnquiryMessageDate(null);
- rocketChatUserDTO.setUsername(USERNAME);
- userInfoResponseDTO.setUser(rocketChatUserDTO);
- groupDTO.setId(RC_GROUP_ID);
- groupResponseDTO.setSuccess(true);
- groupResponseDTO.setGroup(groupDTO);
- rocketChatCredentials.setRocketChatUserId(RC_USER_ID);
- rocketChatCredentials.setRocketChatUsername(RC_USERNAME);
-
- when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.of(session));
- when(consultingTypeManager.getConsultingTypeSettings(session.getConsultingTypeId()))
- .thenReturn(extendedConsultingTypeResponseDTO);
- when(rocketChatService.getUserInfo(RC_USER_ID)).thenReturn(userInfoResponseDTO);
- when(userHelper.doUsernamesMatch(anyString(), anyString())).thenReturn(true);
-
- createEnquiryMessageFacade.createEnquiryMessage(
- new EnquiryData(user, SESSION_ID, MESSAGE, null, rocketChatCredentials));
- resetRequestAttributes();
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ session.setUser(user);
+ session.setConsultingTypeId(0);
+ session.setConsultant(null);
+ session.setEnquiryMessageDate(null);
+ rocketChatUserDTO.setUsername(USERNAME);
+ userInfoResponseDTO.setUser(rocketChatUserDTO);
+ groupDTO.setId(RC_GROUP_ID);
+ groupResponseDTO.setSuccess(true);
+ groupResponseDTO.setGroup(groupDTO);
+ rocketChatCredentials.setRocketChatUserId(RC_USER_ID);
+ rocketChatCredentials.setRocketChatUsername(RC_USERNAME);
+
+ when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.of(session));
+ when(consultingTypeManager.getConsultingTypeSettings(session.getConsultingTypeId()))
+ .thenReturn(extendedConsultingTypeResponseDTO);
+ when(rocketChatService.getUserInfo(RC_USER_ID)).thenReturn(userInfoResponseDTO);
+ when(userHelper.doUsernamesMatch(anyString(), anyString())).thenReturn(true);
+
+ createEnquiryMessageFacade.createEnquiryMessage(
+ new EnquiryData(user, SESSION_ID, MESSAGE, null, rocketChatCredentials));
+ resetRequestAttributes();
+ });
}
- @Test(expected = InternalServerErrorException.class)
- public void
+ @Test
+ void
createEnquiryMessage_Should_ThrowInternalServerErrorException_When_ConsultantsOfAgencyCanNotBeReadFromDB() {
-
- session.setUser(user);
- session.setConsultingTypeId(0);
- session.setConsultant(null);
- rocketChatUserDTO.setUsername(USERNAME);
- userInfoResponseDTO.setUser(rocketChatUserDTO);
- rocketChatCredentials.setRocketChatUserId(RC_USER_ID);
- rocketChatCredentials.setRocketChatUsername(RC_USERNAME);
-
- when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.of(session));
- when(rocketChatService.getUserInfo(RC_USER_ID)).thenReturn(userInfoResponseDTO);
- when(userHelper.doUsernamesMatch(anyString(), anyString())).thenReturn(true);
-
- createEnquiryMessageFacade.createEnquiryMessage(
- new EnquiryData(user, SESSION_ID, MESSAGE, null, rocketChatCredentials));
- verify(rocketChatService, atLeast(1)).rollbackGroup(RC_GROUP_ID, rocketChatCredentials);
- resetRequestAttributes();
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ session.setUser(user);
+ session.setConsultingTypeId(0);
+ session.setConsultant(null);
+ rocketChatUserDTO.setUsername(USERNAME);
+ userInfoResponseDTO.setUser(rocketChatUserDTO);
+ rocketChatCredentials.setRocketChatUserId(RC_USER_ID);
+ rocketChatCredentials.setRocketChatUsername(RC_USERNAME);
+
+ when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.of(session));
+ when(rocketChatService.getUserInfo(RC_USER_ID)).thenReturn(userInfoResponseDTO);
+ when(userHelper.doUsernamesMatch(anyString(), anyString())).thenReturn(true);
+
+ createEnquiryMessageFacade.createEnquiryMessage(
+ new EnquiryData(user, SESSION_ID, MESSAGE, null, rocketChatCredentials));
+ verify(rocketChatService, atLeast(1)).rollbackGroup(RC_GROUP_ID, rocketChatCredentials);
+ resetRequestAttributes();
+ });
}
- @Test(expected = InternalServerErrorException.class)
- public void
+ @Test
+ void
createEnquiryMessage_Should_ThrowInternalServerErrorException_When_AddConsultantToRocketChatGroupFails()
throws Exception {
-
- session.setUser(user);
- session.setConsultingTypeId(0);
- session.setConsultant(null);
- session.setEnquiryMessageDate(null);
- rocketChatUserDTO.setUsername(USERNAME);
- userInfoResponseDTO.setUser(rocketChatUserDTO);
- groupDTO.setId(RC_GROUP_ID);
- groupResponseDTO.setSuccess(true);
- groupResponseDTO.setGroup(groupDTO);
- rocketChatCredentials.setRocketChatUserId(RC_USER_ID);
- rocketChatCredentials.setRocketChatUsername(RC_USERNAME);
-
- when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.of(session));
- when(rocketChatService.getUserInfo(RC_USER_ID)).thenReturn(userInfoResponseDTO);
- when(userHelper.doUsernamesMatch(anyString(), anyString())).thenReturn(true);
- when(rocketChatService.createPrivateGroup(anyString(), any()))
- .thenReturn(Optional.of(groupResponseDTO));
- when(rocketChatRoomNameGenerator.generateGroupName(any(Session.class)))
- .thenReturn(session.getId().toString());
-
- Mockito.doThrow(new RocketChatAddUserToGroupException(MESSAGE))
- .when(rocketChatService)
- .addUserToGroup(anyString(), anyString());
-
- createEnquiryMessageFacade.createEnquiryMessage(
- new EnquiryData(user, SESSION_ID, MESSAGE, null, rocketChatCredentials));
- resetRequestAttributes();
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ session.setUser(user);
+ session.setConsultingTypeId(0);
+ session.setConsultant(null);
+ session.setEnquiryMessageDate(null);
+ rocketChatUserDTO.setUsername(USERNAME);
+ userInfoResponseDTO.setUser(rocketChatUserDTO);
+ groupDTO.setId(RC_GROUP_ID);
+ groupResponseDTO.setSuccess(true);
+ groupResponseDTO.setGroup(groupDTO);
+ rocketChatCredentials.setRocketChatUserId(RC_USER_ID);
+ rocketChatCredentials.setRocketChatUsername(RC_USERNAME);
+
+ when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.of(session));
+ when(rocketChatService.getUserInfo(RC_USER_ID)).thenReturn(userInfoResponseDTO);
+ when(userHelper.doUsernamesMatch(anyString(), anyString())).thenReturn(true);
+ when(rocketChatService.createPrivateGroup(anyString(), any()))
+ .thenReturn(Optional.of(groupResponseDTO));
+ when(rocketChatRoomNameGenerator.generateGroupName(any(Session.class)))
+ .thenReturn(session.getId().toString());
+
+ Mockito.doThrow(new RocketChatAddUserToGroupException(MESSAGE))
+ .when(rocketChatService)
+ .addUserToGroup(anyString(), anyString());
+
+ createEnquiryMessageFacade.createEnquiryMessage(
+ new EnquiryData(user, SESSION_ID, MESSAGE, null, rocketChatCredentials));
+ resetRequestAttributes();
+ });
}
@Test
- public void createEnquiryMessage_Should_DeleteRcGroup_When_PostMessageFails() throws Exception {
+ void createEnquiryMessage_Should_DeleteRcGroup_When_PostMessageFails() throws Exception {
when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.of(SESSION_WITHOUT_CONSULTANT));
when(consultingTypeManager.getConsultingTypeSettings(
@@ -593,7 +621,7 @@ public void createEnquiryMessage_Should_DeleteRcGroup_When_PostMessageFails() th
}
@Test
- public void createEnquiryMessage_Should_DeleteRcGroup_When_AddConsultantToRocketChatGroupFails()
+ void createEnquiryMessage_Should_DeleteRcGroup_When_AddConsultantToRocketChatGroupFails()
throws Exception {
when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.of(SESSION_WITHOUT_CONSULTANT));
@@ -623,19 +651,22 @@ public void createEnquiryMessage_Should_DeleteRcGroup_When_AddConsultantToRocket
resetRequestAttributes();
}
- @Test(expected = CreateEnquiryMessageException.class)
- public void
+ @Test
+ void
createEnquiryMessage_Should_ThrowCreateEnquiryMessageException_When_KeycloakAndRocketChatUsersDontMatch() {
-
- when(rocketChatService.getUserInfo(RC_USER_ID)).thenReturn(USER_INFO_RESPONSE_DTO_2);
-
- createEnquiryMessageFacade.createEnquiryMessage(
- new EnquiryData(USER, SESSION_ID, MESSAGE, null, RC_CREDENTIALS));
- resetRequestAttributes();
+ assertThrows(
+ CreateEnquiryMessageException.class,
+ () -> {
+ when(rocketChatService.getUserInfo(RC_USER_ID)).thenReturn(USER_INFO_RESPONSE_DTO_2);
+
+ createEnquiryMessageFacade.createEnquiryMessage(
+ new EnquiryData(USER, SESSION_ID, MESSAGE, null, RC_CREDENTIALS));
+ resetRequestAttributes();
+ });
}
@Test
- public void createEnquiryMessage_Should_UpdateCorrectSessionInformation_When_Successful()
+ void createEnquiryMessage_Should_UpdateCorrectSessionInformation_When_Successful()
throws Exception {
session.setUser(user);
@@ -678,138 +709,150 @@ public void createEnquiryMessage_Should_UpdateCorrectSessionInformation_When_Suc
resetRequestAttributes();
}
- @Test(expected = InternalServerErrorException.class)
- public void
+ @Test
+ void
createEnquiryMessage_Should_ThrowInternalServerErrorException_When_CreatePrivateGroupWithSystemUserFails()
throws RocketChatCreateGroupException {
-
- session.setUser(user);
- session.setConsultingTypeId(0);
- session.setConsultant(null);
- extendedConsultingTypeResponseDTO.setInitializeFeedbackChat(true);
- rocketChatUserDTO.setUsername(USERNAME);
- userInfoResponseDTO.setUser(rocketChatUserDTO);
- groupDTO.setId(RC_GROUP_ID);
- groupResponseDTO.setSuccess(true);
- groupResponseDTO.setGroup(groupDTO);
- rocketChatCredentials.setRocketChatUserId(RC_USER_ID);
- rocketChatCredentials.setRocketChatUsername(RC_USERNAME);
-
- when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.of(session));
- when(consultingTypeManager.getConsultingTypeSettings(session.getConsultingTypeId()))
- .thenReturn(extendedConsultingTypeResponseDTO);
- when(rocketChatService.getUserInfo(RC_USER_ID)).thenReturn(userInfoResponseDTO);
- when(userHelper.doUsernamesMatch(anyString(), anyString())).thenReturn(true);
- when(rocketChatRoomNameGenerator.generateGroupName(any(Session.class)))
- .thenReturn(session.getId().toString());
- when(rocketChatService.createPrivateGroup(anyString(), any()))
- .thenReturn(Optional.of(groupResponseDTO));
-
- createEnquiryMessageFacade.createEnquiryMessage(
- new EnquiryData(user, SESSION_ID, MESSAGE, null, rocketChatCredentials));
- resetRequestAttributes();
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ session.setUser(user);
+ session.setConsultingTypeId(0);
+ session.setConsultant(null);
+ extendedConsultingTypeResponseDTO.setInitializeFeedbackChat(true);
+ rocketChatUserDTO.setUsername(USERNAME);
+ userInfoResponseDTO.setUser(rocketChatUserDTO);
+ groupDTO.setId(RC_GROUP_ID);
+ groupResponseDTO.setSuccess(true);
+ groupResponseDTO.setGroup(groupDTO);
+ rocketChatCredentials.setRocketChatUserId(RC_USER_ID);
+ rocketChatCredentials.setRocketChatUsername(RC_USERNAME);
+
+ when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.of(session));
+ when(consultingTypeManager.getConsultingTypeSettings(session.getConsultingTypeId()))
+ .thenReturn(extendedConsultingTypeResponseDTO);
+ when(rocketChatService.getUserInfo(RC_USER_ID)).thenReturn(userInfoResponseDTO);
+ when(userHelper.doUsernamesMatch(anyString(), anyString())).thenReturn(true);
+ when(rocketChatRoomNameGenerator.generateGroupName(any(Session.class)))
+ .thenReturn(session.getId().toString());
+ when(rocketChatService.createPrivateGroup(anyString(), any()))
+ .thenReturn(Optional.of(groupResponseDTO));
+
+ createEnquiryMessageFacade.createEnquiryMessage(
+ new EnquiryData(user, SESSION_ID, MESSAGE, null, rocketChatCredentials));
+ resetRequestAttributes();
+ });
}
- @Test(expected = InternalServerErrorException.class)
- public void
+ @Test
+ void
createEnquiryMessage_Should_ThrowInternalServerErrorException_When_UpdateRocketChatIdForUserFails()
throws RocketChatCreateGroupException {
-
- session.setUser(user);
- session.setConsultingTypeId(0);
- session.setConsultant(null);
- rocketChatUserDTO.setUsername(USERNAME);
- userInfoResponseDTO.setUser(rocketChatUserDTO);
- groupDTO.setId(RC_GROUP_ID);
- groupResponseDTO.setSuccess(true);
- groupResponseDTO.setGroup(groupDTO);
- rocketChatCredentials.setRocketChatUserId(RC_USER_ID);
- rocketChatCredentials.setRocketChatUsername(RC_USERNAME);
- extendedConsultingTypeResponseDTO.setInitializeFeedbackChat(true);
-
- when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.of(session));
- when(consultingTypeManager.getConsultingTypeSettings(session.getConsultingTypeId()))
- .thenReturn(extendedConsultingTypeResponseDTO);
- when(rocketChatService.getUserInfo(RC_USER_ID)).thenReturn(userInfoResponseDTO);
- when(userHelper.doUsernamesMatch(anyString(), anyString())).thenReturn(true);
- when(rocketChatRoomNameGenerator.generateGroupName(any(Session.class)))
- .thenReturn(session.getId().toString());
- when(rocketChatService.createPrivateGroup(anyString(), any()))
- .thenReturn(Optional.of(groupResponseDTO));
-
- createEnquiryMessageFacade.createEnquiryMessage(
- new EnquiryData(user, SESSION_ID, MESSAGE, null, rocketChatCredentials));
- resetRequestAttributes();
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ session.setUser(user);
+ session.setConsultingTypeId(0);
+ session.setConsultant(null);
+ rocketChatUserDTO.setUsername(USERNAME);
+ userInfoResponseDTO.setUser(rocketChatUserDTO);
+ groupDTO.setId(RC_GROUP_ID);
+ groupResponseDTO.setSuccess(true);
+ groupResponseDTO.setGroup(groupDTO);
+ rocketChatCredentials.setRocketChatUserId(RC_USER_ID);
+ rocketChatCredentials.setRocketChatUsername(RC_USERNAME);
+ extendedConsultingTypeResponseDTO.setInitializeFeedbackChat(true);
+
+ when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.of(session));
+ when(consultingTypeManager.getConsultingTypeSettings(session.getConsultingTypeId()))
+ .thenReturn(extendedConsultingTypeResponseDTO);
+ when(rocketChatService.getUserInfo(RC_USER_ID)).thenReturn(userInfoResponseDTO);
+ when(userHelper.doUsernamesMatch(anyString(), anyString())).thenReturn(true);
+ when(rocketChatRoomNameGenerator.generateGroupName(any(Session.class)))
+ .thenReturn(session.getId().toString());
+ when(rocketChatService.createPrivateGroup(anyString(), any()))
+ .thenReturn(Optional.of(groupResponseDTO));
+
+ createEnquiryMessageFacade.createEnquiryMessage(
+ new EnquiryData(user, SESSION_ID, MESSAGE, null, rocketChatCredentials));
+ resetRequestAttributes();
+ });
}
- @Test(expected = InternalServerErrorException.class)
- public void
- createEnquiryMessage_Should_ThrowInternalServerErrorException_When_UpdateOfSessionFails()
- throws RocketChatCreateGroupException {
-
- session.setUser(user);
- session.setConsultingTypeId(0);
- session.setConsultant(null);
- rocketChatUserDTO.setUsername(USERNAME);
- userInfoResponseDTO.setUser(rocketChatUserDTO);
- groupDTO.setId(RC_GROUP_ID);
- groupResponseDTO.setSuccess(true);
- groupResponseDTO.setGroup(groupDTO);
- rocketChatCredentials.setRocketChatUserId(RC_USER_ID);
- rocketChatCredentials.setRocketChatUsername(RC_USERNAME);
- extendedConsultingTypeResponseDTO.setInitializeFeedbackChat(true);
- InternalServerErrorException internalServerErrorException =
- new InternalServerErrorException(MESSAGE);
-
- when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.of(session));
- when(consultingTypeManager.getConsultingTypeSettings(session.getConsultingTypeId()))
- .thenReturn(extendedConsultingTypeResponseDTO);
- when(rocketChatService.getUserInfo(RC_USER_ID)).thenReturn(userInfoResponseDTO);
- when(userHelper.doUsernamesMatch(anyString(), anyString())).thenReturn(true);
- when(rocketChatRoomNameGenerator.generateGroupName(any(Session.class)))
- .thenReturn(session.getId().toString());
- when(rocketChatService.createPrivateGroup(Mockito.anyString(), any()))
- .thenReturn(Optional.of(groupResponseDTO));
- createEnquiryMessageFacade.createEnquiryMessage(
- new EnquiryData(user, SESSION_ID, MESSAGE, null, rocketChatCredentials));
- resetRequestAttributes();
+ @Test
+ void createEnquiryMessage_Should_ThrowInternalServerErrorException_When_UpdateOfSessionFails()
+ throws RocketChatCreateGroupException {
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ session.setUser(user);
+ session.setConsultingTypeId(0);
+ session.setConsultant(null);
+ rocketChatUserDTO.setUsername(USERNAME);
+ userInfoResponseDTO.setUser(rocketChatUserDTO);
+ groupDTO.setId(RC_GROUP_ID);
+ groupResponseDTO.setSuccess(true);
+ groupResponseDTO.setGroup(groupDTO);
+ rocketChatCredentials.setRocketChatUserId(RC_USER_ID);
+ rocketChatCredentials.setRocketChatUsername(RC_USERNAME);
+ extendedConsultingTypeResponseDTO.setInitializeFeedbackChat(true);
+ InternalServerErrorException internalServerErrorException =
+ new InternalServerErrorException(MESSAGE);
+
+ when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.of(session));
+ when(consultingTypeManager.getConsultingTypeSettings(session.getConsultingTypeId()))
+ .thenReturn(extendedConsultingTypeResponseDTO);
+ when(rocketChatService.getUserInfo(RC_USER_ID)).thenReturn(userInfoResponseDTO);
+ when(userHelper.doUsernamesMatch(anyString(), anyString())).thenReturn(true);
+ when(rocketChatRoomNameGenerator.generateGroupName(any(Session.class)))
+ .thenReturn(session.getId().toString());
+ when(rocketChatService.createPrivateGroup(Mockito.anyString(), any()))
+ .thenReturn(Optional.of(groupResponseDTO));
+ createEnquiryMessageFacade.createEnquiryMessage(
+ new EnquiryData(user, SESSION_ID, MESSAGE, null, rocketChatCredentials));
+ resetRequestAttributes();
+ });
}
- @Test(expected = InternalServerErrorException.class)
- public void
+ @Test
+ void
createEnquiryMessage_Should_ThrowInternalServerErrorException_When_PrivateGroupWithSystemUserIsNotPresent()
throws RocketChatCreateGroupException {
-
- session.setUser(user);
- session.setConsultingTypeId(0);
- session.setConsultant(null);
- extendedConsultingTypeResponseDTO.setInitializeFeedbackChat(true);
- rocketChatUserDTO.setUsername(USERNAME);
- userInfoResponseDTO.setUser(rocketChatUserDTO);
- groupDTO.setId(RC_GROUP_ID);
- groupResponseDTO.setSuccess(true);
- groupResponseDTO.setGroup(groupDTO);
- rocketChatCredentials.setRocketChatUserId(RC_USER_ID);
- rocketChatCredentials.setRocketChatUsername(RC_USERNAME);
-
- when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.of(session));
- when(consultingTypeManager.getConsultingTypeSettings(session.getConsultingTypeId()))
- .thenReturn(extendedConsultingTypeResponseDTO);
- when(rocketChatService.getUserInfo(RC_USER_ID)).thenReturn(userInfoResponseDTO);
- when(userHelper.doUsernamesMatch(anyString(), anyString())).thenReturn(true);
- when(rocketChatRoomNameGenerator.generateGroupName(any(Session.class)))
- .thenReturn(session.getId().toString());
- when(rocketChatService.createPrivateGroup(anyString(), any()))
- .thenReturn(Optional.of(groupResponseDTO));
- when(rocketChatService.createPrivateGroupWithSystemUser(any())).thenReturn(Optional.empty());
-
- createEnquiryMessageFacade.createEnquiryMessage(
- new EnquiryData(user, SESSION_ID, MESSAGE, null, rocketChatCredentials));
- resetRequestAttributes();
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ session.setUser(user);
+ session.setConsultingTypeId(0);
+ session.setConsultant(null);
+ extendedConsultingTypeResponseDTO.setInitializeFeedbackChat(true);
+ rocketChatUserDTO.setUsername(USERNAME);
+ userInfoResponseDTO.setUser(rocketChatUserDTO);
+ groupDTO.setId(RC_GROUP_ID);
+ groupResponseDTO.setSuccess(true);
+ groupResponseDTO.setGroup(groupDTO);
+ rocketChatCredentials.setRocketChatUserId(RC_USER_ID);
+ rocketChatCredentials.setRocketChatUsername(RC_USERNAME);
+
+ when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.of(session));
+ when(consultingTypeManager.getConsultingTypeSettings(session.getConsultingTypeId()))
+ .thenReturn(extendedConsultingTypeResponseDTO);
+ when(rocketChatService.getUserInfo(RC_USER_ID)).thenReturn(userInfoResponseDTO);
+ when(userHelper.doUsernamesMatch(anyString(), anyString())).thenReturn(true);
+ when(rocketChatRoomNameGenerator.generateGroupName(any(Session.class)))
+ .thenReturn(session.getId().toString());
+ when(rocketChatService.createPrivateGroup(anyString(), any()))
+ .thenReturn(Optional.of(groupResponseDTO));
+ when(rocketChatService.createPrivateGroupWithSystemUser(any()))
+ .thenReturn(Optional.empty());
+
+ createEnquiryMessageFacade.createEnquiryMessage(
+ new EnquiryData(user, SESSION_ID, MESSAGE, null, rocketChatCredentials));
+ resetRequestAttributes();
+ });
}
@Test
- public void createEnquiryMessage_Should_DeleteRcGroup_WhenAddSystemUserToGroupFails() {
+ void createEnquiryMessage_Should_DeleteRcGroup_WhenAddSystemUserToGroupFails() {
when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.of(SESSION_WITHOUT_CONSULTANT));
when(consultingTypeManager.getConsultingTypeSettings(
@@ -831,7 +874,7 @@ public void createEnquiryMessage_Should_DeleteRcGroup_WhenAddSystemUserToGroupFa
}
@Test
- public void createEnquiryMessage_Should_DeleteRcGroup_WhenRemoveSystemMessagesFails()
+ void createEnquiryMessage_Should_DeleteRcGroup_WhenRemoveSystemMessagesFails()
throws RocketChatCreateGroupException, RocketChatRemoveSystemMessagesException,
RocketChatUserNotInitializedException {
@@ -863,7 +906,7 @@ public void createEnquiryMessage_Should_DeleteRcGroup_WhenRemoveSystemMessagesFa
}
@Test
- public void
+ void
createEnquiryMessage_Should_DeleteRcGroupAndFeedbackGroup_WhenAddSystemUserToFeedbackGroupFails() {
when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.of(SESSION_WITHOUT_CONSULTANT));
@@ -890,7 +933,7 @@ public void createEnquiryMessage_Should_DeleteRcGroup_WhenRemoveSystemMessagesFa
}
@Test
- public void
+ void
createEnquiryMessage_Should_DeleteRcGroupAndFeedbackGroup_When_WhenRemoveSystemMessagesFailsForFeedbackGroup()
throws Exception {
@@ -930,7 +973,7 @@ public void createEnquiryMessage_Should_DeleteRcGroup_WhenRemoveSystemMessagesFa
}
@Test
- public void
+ void
createEnquiryMessage_Should_DeleteRcGroupAndFeedbackGroup_When_AddConsultantToRocketChatFeedbackGroupFails()
throws RocketChatCreateGroupException, RocketChatAddUserToGroupException {
@@ -969,7 +1012,7 @@ public void createEnquiryMessage_Should_DeleteRcGroup_WhenRemoveSystemMessagesFa
}
@Test
- public void createEnquiryMessage_Should_DeleteRcGroupFeedbackGroup_When_UpdateOfSessionFails()
+ void createEnquiryMessage_Should_DeleteRcGroupFeedbackGroup_When_UpdateOfSessionFails()
throws Exception {
Session spySession = Mockito.spy(SESSION_WITHOUT_CONSULTANT);
@@ -1003,7 +1046,7 @@ public void createEnquiryMessage_Should_DeleteRcGroupFeedbackGroup_When_UpdateOf
}
@Test
- public void
+ void
createEnquiryMessage_Should_DeleteRcGroupFeedbackGroup_When_PostWelcomeMessageFailsWithAnException()
throws Exception {
@@ -1048,9 +1091,8 @@ public void createEnquiryMessage_Should_DeleteRcGroupFeedbackGroup_When_UpdateOf
}
@Test
- public void
- createEnquiryMessage_Should_DeleteRcGroupFeedbackGroup_When_PostMessageFailsWithAnException()
- throws Exception {
+ void createEnquiryMessage_Should_DeleteRcGroupFeedbackGroup_When_PostMessageFailsWithAnException()
+ throws Exception {
when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.of(SESSION_WITHOUT_CONSULTANT));
when(consultingTypeManager.getConsultingTypeSettings(
@@ -1092,9 +1134,8 @@ public void createEnquiryMessage_Should_DeleteRcGroupFeedbackGroup_When_UpdateOf
}
@Test
- public void
- createEnquiryMessage_Should_DeleteRcGroupFeedback_When_UpdateOfUserFailsWithAnException()
- throws Exception {
+ void createEnquiryMessage_Should_DeleteRcGroupFeedback_When_UpdateOfUserFailsWithAnException()
+ throws Exception {
when(sessionService.getSession(SESSION_ID)).thenReturn(Optional.of(SESSION_WITHOUT_CONSULTANT));
when(consultingTypeManager.getConsultingTypeSettings(
@@ -1127,7 +1168,7 @@ public void createEnquiryMessage_Should_DeleteRcGroupFeedbackGroup_When_UpdateOf
}
@Test
- public void createEnquiryMessage_Should_PostAliasOnlyMessageAndWelcomeMessage() throws Exception {
+ void createEnquiryMessage_Should_PostAliasOnlyMessageAndWelcomeMessage() throws Exception {
session.setUser(user);
session.setConsultingTypeId(0);
@@ -1174,7 +1215,7 @@ public void createEnquiryMessage_Should_PostAliasOnlyMessageAndWelcomeMessage()
}
@Test
- public void createEnquiryMessage_Should_setSessionInProgress_When_consultantIsAlreadyAssigned()
+ void createEnquiryMessage_Should_setSessionInProgress_When_consultantIsAlreadyAssigned()
throws Exception {
var session = mock(Session.class);
when(session.getUser()).thenReturn(user);
diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/CreateNewConsultingTypeFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/CreateNewConsultingTypeFacadeTest.java
index ceacf749f..df59478bf 100644
--- a/src/test/java/de/caritas/cob/userservice/api/facade/CreateNewConsultingTypeFacadeTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/facade/CreateNewConsultingTypeFacadeTest.java
@@ -8,8 +8,7 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.UNKNOWN_CONSULTING_TYPE_ID;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -27,13 +26,13 @@
import de.caritas.cob.userservice.api.service.statistics.StatisticsService;
import de.caritas.cob.userservice.consultingtypeservice.generated.web.model.ExtendedConsultingTypeResponseDTO;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class CreateNewConsultingTypeFacadeTest {
@InjectMocks private CreateNewConsultingTypeFacade createNewConsultingTypeFacade;
@@ -111,38 +110,48 @@ public class CreateNewConsultingTypeFacadeTest {
.initializeUserChatAgencyRelation(any(), any(), any());
}
- @Test(expected = BadRequestException.class)
+ @Test
public void
initializeNewConsultingType_Should_ThrowBadRequestException_When_ProvidedWithInvalidConsultingType_For_NewConsultingTypeRegistrations() {
- EasyRandom easyRandom = new EasyRandom();
- UserDTO userDTO = easyRandom.nextObject(UserDTO.class);
- userDTO.setConsultingType(INVALID_CONSULTING_TYPE_ID);
- User user = easyRandom.nextObject(User.class);
- RocketChatCredentials rocketChatCredentials =
- easyRandom.nextObject(RocketChatCredentials.class);
- when(consultingTypeManager.getConsultingTypeSettings(INVALID_CONSULTING_TYPE_ID))
- .thenThrow(new NumberFormatException(""));
- createNewConsultingTypeFacade.initializeNewConsultingType(userDTO, user, rocketChatCredentials);
-
- verify(createUserChatRelationFacade, times(0))
- .initializeUserChatAgencyRelation(any(), any(), any());
+ assertThrows(
+ BadRequestException.class,
+ () -> {
+ EasyRandom easyRandom = new EasyRandom();
+ UserDTO userDTO = easyRandom.nextObject(UserDTO.class);
+ userDTO.setConsultingType(INVALID_CONSULTING_TYPE_ID);
+ User user = easyRandom.nextObject(User.class);
+ RocketChatCredentials rocketChatCredentials =
+ easyRandom.nextObject(RocketChatCredentials.class);
+ when(consultingTypeManager.getConsultingTypeSettings(INVALID_CONSULTING_TYPE_ID))
+ .thenThrow(new NumberFormatException(""));
+ createNewConsultingTypeFacade.initializeNewConsultingType(
+ userDTO, user, rocketChatCredentials);
+
+ verify(createUserChatRelationFacade, times(0))
+ .initializeUserChatAgencyRelation(any(), any(), any());
+ });
}
- @Test(expected = BadRequestException.class)
+ @Test
public void
initializeNewConsultingType_Should_ThrowBadRequestException_When_ProvidedWithUnknownConsultingType_For_NewConsultingTypeRegistrations() {
- EasyRandom easyRandom = new EasyRandom();
- UserDTO userDTO = easyRandom.nextObject(UserDTO.class);
- userDTO.setConsultingType(UNKNOWN_CONSULTING_TYPE_ID);
- User user = easyRandom.nextObject(User.class);
- RocketChatCredentials rocketChatCredentials =
- easyRandom.nextObject(RocketChatCredentials.class);
- when(consultingTypeManager.getConsultingTypeSettings(UNKNOWN_CONSULTING_TYPE_ID))
- .thenThrow(new MissingConsultingTypeException(""));
- createNewConsultingTypeFacade.initializeNewConsultingType(userDTO, user, rocketChatCredentials);
-
- verify(createUserChatRelationFacade, times(0))
- .initializeUserChatAgencyRelation(any(), any(), any());
+ assertThrows(
+ BadRequestException.class,
+ () -> {
+ EasyRandom easyRandom = new EasyRandom();
+ UserDTO userDTO = easyRandom.nextObject(UserDTO.class);
+ userDTO.setConsultingType(UNKNOWN_CONSULTING_TYPE_ID);
+ User user = easyRandom.nextObject(User.class);
+ RocketChatCredentials rocketChatCredentials =
+ easyRandom.nextObject(RocketChatCredentials.class);
+ when(consultingTypeManager.getConsultingTypeSettings(UNKNOWN_CONSULTING_TYPE_ID))
+ .thenThrow(new MissingConsultingTypeException(""));
+ createNewConsultingTypeFacade.initializeNewConsultingType(
+ userDTO, user, rocketChatCredentials);
+
+ verify(createUserChatRelationFacade, times(0))
+ .initializeUserChatAgencyRelation(any(), any(), any());
+ });
}
@Test
diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/CreateSessionFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/CreateSessionFacadeTest.java
index 88b896b25..1c1df7e50 100644
--- a/src/test/java/de/caritas/cob/userservice/api/facade/CreateSessionFacadeTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/facade/CreateSessionFacadeTest.java
@@ -13,7 +13,8 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USER_SESSION_RESPONSE_DTO_LIST_U25;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
@@ -42,16 +43,16 @@
import de.caritas.cob.userservice.consultingtypeservice.generated.web.model.ExtendedConsultingTypeResponseDTO;
import java.util.Optional;
import org.jeasy.random.EasyRandom;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.slf4j.Logger;
import org.springframework.http.HttpStatus;
-import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
-@RunWith(SpringRunner.class)
+@ExtendWith(SpringExtension.class)
public class CreateSessionFacadeTest {
@InjectMocks private CreateSessionFacade createSessionFacade;
@@ -62,67 +63,83 @@ public class CreateSessionFacadeTest {
@Mock private UserAccountService userAccountProvider;
@Mock private Logger logger;
- @Before
+ @BeforeEach
public void setup() {
setInternalState(LogService.class, "LOGGER", logger);
}
/** Method: createUserSession */
- @Test(expected = ConflictException.class)
+ @Test
public void createUserSession_Should_ReturnConflict_When_AlreadyRegisteredToConsultingType() {
-
- when(sessionService.getSessionsForUserByConsultingTypeId(any(), anyInt()))
- .thenReturn(SESSION_LIST);
- createSessionFacade.createUserSession(USER_DTO_SUCHT, USER, CONSULTING_TYPE_SETTINGS_SUCHT);
-
- verify(sessionService, times(0)).saveSession(any());
+ assertThrows(
+ ConflictException.class,
+ () -> {
+ when(sessionService.getSessionsForUserByConsultingTypeId(any(), anyInt()))
+ .thenReturn(SESSION_LIST);
+ createSessionFacade.createUserSession(
+ USER_DTO_SUCHT, USER, CONSULTING_TYPE_SETTINGS_SUCHT);
+
+ verify(sessionService, times(0)).saveSession(any());
+ });
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
createUserSession_Should_ReturnInternalServerErrorAndRollbackUserAccount_When_SessionCouldNotBeSaved() {
-
- when(sessionService.getSessionsForUserId(USER_ID))
- .thenReturn(USER_SESSION_RESPONSE_DTO_LIST_U25);
- when(agencyVerifier.getVerifiedAgency(AGENCY_ID, 0)).thenReturn(AGENCY_DTO_U25);
- when(sessionService.initializeSession(any(), any(), any(Boolean.class)))
- .thenThrow(new InternalServerErrorException(MESSAGE));
-
- createSessionFacade.createUserSession(USER_DTO_SUCHT, USER, CONSULTING_TYPE_SETTINGS_SUCHT);
-
- verify(logger, atLeastOnce()).error(anyString(), anyString(), anyString());
- verify(rollbackFacade, times(1)).rollBackUserAccount(any());
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(sessionService.getSessionsForUserId(USER_ID))
+ .thenReturn(USER_SESSION_RESPONSE_DTO_LIST_U25);
+ when(agencyVerifier.getVerifiedAgency(AGENCY_ID, 0)).thenReturn(AGENCY_DTO_U25);
+ when(sessionService.initializeSession(any(), any(), any(Boolean.class)))
+ .thenThrow(new InternalServerErrorException(MESSAGE));
+
+ createSessionFacade.createUserSession(
+ USER_DTO_SUCHT, USER, CONSULTING_TYPE_SETTINGS_SUCHT);
+
+ verify(logger, atLeastOnce()).error(anyString(), anyString(), anyString());
+ verify(rollbackFacade, times(1)).rollBackUserAccount(any());
+ });
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
createUserSession_Should_ReturnInternalServerErrorAndRollbackUserAccount_When_SessionDataCouldNotBeSaved() {
-
- when(sessionService.getSessionsForUserId(USER_ID))
- .thenReturn(USER_SESSION_RESPONSE_DTO_LIST_U25);
- when(agencyVerifier.getVerifiedAgency(AGENCY_ID, 0)).thenReturn(AGENCY_DTO_U25);
- when(sessionService.initializeSession(any(), any(), any(Boolean.class)))
- .thenThrow(new InternalServerErrorException(MESSAGE));
- doThrow(INTERNAL_SERVER_ERROR_EXCEPTION)
- .when(sessionDataService)
- .saveSessionData(any(Session.class), any());
-
- createSessionFacade.createUserSession(USER_DTO_SUCHT, USER, CONSULTING_TYPE_SETTINGS_SUCHT);
-
- verify(logger, atLeastOnce()).error(anyString(), anyString(), anyString());
- verify(sessionService, times(1)).deleteSession(any());
- verify(rollbackFacade, times(1)).rollBackUserAccount(any());
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(sessionService.getSessionsForUserId(USER_ID))
+ .thenReturn(USER_SESSION_RESPONSE_DTO_LIST_U25);
+ when(agencyVerifier.getVerifiedAgency(AGENCY_ID, 0)).thenReturn(AGENCY_DTO_U25);
+ when(sessionService.initializeSession(any(), any(), any(Boolean.class)))
+ .thenThrow(new InternalServerErrorException(MESSAGE));
+ doThrow(INTERNAL_SERVER_ERROR_EXCEPTION)
+ .when(sessionDataService)
+ .saveSessionData(any(Session.class), any());
+
+ createSessionFacade.createUserSession(
+ USER_DTO_SUCHT, USER, CONSULTING_TYPE_SETTINGS_SUCHT);
+
+ verify(logger, atLeastOnce()).error(anyString(), anyString(), anyString());
+ verify(sessionService, times(1)).deleteSession(any());
+ verify(rollbackFacade, times(1)).rollBackUserAccount(any());
+ });
}
- @Test(expected = BadRequestException.class)
+ @Test
public void
createUserSession_Should_ReturnBadRequest_When_AgencyForConsultingTypeCouldNotBeFound() {
-
- when(sessionService.getSessionsForUserId(USER_ID))
- .thenReturn(USER_SESSION_RESPONSE_DTO_LIST_U25);
- when(agencyVerifier.getVerifiedAgency(AGENCY_ID, 0)).thenReturn(null);
-
- createSessionFacade.createUserSession(USER_DTO_SUCHT, USER, CONSULTING_TYPE_SETTINGS_SUCHT);
+ assertThrows(
+ BadRequestException.class,
+ () -> {
+ when(sessionService.getSessionsForUserId(USER_ID))
+ .thenReturn(USER_SESSION_RESPONSE_DTO_LIST_U25);
+ when(agencyVerifier.getVerifiedAgency(AGENCY_ID, 0)).thenReturn(null);
+
+ createSessionFacade.createUserSession(
+ USER_DTO_SUCHT, USER, CONSULTING_TYPE_SETTINGS_SUCHT);
+ });
}
@Test
diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/CreateUserChatRelationFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/CreateUserChatRelationFacadeTest.java
index e0081d1d0..1f6dce75d 100644
--- a/src/test/java/de/caritas/cob/userservice/api/facade/CreateUserChatRelationFacadeTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/facade/CreateUserChatRelationFacadeTest.java
@@ -7,8 +7,7 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USER_WITH_RC_ID;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -30,15 +29,15 @@
import java.util.Collections;
import java.util.List;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.auditing.AuditingHandler;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class CreateUserChatRelationFacadeTest {
@InjectMocks private CreateUserChatRelationFacade createUserChatRelationFacade;
@@ -126,46 +125,54 @@ public class CreateUserChatRelationFacadeTest {
assertEquals(rocketChatCredentials.getRocketChatUserId(), captor.getValue().getRcUserId());
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
initializeUserChatAgencyRelation_Should_ThrowInternalServerErrorExceptionAndRollBackUserAccount_IfLoginToRocketChatFails_OnUpdatingRocketChatCredentialsInDb()
throws RocketChatLoginException {
- EasyRandom easyRandom = new EasyRandom();
- UserDTO userDTO = easyRandom.nextObject(UserDTO.class);
- User user = easyRandom.nextObject(User.class);
- user.setRcUserId(null);
- ArgumentCaptor captor =
- ArgumentCaptor.forClass(RollbackUserAccountInformation.class);
-
- when(rocketChatService.loginUserFirstTime(any(), any()))
- .thenThrow(new RocketChatLoginException(MESSAGE));
-
- createUserChatRelationFacade.initializeUserChatAgencyRelation(userDTO, user, null);
-
- verify(rollbackFacade).rollBackUserAccount(captor.capture());
- assertEquals(user, captor.getValue().getUser());
- assertTrue(captor.getValue().isRollBackUserAccount());
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ EasyRandom easyRandom = new EasyRandom();
+ UserDTO userDTO = easyRandom.nextObject(UserDTO.class);
+ User user = easyRandom.nextObject(User.class);
+ user.setRcUserId(null);
+ ArgumentCaptor captor =
+ ArgumentCaptor.forClass(RollbackUserAccountInformation.class);
+
+ when(rocketChatService.loginUserFirstTime(any(), any()))
+ .thenThrow(new RocketChatLoginException(MESSAGE));
+
+ createUserChatRelationFacade.initializeUserChatAgencyRelation(userDTO, user, null);
+
+ verify(rollbackFacade).rollBackUserAccount(captor.capture());
+ assertEquals(user, captor.getValue().getUser());
+ assertTrue(captor.getValue().isRollBackUserAccount());
+ });
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
initializeUserChatAgencyRelation_Should_ThrowInternalServerErrorExceptionAndRollBackUserAccount_IfLoginToRocketChatReturnsInvalidResponse_OnUpdatingRocketChatCredentialsInDb()
throws RocketChatLoginException {
- EasyRandom easyRandom = new EasyRandom();
- UserDTO userDTO = easyRandom.nextObject(UserDTO.class);
- User user = easyRandom.nextObject(User.class);
- user.setRcUserId(null);
- ArgumentCaptor captor =
- ArgumentCaptor.forClass(RollbackUserAccountInformation.class);
-
- when(rocketChatService.loginUserFirstTime(any(), any()))
- .thenReturn(LOGIN_RESPONSE_ENTITY_OK_NO_TOKEN);
-
- createUserChatRelationFacade.initializeUserChatAgencyRelation(userDTO, user, null);
-
- verify(rollbackFacade).rollBackUserAccount(captor.capture());
- assertEquals(user, captor.getValue().getUser());
- assertTrue(captor.getValue().isRollBackUserAccount());
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ EasyRandom easyRandom = new EasyRandom();
+ UserDTO userDTO = easyRandom.nextObject(UserDTO.class);
+ User user = easyRandom.nextObject(User.class);
+ user.setRcUserId(null);
+ ArgumentCaptor captor =
+ ArgumentCaptor.forClass(RollbackUserAccountInformation.class);
+
+ when(rocketChatService.loginUserFirstTime(any(), any()))
+ .thenReturn(LOGIN_RESPONSE_ENTITY_OK_NO_TOKEN);
+
+ createUserChatRelationFacade.initializeUserChatAgencyRelation(userDTO, user, null);
+
+ verify(rollbackFacade).rollBackUserAccount(captor.capture());
+ assertEquals(user, captor.getValue().getUser());
+ assertTrue(captor.getValue().isRollBackUserAccount());
+ });
}
@Test
@@ -193,45 +200,53 @@ public class CreateUserChatRelationFacadeTest {
assertEquals(user, captor.getValue().getUser());
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
initializeUserChatAgencyRelation_Should_ThrowInternalServerErrorExceptionAndRollBackUserAccount_IfCreateUserChatAgencyRelationFails() {
- ArgumentCaptor captor =
- ArgumentCaptor.forClass(RollbackUserAccountInformation.class);
- EasyRandom easyRandom = new EasyRandom();
- UserDTO userDTO = easyRandom.nextObject(UserDTO.class);
- User user = easyRandom.nextObject(User.class);
- RocketChatCredentials rocketChatCredentials =
- easyRandom.nextObject(RocketChatCredentials.class);
-
- when(userAgencyService.saveUserAgency(any()))
- .thenThrow(new InternalServerErrorException(MESSAGE));
-
- createUserChatRelationFacade.initializeUserChatAgencyRelation(
- userDTO, user, rocketChatCredentials);
-
- verify(rollbackFacade).rollBackUserAccount(captor.capture());
- assertEquals(user, captor.getValue().getUser());
- assertTrue(captor.getValue().isRollBackUserAccount());
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ ArgumentCaptor captor =
+ ArgumentCaptor.forClass(RollbackUserAccountInformation.class);
+ EasyRandom easyRandom = new EasyRandom();
+ UserDTO userDTO = easyRandom.nextObject(UserDTO.class);
+ User user = easyRandom.nextObject(User.class);
+ RocketChatCredentials rocketChatCredentials =
+ easyRandom.nextObject(RocketChatCredentials.class);
+
+ when(userAgencyService.saveUserAgency(any()))
+ .thenThrow(new InternalServerErrorException(MESSAGE));
+
+ createUserChatRelationFacade.initializeUserChatAgencyRelation(
+ userDTO, user, rocketChatCredentials);
+
+ verify(rollbackFacade).rollBackUserAccount(captor.capture());
+ assertEquals(user, captor.getValue().getUser());
+ assertTrue(captor.getValue().isRollBackUserAccount());
+ });
}
- @Test(expected = BadRequestException.class)
+ @Test
public void
initializeUserChatAgencyRelation_Should_ThrowBadRequestException_WhenAlreadyRegisteredToConsultingType() {
- EasyRandom easyRandom = new EasyRandom();
- UserDTO userDTO = easyRandom.nextObject(UserDTO.class);
- userDTO.setAgencyId(AGENCY_ID);
- User user = easyRandom.nextObject(User.class);
- RocketChatCredentials rocketChatCredentials =
- easyRandom.nextObject(RocketChatCredentials.class);
- UserAgency userAgency = new UserAgency(user, AGENCY_ID);
- List userAgencies = Collections.singletonList(userAgency);
-
- when(userAgencyService.getUserAgenciesByUser(any())).thenReturn(userAgencies);
-
- createUserChatRelationFacade.initializeUserChatAgencyRelation(
- userDTO, user, rocketChatCredentials);
-
- verify(userAgencyService, times(1)).saveUserAgency(any());
+ assertThrows(
+ BadRequestException.class,
+ () -> {
+ EasyRandom easyRandom = new EasyRandom();
+ UserDTO userDTO = easyRandom.nextObject(UserDTO.class);
+ userDTO.setAgencyId(AGENCY_ID);
+ User user = easyRandom.nextObject(User.class);
+ RocketChatCredentials rocketChatCredentials =
+ easyRandom.nextObject(RocketChatCredentials.class);
+ UserAgency userAgency = new UserAgency(user, AGENCY_ID);
+ List userAgencies = Collections.singletonList(userAgency);
+
+ when(userAgencyService.getUserAgenciesByUser(any())).thenReturn(userAgencies);
+
+ createUserChatRelationFacade.initializeUserChatAgencyRelation(
+ userDTO, user, rocketChatCredentials);
+
+ verify(userAgencyService, times(1)).saveUserAgency(any());
+ });
}
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/CreateUserFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/CreateUserFacadeTest.java
index 99e844996..d39a855aa 100644
--- a/src/test/java/de/caritas/cob/userservice/api/facade/CreateUserFacadeTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/facade/CreateUserFacadeTest.java
@@ -11,6 +11,7 @@
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.notNullValue;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
@@ -42,15 +43,15 @@
import de.caritas.cob.userservice.consultingtypeservice.generated.web.model.ExtendedConsultingTypeResponseDTO;
import de.caritas.cob.userservice.tenantservice.generated.web.model.RestrictedTenantDTO;
import org.hamcrest.Matchers;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class CreateUserFacadeTest {
@InjectMocks private CreateUserFacade createUserFacade;
@@ -85,15 +86,19 @@ public class CreateUserFacadeTest {
}
}
- @Test(expected = BadRequestException.class)
+ @Test
public void
createUserAccountWithInitializedConsultingType_Should_ThrowBadRequest_When_ProvidedConsultingTypeDoesNotMatchAgency() {
- doNothing().when(userVerifier).checkIfUsernameIsAvailable(any());
- doThrow(new BadRequestException(ERROR))
- .when(agencyVerifier)
- .checkIfConsultingTypeMatchesToAgency(any());
-
- createUserFacade.createUserAccountWithInitializedConsultingType(USER_DTO_SUCHT);
+ assertThrows(
+ BadRequestException.class,
+ () -> {
+ doNothing().when(userVerifier).checkIfUsernameIsAvailable(any());
+ doThrow(new BadRequestException(ERROR))
+ .when(agencyVerifier)
+ .checkIfConsultingTypeMatchesToAgency(any());
+
+ createUserFacade.createUserAccountWithInitializedConsultingType(USER_DTO_SUCHT);
+ });
}
@Test
@@ -114,14 +119,17 @@ public class CreateUserFacadeTest {
}
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
createUserAccountWithInitializedConsultingType_Should_ThrowInternalServerErrorException_When_CreateKeycloakUserReturnsNoUserId() {
-
- when(keycloakService.createKeycloakUser(any()))
- .thenReturn(KEYCLOAK_CREATE_USER_RESPONSE_DTO_WITHOUT_USER_ID);
-
- createUserFacade.createUserAccountWithInitializedConsultingType(USER_DTO_SUCHT);
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(keycloakService.createKeycloakUser(any()))
+ .thenReturn(KEYCLOAK_CREATE_USER_RESPONSE_DTO_WITHOUT_USER_ID);
+
+ createUserFacade.createUserAccountWithInitializedConsultingType(USER_DTO_SUCHT);
+ });
}
@Test
@@ -185,39 +193,53 @@ public class CreateUserFacadeTest {
verify(rollbackFacade, times(0)).rollBackUserAccount(any());
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
updateKeycloakAccountAndCreateDatabaseUserAccount_Should_ThrowInternalServerErrorExceptionAndRollbackUserAccount_When_UpdateKeycloakPwFails() {
- doThrow(new RuntimeException()).when(keycloakService).updatePassword(anyString(), anyString());
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ doThrow(new RuntimeException())
+ .when(keycloakService)
+ .updatePassword(anyString(), anyString());
- createUserFacade.updateIdentityAndCreateAccount(USER_ID, USER_DTO_SUCHT, UserRole.USER);
+ createUserFacade.updateIdentityAndCreateAccount(USER_ID, USER_DTO_SUCHT, UserRole.USER);
- verify(rollbackFacade, times(1)).rollBackUserAccount(any());
+ verify(rollbackFacade, times(1)).rollBackUserAccount(any());
+ });
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
updateKeycloakAccountAndCreateDatabaseUserAccount_Should_ThrowInternalServerErrorExceptionAndRollbackUserAccount_When_UpdateKeycloakRoleFails() {
- doThrow(new RuntimeException())
- .when(keycloakService)
- .updateRole(anyString(), any(UserRole.class));
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ doThrow(new RuntimeException())
+ .when(keycloakService)
+ .updateRole(anyString(), any(UserRole.class));
- createUserFacade.updateIdentityAndCreateAccount(USER_ID, USER_DTO_SUCHT, UserRole.USER);
+ createUserFacade.updateIdentityAndCreateAccount(USER_ID, USER_DTO_SUCHT, UserRole.USER);
- verify(rollbackFacade, times(1)).rollBackUserAccount(any());
+ verify(rollbackFacade, times(1)).rollBackUserAccount(any());
+ });
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
updateKeycloakAccountAndCreateDatabaseUserAccount_Should_ThrowInternalServerErrorExceptionAndRollbackUserAccount_When_CreateDbUserFails() {
- when(consultingTypeManager.getConsultingTypeSettings(any()))
- .thenReturn(CONSULTING_TYPE_SETTINGS_KREUZBUND);
- doNothing().when(keycloakService).updatePassword(anyString(), anyString());
- when(userService.createUser(any(), any(), any(), any(), anyBoolean(), any()))
- .thenThrow(new IllegalArgumentException());
-
- createUserFacade.updateIdentityAndCreateAccount(USER_ID, USER_DTO_SUCHT, UserRole.USER);
-
- verify(rollbackFacade, times(1)).rollBackUserAccount(any());
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(consultingTypeManager.getConsultingTypeSettings(any()))
+ .thenReturn(CONSULTING_TYPE_SETTINGS_KREUZBUND);
+ doNothing().when(keycloakService).updatePassword(anyString(), anyString());
+ when(userService.createUser(any(), any(), any(), any(), anyBoolean(), any()))
+ .thenThrow(new IllegalArgumentException());
+
+ createUserFacade.updateIdentityAndCreateAccount(USER_ID, USER_DTO_SUCHT, UserRole.USER);
+
+ verify(rollbackFacade, times(1)).rollBackUserAccount(any());
+ });
}
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/EmailNotificationFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/EmailNotificationFacadeTest.java
index b46af6563..6becfc8b5 100644
--- a/src/test/java/de/caritas/cob/userservice/api/facade/EmailNotificationFacadeTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/facade/EmailNotificationFacadeTest.java
@@ -23,6 +23,7 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USERNAME_ENCODED;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USER_ID;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.atLeastOnce;
@@ -84,19 +85,22 @@
import java.util.Optional;
import java.util.Set;
import org.jeasy.random.EasyRandom;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.Spy;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
import org.slf4j.Logger;
import org.springframework.test.util.ReflectionTestUtils;
-@RunWith(MockitoJUnitRunner.class)
-public class EmailNotificationFacadeTest {
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
+class EmailNotificationFacadeTest {
private final Consultant CONSULTANT =
new Consultant(
@@ -472,8 +476,8 @@ public class EmailNotificationFacadeTest {
@Mock TenantTemplateSupplier tenantTemplateSupplier;
- @Before
- public void setup() throws NoSuchFieldException, SecurityException {
+ @BeforeEach
+ void setup() throws NoSuchFieldException, SecurityException {
when(identityClientConfig.getEmailDummySuffix()).thenReturn(FIELD_VALUE_EMAIL_DUMMY_SUFFIX);
ReflectionTestUtils.setField(
emailNotificationFacade,
@@ -492,7 +496,7 @@ public void setup() throws NoSuchFieldException, SecurityException {
}
@Test
- public void
+ void
sendNewEnquiryEmailNotification_Should_SendEmailNotificationViaMailServiceHelperToConsultants() {
givenNewEnquiryMailSupplierReturnNonEmptyMails();
var session = givenEnquirySession();
@@ -503,8 +507,7 @@ public void setup() throws NoSuchFieldException, SecurityException {
}
@Test
- public void
- sendNewEnquiryEmailNotification_ShouldNot_SendEmailNotificationViaMailServiceHelperToUser() {
+ void sendNewEnquiryEmailNotification_ShouldNot_SendEmailNotificationViaMailServiceHelperToUser() {
givenNewEnquiryMailSupplierReturnNonEmptyMails();
var session = givenEnquirySession();
@@ -514,7 +517,7 @@ public void setup() throws NoSuchFieldException, SecurityException {
}
@Test
- public void sendNewEnquiryEmailNotification_Should_SetCurrentTenantContextFromSession() {
+ void sendNewEnquiryEmailNotification_Should_SetCurrentTenantContextFromSession() {
assertThat(TenantContext.getCurrentTenant()).isNull();
givenNewEnquiryMailSupplierReturnNonEmptyMails();
var session = givenEnquirySession();
@@ -543,14 +546,14 @@ private List getMailDTOS() {
}
@Test
- public void sendNewEnquiryEmailNotification_ShouldNot_SendEmailWhenGeneratedEmailListIsEmpty() {
+ void sendNewEnquiryEmailNotification_ShouldNot_SendEmailWhenGeneratedEmailListIsEmpty() {
emailNotificationFacade.sendNewEnquiryEmailNotification(SESSION, null);
verify(mailService, times(0)).sendEmailNotification(Mockito.any(MailsDTO.class));
}
@Test
- public void sendNewEnquiryEmailNotification_Should_LogError_WhenSendEmailFails() {
+ void sendNewEnquiryEmailNotification_Should_LogError_WhenSendEmailFails() {
var session = givenEnquirySession();
EmailNotificationException emailNotificationException =
new EmailNotificationException(new Exception());
@@ -563,7 +566,7 @@ public void sendNewEnquiryEmailNotification_Should_LogError_WhenSendEmailFails()
/** Method: sendNewMessageNotification */
@Test
- public void
+ void
sendNewMessageNotification_Should_SendEmailNotificationViaMailServiceHelperToConsultant_WhenCalledAsUserAuthorityAndIsTeamSession() {
when(sessionService.getSessionByGroupIdAndUser(RC_GROUP_ID, USER_ID, USER_ROLES))
@@ -579,7 +582,7 @@ public void sendNewEnquiryEmailNotification_Should_LogError_WhenSendEmailFails()
}
@Test
- public void
+ void
sendNewMessageNotification_ShouldNot_SendEmailNotificationToUser_WhenCalledAsUserAuthorityAndIsTeamSession() {
when(sessionService.getSessionByGroupIdAndUser(RC_GROUP_ID, USER_ID, USER_ROLES))
@@ -595,7 +598,7 @@ public void sendNewEnquiryEmailNotification_Should_LogError_WhenSendEmailFails()
}
@Test
- public void
+ void
sendNewMessageNotification_ShouldNot_SendEmail_WhenMailListIsEmptyAndCalledAsUserAuthorityAndIsTeamSession() {
when(sessionService.getSessionByGroupIdAndUser(RC_GROUP_ID, USER_ID, USER_ROLES))
@@ -610,7 +613,7 @@ public void sendNewEnquiryEmailNotification_Should_LogError_WhenSendEmailFails()
}
@Test
- public void sendNewMessageNotification_Should_LogError_WhenSessionServiceFails() {
+ void sendNewMessageNotification_Should_LogError_WhenSessionServiceFails() {
InternalServerErrorException serviceException = new InternalServerErrorException(ERROR_MSG);
when(sessionService.getSessionByGroupIdAndUser(RC_GROUP_ID, USER_ID, USER_ROLES))
.thenThrow(serviceException);
@@ -620,7 +623,7 @@ public void sendNewMessageNotification_Should_LogError_WhenSessionServiceFails()
}
@Test
- public void
+ void
sendNewMessageNotification_ShouldNot_SendEmailAndLogEmailNotificationFacadeError_WhenSessionIsNullOrEmpty() {
when(sessionService.getSessionByGroupIdAndUser(RC_GROUP_ID, USER_ID, USER_ROLES))
@@ -633,7 +636,7 @@ public void sendNewMessageNotification_Should_LogError_WhenSessionServiceFails()
}
@Test
- public void
+ void
sendNewMessageNotification_ShouldNot_SendEmailAndLogEmailNotificationFacadeError_WhenSessionIsNotInProgress() {
when(sessionService.getSessionByGroupIdAndUser(RC_GROUP_ID, USER_ID, USER_ROLES))
@@ -646,7 +649,7 @@ public void sendNewMessageNotification_Should_LogError_WhenSessionServiceFails()
}
@Test
- public void
+ void
sendNewMessageNotification_ShouldNot_SendEmail_WhenCalledAsUserAuthorityAndIsSingleSessionAndConsultantHasNoEmailProvided() {
when(sessionService.getSessionByGroupIdAndUser(RC_GROUP_ID, USER_ID, USER_ROLES))
@@ -658,7 +661,7 @@ public void sendNewMessageNotification_Should_LogError_WhenSessionServiceFails()
}
@Test
- public void
+ void
sendNewMessageNotification_Should_SendEmailNotificationViaMailServiceHelper_WhenCalledAsUserAuthorityAndIsSingleSession() {
when(sessionService.getSessionByGroupIdAndUser(RC_GROUP_ID, USER_ID, USER_ROLES))
@@ -670,7 +673,7 @@ public void sendNewMessageNotification_Should_LogError_WhenSessionServiceFails()
}
@Test
- public void
+ void
sendNewMessageNotification_ShouldNot_SendEmailAndLogEmailNotificationFacadeWarning_When_GetSessionFails() {
when(sessionService.getSessionByGroupIdAndUser(RC_GROUP_ID, CONSULTANT_ID, CONSULTANT_ROLES))
@@ -684,7 +687,7 @@ public void sendNewMessageNotification_Should_LogError_WhenSessionServiceFails()
}
@Test
- public void
+ void
sendNewMessageNotification_Should_LogEmailNotificationFacadeError_When_ErrorOccursDuringMailTransmission() {
when(sessionService.getSessionByGroupIdAndUser(RC_GROUP_ID, CONSULTANT_ID, CONSULTANT_ROLES))
@@ -699,7 +702,7 @@ public void sendNewMessageNotification_Should_LogError_WhenSessionServiceFails()
}
@Test
- public void
+ void
sendNewMessageNotification_ShouldNot_SendEmail_WhenCalledAsConsultantAuthorityAndAskerHasNoEmailProvided() {
when(sessionService.getSessionByGroupIdAndUser(RC_GROUP_ID, CONSULTANT_ID, CONSULTANT_ROLES))
@@ -712,7 +715,7 @@ public void sendNewMessageNotification_Should_LogError_WhenSessionServiceFails()
}
@Test
- public void
+ void
sendNewMessageNotification_Should_SendEmailToUserWithEncodedUsernames_WhenCalledAsConsultantAuthorityAndAskerHasEmail() {
when(sessionService.getSessionByGroupIdAndUser(RC_GROUP_ID, CONSULTANT_ID, CONSULTANT_ROLES))
@@ -725,7 +728,7 @@ public void sendNewMessageNotification_Should_LogError_WhenSessionServiceFails()
}
@Test
- public void
+ void
sendNewMessageNotification_Should_SendEmailToAllConsultants_WhenIsTeamSessionAndConsultingTypeSettingsToSendToAllTeamConsultantsIsTrue() {
when(sessionService.getSessionByGroupIdAndUser(RC_GROUP_ID, USER_ID, USER_ROLES))
@@ -740,7 +743,7 @@ public void sendNewMessageNotification_Should_LogError_WhenSessionServiceFails()
}
@Test
- public void
+ void
sendNewMessageNotification_Should_SendEmailToAssignConsultantOnly_WhenIsTeamSessionAndConsultingTypeSettingsToSendToAllTeamConsultantsIsFalse() {
when(sessionService.getSessionByGroupIdAndUser(RC_GROUP_ID, USER_ID, USER_ROLES))
@@ -755,7 +758,7 @@ public void sendNewMessageNotification_Should_LogError_WhenSessionServiceFails()
/** Method: sendNewFeedbackMessageNotification */
@Test
- public void
+ void
sendNewFeedbackMessageNotification_Should_SendEmailToAllFeedbackChatGroupMembersWithDecodedUsernames_WhenAssignedConsultantWroteAFeedbackMessage() {
when(consultantService.getConsultant(CONSULTANT_ID)).thenReturn(Optional.of(CONSULTANT));
when(sessionService.getSessionByFeedbackGroupId(RC_FEEDBACK_GROUP_ID)).thenReturn(SESSION);
@@ -772,7 +775,7 @@ public void sendNewMessageNotification_Should_LogError_WhenSessionServiceFails()
}
@Test
- public void
+ void
sendNewFeedbackMessageNotification_Should_SendEmailToAssignedConsultantWithDecodedUsername_WhenOtherConsultantWrote() {
when(consultantService.getConsultant(CONSULTANT_ID_2)).thenReturn(Optional.of(CONSULTANT2));
@@ -785,7 +788,7 @@ public void sendNewMessageNotification_Should_LogError_WhenSessionServiceFails()
}
@Test
- public void
+ void
sendNewFeedbackMessageNotification_Should_LogErrorAndSendNoMails_WhenCallingConsultantIsNotFound() {
emailNotificationFacade.sendNewFeedbackMessageNotification(
@@ -795,8 +798,7 @@ public void sendNewMessageNotification_Should_LogError_WhenSessionServiceFails()
}
@Test
- public void
- sendNewFeedbackMessageNotification_Should_LogErrorAndSendNoMails_WhenSessionIsNotFound() {
+ void sendNewFeedbackMessageNotification_Should_LogErrorAndSendNoMails_WhenSessionIsNotFound() {
when(sessionService.getSessionByFeedbackGroupId(RC_FEEDBACK_GROUP_ID)).thenReturn(null);
@@ -807,7 +809,7 @@ public void sendNewMessageNotification_Should_LogError_WhenSessionServiceFails()
}
@Test
- public void
+ void
sendNewFeedbackMessageNotification_Should_LogErrorAndSendNoMails_WhenNoConsultantIsAssignedToSession() {
when(sessionService.getSessionByFeedbackGroupId(RC_FEEDBACK_GROUP_ID))
@@ -820,7 +822,7 @@ public void sendNewMessageNotification_Should_LogError_WhenSessionServiceFails()
}
@Test
- public void sendAssignEnquiryEmailNotification_Should_SendEmail_WhenAllParametersAreValid() {
+ void sendAssignEnquiryEmailNotification_Should_SendEmail_WhenAllParametersAreValid() {
when(consultantService.getConsultant(CONSULTANT_ID_2)).thenReturn(Optional.of(CONSULTANT2));
emailNotificationFacade.sendAssignEnquiryEmailNotification(
@@ -830,7 +832,7 @@ public void sendAssignEnquiryEmailNotification_Should_SendEmail_WhenAllParameter
}
@Test
- public void
+ void
sendAssignEnquiryEmailNotification_Should_LogErrorAndSendNoMails_WhenReceiverConsultantIsNull() {
emailNotificationFacade.sendAssignEnquiryEmailNotification(
null, CONSULTANT_ID_2, USERNAME, null);
@@ -838,7 +840,7 @@ public void sendAssignEnquiryEmailNotification_Should_SendEmail_WhenAllParameter
}
@Test
- public void
+ void
sendAssignEnquiryEmailNotification_Should_LogErrorAndSendNoMails_WhenReceiverConsultantIsMissingEmailAddress() {
emailNotificationFacade.sendAssignEnquiryEmailNotification(
CONSULTANT_WITHOUT_MAIL, CONSULTANT_ID_2, USERNAME, null);
@@ -847,7 +849,7 @@ public void sendAssignEnquiryEmailNotification_Should_SendEmail_WhenAllParameter
}
@Test
- public void
+ void
sendAssignEnquiryEmailNotification_Should_LogErrorAndSendNoMails_WhenSenderConsultantIsNotFound() {
when(consultantService.getConsultant(Mockito.anyString())).thenReturn(Optional.empty());
@@ -858,7 +860,7 @@ public void sendAssignEnquiryEmailNotification_Should_SendEmail_WhenAllParameter
}
@Test
- public void sendNewMessageNotification_ShouldNot_LogError_When_SessionStatusIsNew() {
+ void sendNewMessageNotification_ShouldNot_LogError_When_SessionStatusIsNew() {
Session session = mock(Session.class);
when(session.getStatus()).thenReturn(SessionStatus.NEW);
when(session.getUser()).thenReturn(USER);
@@ -871,8 +873,7 @@ public void sendNewMessageNotification_ShouldNot_LogError_When_SessionStatusIsNe
}
@Test
- public void
- sendAssignEnquiryEmailNotification_Should_LogError_When_MailServiceHelperThrowsException() {
+ void sendAssignEnquiryEmailNotification_Should_LogError_When_MailServiceHelperThrowsException() {
doThrow(new RuntimeException("unexpected")).when(mailService).sendEmailNotification(any());
when(consultantService.getConsultant(any())).thenReturn(Optional.of(CONSULTANT));
emailNotificationFacade.sendAssignEnquiryEmailNotification(CONSULTANT, USER_ID, NAME, null);
@@ -880,7 +881,7 @@ public void sendNewMessageNotification_ShouldNot_LogError_When_SessionStatusIsNe
}
@Test
- public void
+ void
sendAssignEnquiryEmailNotification_Should_LogError_When_SessionServiceThrowsRuntimeException() {
when(sessionService.getSessionByFeedbackGroupId(any())).thenThrow(new RuntimeException(""));
@@ -890,7 +891,7 @@ public void sendNewMessageNotification_ShouldNot_LogError_When_SessionStatusIsNe
}
@Test
- public void
+ void
sendNewEnquiryEmailNotification_Should_notSendAnyMail_When_sessionHasAlreadyAConsultantAssigned() {
emailNotificationFacade.sendNewEnquiryEmailNotification(
new EasyRandom().nextObject(Session.class), null);
@@ -899,7 +900,7 @@ public void sendNewMessageNotification_ShouldNot_LogError_When_SessionStatusIsNe
}
@Test
- public void sendReassignRequestNotification_Should_SendEmail_When_askerHasValidMailAddress() {
+ void sendReassignRequestNotification_Should_SendEmail_When_askerHasValidMailAddress() {
var session = new EasyRandom().nextObject(Session.class);
when(sessionService.getSessionByGroupId(any())).thenReturn(session);
session.getUser().setEmail("mail@valid.de");
@@ -914,7 +915,7 @@ public void sendReassignRequestNotification_Should_SendEmail_When_askerHasValidM
}
@Test
- public void sendReassignRequestNotification_ShouldNot_SendEmail_When_askerHasDummyMailAddress() {
+ void sendReassignRequestNotification_ShouldNot_SendEmail_When_askerHasDummyMailAddress() {
var session = new EasyRandom().nextObject(Session.class);
when(sessionService.getSessionByGroupId(any())).thenReturn(session);
session.getUser().setEmail("mail@" + FIELD_VALUE_EMAIL_DUMMY_SUFFIX);
@@ -925,7 +926,7 @@ public void sendReassignRequestNotification_ShouldNot_SendEmail_When_askerHasDum
}
@Test
- public void
+ void
sendReassignRequestNotification_Should_SendEmail_When_NewNotificationModeEnabledAndAskerDoesNotWantToReceiveNotifications() {
var session = new EasyRandom().nextObject(Session.class);
when(sessionService.getSessionByGroupId(any())).thenReturn(session);
@@ -944,7 +945,7 @@ public void sendReassignRequestNotification_ShouldNot_SendEmail_When_askerHasDum
}
@Test
- public void sendReassignConfirmationNotification_Should_sendEmail_When_consultantsExists() {
+ void sendReassignConfirmationNotification_Should_sendEmail_When_consultantsExists() {
var randomConsultant = new EasyRandom().nextObject(Consultant.class);
when(consultantService.getConsultant(any())).thenReturn(Optional.of(randomConsultant));
var reassignmentNotification = new EasyRandom().nextObject(ReassignmentNotificationDTO.class);
@@ -957,7 +958,7 @@ public void sendReassignConfirmationNotification_Should_sendEmail_When_consultan
}
@Test
- public void
+ void
sendReassignConfirmationNotification_Should_sendNotEmail_When_newEmailNotificationsEnabledAndConsultantsDoesNotWantToReceiveNotifications() {
var randomConsultant = new EasyRandom().nextObject(Consultant.class);
when(consultantService.getConsultant(any())).thenReturn(Optional.of(randomConsultant));
@@ -976,7 +977,7 @@ public void sendReassignConfirmationNotification_Should_sendEmail_When_consultan
}
@Test
- public void
+ void
sendReassignConfirmationNotification_Should_sendEmail_When_newEmailNotificationsEnabledAndConsultantsDoesWantsToReceiveNotifications() {
var randomConsultant = new EasyRandom().nextObject(Consultant.class);
when(consultantService.getConsultant(any())).thenReturn(Optional.of(randomConsultant));
@@ -994,12 +995,18 @@ public void sendReassignConfirmationNotification_Should_sendEmail_When_consultan
verifyAsync(a -> mailService.sendEmailNotification(Mockito.any()));
}
- @Test(expected = NotFoundException.class)
- public void
+ @Test
+ void
sendReassignConfirmationNotification_ShouldThrow_NotFoundEception_When_consultantDoesNotExist() {
- var reassignmentNotification = new EasyRandom().nextObject(ReassignmentNotificationDTO.class);
- when(consultantService.getConsultant(any())).thenReturn(Optional.empty());
-
- emailNotificationFacade.sendReassignConfirmationNotification(reassignmentNotification, null);
+ assertThrows(
+ NotFoundException.class,
+ () -> {
+ var reassignmentNotification =
+ new EasyRandom().nextObject(ReassignmentNotificationDTO.class);
+ when(consultantService.getConsultant(any())).thenReturn(Optional.empty());
+
+ emailNotificationFacade.sendReassignConfirmationNotification(
+ reassignmentNotification, null);
+ });
}
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/GetChatFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/GetChatFacadeTest.java
index c31dd342a..d909f1229 100644
--- a/src/test/java/de/caritas/cob/userservice/api/facade/GetChatFacadeTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/facade/GetChatFacadeTest.java
@@ -5,9 +5,7 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.CONSULTANT;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -19,13 +17,13 @@
import de.caritas.cob.userservice.api.helper.ChatPermissionVerifier;
import de.caritas.cob.userservice.api.service.ChatService;
import java.util.Optional;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
-@RunWith(SpringRunner.class)
+@ExtendWith(SpringExtension.class)
public class GetChatFacadeTest {
@InjectMocks private GetChatFacade getChatFacade;
@@ -42,7 +40,7 @@ public void getChat_Should_ThrowNotFoundException_WhenChatDoesNotExist() {
getChatFacade.getChat(CHAT_ID);
fail("Expected exception: NotFoundException");
} catch (NotFoundException notFoundException) {
- assertTrue("Excepted NotFoundException thrown", true);
+ assertTrue(true, "Excepted NotFoundException thrown");
}
verify(chatService, times(1)).getChat(CHAT_ID);
@@ -59,7 +57,7 @@ public void getChat_Should_ThrowRequestForbiddenException_WhenConsultantHasNoPer
getChatFacade.getChat(CHAT_ID);
fail("Expected exception: RequestForbiddenException");
} catch (ForbiddenException requestForbiddenException) {
- assertTrue("Excepted RequestForbiddenException thrown", true);
+ assertTrue(true, "Excepted RequestForbiddenException thrown");
}
verify(chatService, times(1)).getChat(CHAT_ID);
@@ -77,7 +75,7 @@ public void getChat_Should_ThrowRequestForbiddenException_WhenUserHasNoPermissio
getChatFacade.getChat(CHAT_ID);
fail("Expected exception: RequestForbiddenException");
} catch (ForbiddenException requestForbiddenException) {
- assertTrue("Excepted RequestForbiddenException thrown", true);
+ assertTrue(true, "Excepted RequestForbiddenException thrown");
}
verify(chatService, times(1)).getChat(CHAT_ID);
diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/GetChatMembersFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/GetChatMembersFacadeTest.java
index 267624977..249a92024 100644
--- a/src/test/java/de/caritas/cob/userservice/api/facade/GetChatMembersFacadeTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/facade/GetChatMembersFacadeTest.java
@@ -6,8 +6,7 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.GROUP_MEMBER_DTO_LIST;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -29,13 +28,13 @@
import de.caritas.cob.userservice.api.port.out.UserRepository;
import de.caritas.cob.userservice.api.service.ChatService;
import java.util.Optional;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
-@RunWith(SpringRunner.class)
+@ExtendWith(SpringExtension.class)
public class GetChatMembersFacadeTest {
@InjectMocks private GetChatMembersFacade getChatMembersFacade;
@@ -61,7 +60,7 @@ public void getChatMembers_Should_ThrowNotFoundException_WhenChatDoesNotExist()
getChatMembersFacade.getChatMembers(CHAT_ID);
fail("Expected exception: NotFoundException");
} catch (NotFoundException notFoundException) {
- assertTrue("Excepted NotFoundException thrown", true);
+ assertTrue(true, "Excepted NotFoundException thrown");
}
verify(chatService, times(1)).getChat(CHAT_ID);
@@ -77,7 +76,7 @@ public void getChatMembers_Should_ThrowConflictException_WhenChatIsNotActive() {
getChatMembersFacade.getChatMembers(CHAT_ID);
fail("Expected exception: ConflictException");
} catch (ConflictException conflictException) {
- assertTrue("Excepted ConflictException thrown", true);
+ assertTrue(true, "Excepted ConflictException thrown");
}
verify(chatService, times(1)).getChat(CHAT_ID);
@@ -95,7 +94,7 @@ public void getChatMembers_Should_ThrowConflictException_WhenChatIsNotActive() {
getChatMembersFacade.getChatMembers(CHAT_ID);
fail("Expected exception: RequestForbiddenException");
} catch (ForbiddenException requestForbiddenException) {
- assertTrue("Excepted RequestForbiddenException thrown", true);
+ assertTrue(true, "Excepted RequestForbiddenException thrown");
}
verify(chatService, times(1)).getChat(CHAT_ID);
@@ -114,7 +113,7 @@ public void getChatMembers_Should_ThrowConflictException_WhenChatIsNotActive() {
getChatMembersFacade.getChatMembers(CHAT_ID);
fail("Expected exception: RequestForbiddenException");
} catch (ForbiddenException requestForbiddenException) {
- assertTrue("Excepted RequestForbiddenException thrown", true);
+ assertTrue(true, "Excepted RequestForbiddenException thrown");
}
verify(chatService, times(1)).getChat(CHAT_ID);
@@ -153,25 +152,34 @@ public void getChatMembers_Should_ReturnValidChatMembersResponseDTOForConsultant
verify(chatPermissionVerifier, times(1)).verifyPermissionForChat(ACTIVE_CHAT);
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void getChatMembers_Should_throwInternalServerErrorException_When_rocketChatAccessFails()
throws Exception {
- when(chatService.getChat(ACTIVE_CHAT.getId())).thenReturn(Optional.of(ACTIVE_CHAT));
- when(rocketChatService.getStandardMembersOfGroup(ACTIVE_CHAT.getGroupId()))
- .thenThrow(new RocketChatGetGroupMembersException(""));
-
- getChatMembersFacade.getChatMembers(ACTIVE_CHAT.getId());
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(chatService.getChat(ACTIVE_CHAT.getId())).thenReturn(Optional.of(ACTIVE_CHAT));
+ when(rocketChatService.getStandardMembersOfGroup(ACTIVE_CHAT.getGroupId()))
+ .thenThrow(new RocketChatGetGroupMembersException(""));
+
+ getChatMembersFacade.getChatMembers(ACTIVE_CHAT.getId());
+ });
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void getChatMembers_Should_throwInternalServerErrorException_When_rocketChatGroupHasNoId()
throws Exception {
- Chat activeChatWithoutId = new Chat();
- activeChatWithoutId.setActive(true);
- when(chatService.getChat(ACTIVE_CHAT.getId())).thenReturn(Optional.of(activeChatWithoutId));
- when(rocketChatService.getStandardMembersOfGroup(ACTIVE_CHAT.getGroupId()))
- .thenThrow(new RocketChatGetGroupMembersException(""));
-
- getChatMembersFacade.getChatMembers(ACTIVE_CHAT.getId());
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ Chat activeChatWithoutId = new Chat();
+ activeChatWithoutId.setActive(true);
+ when(chatService.getChat(ACTIVE_CHAT.getId()))
+ .thenReturn(Optional.of(activeChatWithoutId));
+ when(rocketChatService.getStandardMembersOfGroup(ACTIVE_CHAT.getGroupId()))
+ .thenThrow(new RocketChatGetGroupMembersException(""));
+
+ getChatMembersFacade.getChatMembers(ACTIVE_CHAT.getId());
+ });
}
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/JoinAndLeaveChatFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/JoinAndLeaveChatFacadeTest.java
index 99e82c437..20a169df0 100644
--- a/src/test/java/de/caritas/cob/userservice/api/facade/JoinAndLeaveChatFacadeTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/facade/JoinAndLeaveChatFacadeTest.java
@@ -4,8 +4,7 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.CHAT_ID;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.CONSULTANT;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.RC_USER_ID;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
@@ -37,14 +36,14 @@
import java.util.List;
import java.util.Optional;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
-public class JoinAndLeaveChatFacadeTest {
+@ExtendWith(MockitoExtension.class)
+class JoinAndLeaveChatFacadeTest {
private static final EasyRandom easyRandom = new EasyRandom();
@@ -67,21 +66,21 @@ public class JoinAndLeaveChatFacadeTest {
@Mock private RocketChatService rocketChatService;
@Test
- public void joinChat_Should_ThrowNotFoundException_WhenChatDoesNotExist() {
+ void joinChat_Should_ThrowNotFoundException_WhenChatDoesNotExist() {
when(chatService.getChat(CHAT_ID)).thenReturn(Optional.empty());
try {
joinAndLeaveChatFacade.joinChat(CHAT_ID, authenticatedUser);
fail("Expected exception: NotFoundException");
} catch (NotFoundException notFoundException) {
- assertTrue("Excepted NotFoundException thrown", true);
+ assertTrue(true, "Excepted NotFoundException thrown");
}
verify(chatService, times(1)).getChat(CHAT_ID);
}
@Test
- public void joinChat_Should_ThrowConflictException_WhenChatIsNotActive() {
+ void joinChat_Should_ThrowConflictException_WhenChatIsNotActive() {
Chat inactiveChat = mock(Chat.class);
when(inactiveChat.isActive()).thenReturn(false);
@@ -91,15 +90,14 @@ public void joinChat_Should_ThrowConflictException_WhenChatIsNotActive() {
joinAndLeaveChatFacade.joinChat(CHAT_ID, authenticatedUser);
fail("Expected exception: ConflictException");
} catch (ConflictException conflictException) {
- assertTrue("Excepted ConflictException thrown", true);
+ assertTrue(true, "Excepted ConflictException thrown");
}
verify(chatService, times(1)).getChat(CHAT_ID);
}
@Test
- public void
- joinChat_Should_ThrowRequestForbiddenException_WhenConsultantHasNoPermissionForChat() {
+ void joinChat_Should_ThrowRequestForbiddenException_WhenConsultantHasNoPermissionForChat() {
when(chatService.getChat(CHAT_ID)).thenReturn(Optional.of(ACTIVE_CHAT));
doThrow(new ForbiddenException(""))
.when(chatPermissionVerifier)
@@ -109,7 +107,7 @@ public void joinChat_Should_ThrowConflictException_WhenChatIsNotActive() {
joinAndLeaveChatFacade.joinChat(CHAT_ID, authenticatedUser);
fail("Expected exception: RequestForbiddenException");
} catch (ForbiddenException requestForbiddenException) {
- assertTrue("Excepted RequestForbiddenException thrown", true);
+ assertTrue(true, "Excepted RequestForbiddenException thrown");
}
verify(chatService, times(1)).getChat(CHAT_ID);
@@ -117,7 +115,7 @@ public void joinChat_Should_ThrowConflictException_WhenChatIsNotActive() {
}
@Test
- public void joinChat_Should_ThrowRequestForbiddenException_WhenUserHasNoPermissionForChat() {
+ void joinChat_Should_ThrowRequestForbiddenException_WhenUserHasNoPermissionForChat() {
when(chatService.getChat(CHAT_ID)).thenReturn(Optional.of(ACTIVE_CHAT));
doThrow(new ForbiddenException(""))
.when(chatPermissionVerifier)
@@ -127,7 +125,7 @@ public void joinChat_Should_ThrowRequestForbiddenException_WhenUserHasNoPermissi
joinAndLeaveChatFacade.joinChat(CHAT_ID, authenticatedUser);
fail("Expected exception: RequestForbiddenException");
} catch (ForbiddenException requestForbiddenException) {
- assertTrue("Excepted RequestForbiddenException thrown", true);
+ assertTrue(true, "Excepted RequestForbiddenException thrown");
}
verify(chatService, times(1)).getChat(CHAT_ID);
@@ -135,7 +133,7 @@ public void joinChat_Should_ThrowRequestForbiddenException_WhenUserHasNoPermissi
}
@Test
- public void joinChat_Should_ThrowInternalServerErrorException_WhenConsultantHasNoRocketChatId() {
+ void joinChat_Should_ThrowInternalServerErrorException_WhenConsultantHasNoRocketChatId() {
when(chatService.getChat(CHAT_ID)).thenReturn(Optional.of(ACTIVE_CHAT));
when(consultantService.getConsultantViaAuthenticatedUser(authenticatedUser))
.thenReturn(Optional.of(consultant));
@@ -145,7 +143,7 @@ public void joinChat_Should_ThrowInternalServerErrorException_WhenConsultantHasN
joinAndLeaveChatFacade.joinChat(CHAT_ID, authenticatedUser);
fail("Expected exception: InternalServerErrorException");
} catch (InternalServerErrorException internalServerErrorException) {
- assertTrue("Excepted InternalServerErrorException thrown", true);
+ assertTrue(true, "Excepted InternalServerErrorException thrown");
}
verify(chatService, times(1)).getChat(CHAT_ID);
@@ -155,7 +153,7 @@ public void joinChat_Should_ThrowInternalServerErrorException_WhenConsultantHasN
}
@Test
- public void joinChat_Should_ThrowInternalServerErrorException_WhenUserHasNoRocketChatId() {
+ void joinChat_Should_ThrowInternalServerErrorException_WhenUserHasNoRocketChatId() {
when(chatService.getChat(CHAT_ID)).thenReturn(Optional.of(ACTIVE_CHAT));
when(userService.getUserViaAuthenticatedUser(authenticatedUser)).thenReturn(Optional.of(user));
when(user.getRcUserId()).thenReturn(null);
@@ -164,7 +162,7 @@ public void joinChat_Should_ThrowInternalServerErrorException_WhenUserHasNoRocke
joinAndLeaveChatFacade.joinChat(CHAT_ID, authenticatedUser);
fail("Expected exception: InternalServerErrorException");
} catch (InternalServerErrorException internalServerErrorException) {
- assertTrue("Excepted InternalServerErrorException thrown", true);
+ assertTrue(true, "Excepted InternalServerErrorException thrown");
}
verify(chatService, times(1)).getChat(CHAT_ID);
@@ -173,8 +171,7 @@ public void joinChat_Should_ThrowInternalServerErrorException_WhenUserHasNoRocke
}
@Test
- public void joinChat_Should_AddConsultantToRocketChatGroup()
- throws RocketChatAddUserToGroupException {
+ void joinChat_Should_AddConsultantToRocketChatGroup() throws RocketChatAddUserToGroupException {
when(chatService.getChat(CHAT_ID)).thenReturn(Optional.of(ACTIVE_CHAT));
when(consultantService.getConsultantViaAuthenticatedUser(authenticatedUser))
.thenReturn(Optional.of(CONSULTANT));
@@ -186,7 +183,7 @@ public void joinChat_Should_AddConsultantToRocketChatGroup()
}
@Test
- public void joinChat_Should_AddUserToRocketChatGroup() throws RocketChatAddUserToGroupException {
+ void joinChat_Should_AddUserToRocketChatGroup() throws RocketChatAddUserToGroupException {
when(chatService.getChat(CHAT_ID)).thenReturn(Optional.of(ACTIVE_CHAT));
when(userService.getUserViaAuthenticatedUser(authenticatedUser)).thenReturn(Optional.of(user));
when(user.getRcUserId()).thenReturn(RC_USER_ID);
@@ -197,21 +194,21 @@ public void joinChat_Should_AddUserToRocketChatGroup() throws RocketChatAddUserT
}
@Test
- public void leaveChat_Should_ThrowNotFoundException_WhenChatDoesNotExist() {
+ void leaveChat_Should_ThrowNotFoundException_WhenChatDoesNotExist() {
when(chatService.getChat(CHAT_ID)).thenReturn(Optional.empty());
try {
joinAndLeaveChatFacade.leaveChat(CHAT_ID, authenticatedUser);
fail("Expected exception: NotFoundException");
} catch (NotFoundException notFoundException) {
- assertTrue("Excepted NotFoundException thrown", true);
+ assertTrue(true, "Excepted NotFoundException thrown");
}
verify(chatService, times(1)).getChat(CHAT_ID);
}
@Test
- public void leaveChat_Should_ThrowConflictException_WhenChatIsNotActive() {
+ void leaveChat_Should_ThrowConflictException_WhenChatIsNotActive() {
Chat inactiveChat = mock(Chat.class);
when(inactiveChat.isActive()).thenReturn(false);
@@ -221,15 +218,14 @@ public void leaveChat_Should_ThrowConflictException_WhenChatIsNotActive() {
joinAndLeaveChatFacade.leaveChat(CHAT_ID, authenticatedUser);
fail("Expected exception: ConflictException");
} catch (ConflictException conflictException) {
- assertTrue("Excepted ConflictException thrown", true);
+ assertTrue(true, "Excepted ConflictException thrown");
}
verify(chatService, times(1)).getChat(CHAT_ID);
}
@Test
- public void
- leaveChat_Should_ThrowRequestForbiddenException_WhenConsultantHasNoPermissionForChat() {
+ void leaveChat_Should_ThrowRequestForbiddenException_WhenConsultantHasNoPermissionForChat() {
when(chatService.getChat(CHAT_ID)).thenReturn(Optional.of(ACTIVE_CHAT));
doThrow(new ForbiddenException(""))
.when(chatPermissionVerifier)
@@ -239,7 +235,7 @@ public void leaveChat_Should_ThrowConflictException_WhenChatIsNotActive() {
joinAndLeaveChatFacade.leaveChat(CHAT_ID, authenticatedUser);
fail("Expected exception: RequestForbiddenException");
} catch (ForbiddenException requestForbiddenException) {
- assertTrue("Excepted RequestForbiddenException thrown", true);
+ assertTrue(true, "Excepted RequestForbiddenException thrown");
}
verify(chatService, times(1)).getChat(CHAT_ID);
@@ -247,7 +243,7 @@ public void leaveChat_Should_ThrowConflictException_WhenChatIsNotActive() {
}
@Test
- public void leaveChat_Should_ThrowRequestForbiddenException_WhenUserHasNoPermissionForChat() {
+ void leaveChat_Should_ThrowRequestForbiddenException_WhenUserHasNoPermissionForChat() {
when(chatService.getChat(CHAT_ID)).thenReturn(Optional.of(ACTIVE_CHAT));
doThrow(new ForbiddenException(""))
.when(chatPermissionVerifier)
@@ -257,7 +253,7 @@ public void leaveChat_Should_ThrowRequestForbiddenException_WhenUserHasNoPermiss
joinAndLeaveChatFacade.leaveChat(CHAT_ID, authenticatedUser);
fail("Expected exception: RequestForbiddenException");
} catch (ForbiddenException requestForbiddenException) {
- assertTrue("Excepted RequestForbiddenException thrown", true);
+ assertTrue(true, "Excepted RequestForbiddenException thrown");
}
verify(chatService, times(1)).getChat(CHAT_ID);
@@ -265,7 +261,7 @@ public void leaveChat_Should_ThrowRequestForbiddenException_WhenUserHasNoPermiss
}
@Test
- public void leaveChat_Should_ThrowInternalServerErrorException_WhenConsultantHasNoRocketChatId() {
+ void leaveChat_Should_ThrowInternalServerErrorException_WhenConsultantHasNoRocketChatId() {
when(chatService.getChat(CHAT_ID)).thenReturn(Optional.of(ACTIVE_CHAT));
when(consultantService.getConsultantViaAuthenticatedUser(authenticatedUser))
.thenReturn(Optional.of(consultant));
@@ -275,7 +271,7 @@ public void leaveChat_Should_ThrowInternalServerErrorException_WhenConsultantHas
joinAndLeaveChatFacade.leaveChat(CHAT_ID, authenticatedUser);
fail("Expected exception: InternalServerErrorException");
} catch (InternalServerErrorException internalServerErrorException) {
- assertTrue("Excepted InternalServerErrorException thrown", true);
+ assertTrue(true, "Excepted InternalServerErrorException thrown");
}
verify(chatService, times(1)).getChat(CHAT_ID);
@@ -285,7 +281,7 @@ public void leaveChat_Should_ThrowInternalServerErrorException_WhenConsultantHas
}
@Test
- public void leaveChat_Should_ThrowInternalServerErrorException_WhenUserHasNoRocketChatId() {
+ void leaveChat_Should_ThrowInternalServerErrorException_WhenUserHasNoRocketChatId() {
when(chatService.getChat(CHAT_ID)).thenReturn(Optional.of(ACTIVE_CHAT));
when(userService.getUserViaAuthenticatedUser(authenticatedUser)).thenReturn(Optional.of(user));
when(user.getRcUserId()).thenReturn(null);
@@ -294,7 +290,7 @@ public void leaveChat_Should_ThrowInternalServerErrorException_WhenUserHasNoRock
joinAndLeaveChatFacade.leaveChat(CHAT_ID, authenticatedUser);
fail("Expected exception: InternalServerErrorException");
} catch (InternalServerErrorException internalServerErrorException) {
- assertTrue("Excepted InternalServerErrorException thrown", true);
+ assertTrue(true, "Excepted InternalServerErrorException thrown");
}
verify(chatService, times(1)).getChat(CHAT_ID);
@@ -303,7 +299,7 @@ public void leaveChat_Should_ThrowInternalServerErrorException_WhenUserHasNoRock
}
@Test
- public void leaveChat_Should_RemoveConsultantFromRocketChatGroup()
+ void leaveChat_Should_RemoveConsultantFromRocketChatGroup()
throws RocketChatRemoveUserFromGroupException, RocketChatUserNotInitializedException,
RocketChatGetGroupMembersException {
when(chatService.getChat(CHAT_ID)).thenReturn(Optional.of(ACTIVE_CHAT));
@@ -318,22 +314,26 @@ public void leaveChat_Should_RemoveConsultantFromRocketChatGroup()
.removeUserFromGroup(CONSULTANT.getRocketChatId(), ACTIVE_CHAT.getGroupId());
}
- @Test(expected = InternalServerErrorException.class)
- public void
- leaveChat_Should_throwInternalServerErrorException_When_rocketChatUserCanNotBeRemoved()
- throws RocketChatRemoveUserFromGroupException {
- when(chatService.getChat(CHAT_ID)).thenReturn(Optional.of(ACTIVE_CHAT));
- when(userService.getUserViaAuthenticatedUser(authenticatedUser)).thenReturn(Optional.of(user));
- when(user.getRcUserId()).thenReturn(RC_USER_ID);
- doThrow(new RocketChatRemoveUserFromGroupException(""))
- .when(rocketChatService)
- .removeUserFromGroup(any(), any());
-
- joinAndLeaveChatFacade.leaveChat(ACTIVE_CHAT.getId(), authenticatedUser);
+ @Test
+ void leaveChat_Should_throwInternalServerErrorException_When_rocketChatUserCanNotBeRemoved()
+ throws RocketChatRemoveUserFromGroupException {
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(chatService.getChat(CHAT_ID)).thenReturn(Optional.of(ACTIVE_CHAT));
+ when(userService.getUserViaAuthenticatedUser(authenticatedUser))
+ .thenReturn(Optional.of(user));
+ when(user.getRcUserId()).thenReturn(RC_USER_ID);
+ doThrow(new RocketChatRemoveUserFromGroupException(""))
+ .when(rocketChatService)
+ .removeUserFromGroup(any(), any());
+
+ joinAndLeaveChatFacade.leaveChat(ACTIVE_CHAT.getId(), authenticatedUser);
+ });
}
@Test
- public void leaveChatShouldNotDeleteChatsWhenStandardMemberInChat()
+ void leaveChatShouldNotDeleteChatsWhenStandardMemberInChat()
throws RocketChatUserNotInitializedException, RocketChatGetGroupMembersException {
when(chatService.getChat(CHAT_ID)).thenReturn(Optional.of(ACTIVE_CHAT));
when(userService.getUserViaAuthenticatedUser(authenticatedUser)).thenReturn(Optional.of(user));
diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/RocketChatFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/RocketChatFacadeTest.java
index 66ae65fdf..a00ab6503 100644
--- a/src/test/java/de/caritas/cob/userservice/api/facade/RocketChatFacadeTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/facade/RocketChatFacadeTest.java
@@ -2,6 +2,7 @@
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
@@ -17,13 +18,13 @@
import de.caritas.cob.userservice.api.exception.rocketchat.RocketChatLeaveFromGroupException;
import de.caritas.cob.userservice.api.exception.rocketchat.RocketChatRemoveSystemMessagesException;
import de.caritas.cob.userservice.api.exception.rocketchat.RocketChatRemoveUserFromGroupException;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class RocketChatFacadeTest {
@InjectMocks private RocketChatFacade rocketChatFacade;
@@ -39,15 +40,19 @@ public void addUserToRocketChatGroup_Should_addUserToGroup() throws Exception {
verify(this.rocketChatService, times(1)).leaveFromGroupAsTechnicalUser("group");
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
addUserToRocketChatGroup_Should_throwInternalServerErrorException_When_RocketChatAddUserToGroupExceptionIsThrown()
throws RocketChatAddUserToGroupException {
- doThrow(new RocketChatAddUserToGroupException(""))
- .when(this.rocketChatService)
- .addUserToGroup(anyString(), anyString());
-
- this.rocketChatFacade.addUserToRocketChatGroup("user", "group");
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ doThrow(new RocketChatAddUserToGroupException(""))
+ .when(this.rocketChatService)
+ .addUserToGroup(anyString(), anyString());
+
+ this.rocketChatFacade.addUserToRocketChatGroup("user", "group");
+ });
}
@Test
@@ -61,15 +66,19 @@ public void addUserToRocketChatGroup_Should_addUserToGroup() throws Exception {
verify(this.rocketChatService, times(1)).leaveFromGroupAsTechnicalUser("group");
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
removeSystemMessagesFromRocketChatGroup_Should_throwInternalServerErrorException_When_RocketChatRemoveSystemMessagesExceptionIsThrown()
throws Exception {
- doThrow(new RocketChatRemoveSystemMessagesException(""))
- .when(this.rocketChatService)
- .removeSystemMessages(anyString(), any(), any());
-
- this.rocketChatFacade.removeSystemMessagesFromRocketChatGroup("group");
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ doThrow(new RocketChatRemoveSystemMessagesException(""))
+ .when(this.rocketChatService)
+ .removeSystemMessages(anyString(), any(), any());
+
+ this.rocketChatFacade.removeSystemMessagesFromRocketChatGroup("group");
+ });
}
@Test
@@ -81,12 +90,18 @@ public void retrieveRocketChatMembers_Should_retrieveRocketChatMembers() throws
verify(this.rocketChatService, times(1)).leaveFromGroupAsTechnicalUser("group");
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
retrieveRocketChatMembers_Should_throwInternalServerErrorException_When_RocketChatGetGroupMembersException() {
- doThrow(new MongoClientException("")).when(this.rocketChatService).getChatUsers(anyString());
-
- this.rocketChatFacade.retrieveRocketChatMembers("group");
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ doThrow(new MongoClientException(""))
+ .when(this.rocketChatService)
+ .getChatUsers(anyString());
+
+ this.rocketChatFacade.retrieveRocketChatMembers("group");
+ });
}
@Test
@@ -96,15 +111,19 @@ public void addTechnicalUserToGroup_Should_addTechnicalUserToGroup() throws Exce
verify(this.rocketChatService, times(1)).addTechnicalUserToGroup("group");
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
addTechnicalUserToGroup_Should_throwInternalServerErrorException_When_RocketChatGetGroupMembersException()
throws Exception {
- doThrow(new RocketChatAddUserToGroupException(""))
- .when(this.rocketChatService)
- .addTechnicalUserToGroup(anyString());
-
- this.rocketChatFacade.addTechnicalUserToGroup("group");
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ doThrow(new RocketChatAddUserToGroupException(""))
+ .when(this.rocketChatService)
+ .addTechnicalUserToGroup(anyString());
+
+ this.rocketChatFacade.addTechnicalUserToGroup("group");
+ });
}
@Test
@@ -115,15 +134,19 @@ public void leaveFromGroupAsTechnicalUser_Should_leaveFromGroupAsTechnicalUser()
verify(this.rocketChatService, times(1)).leaveFromGroupAsTechnicalUser("group");
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
leaveFromGroupAsTechnicalUser_Should_throwInternalServerErrorException_When_RocketChatLeaveFromGroupException()
throws Exception {
- doThrow(new RocketChatLeaveFromGroupException(""))
- .when(this.rocketChatService)
- .leaveFromGroupAsTechnicalUser(anyString());
-
- this.rocketChatFacade.leaveFromGroupAsTechnicalUser("group");
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ doThrow(new RocketChatLeaveFromGroupException(""))
+ .when(this.rocketChatService)
+ .leaveFromGroupAsTechnicalUser(anyString());
+
+ this.rocketChatFacade.leaveFromGroupAsTechnicalUser("group");
+ });
}
@Test
@@ -133,15 +156,19 @@ public void removeUserFromGroup_Should_removeUserFromGroup() throws Exception {
verify(this.rocketChatService, times(1)).removeUserFromGroup("user", "group");
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
removeUserFromGroup_Should_throwInternalServerErrorException_When_RocketChatRemoveUserFromGroupExceptionIsThrown()
throws Exception {
- doThrow(new RocketChatRemoveUserFromGroupException(""))
- .when(this.rocketChatService)
- .removeUserFromGroup(anyString(), anyString());
-
- this.rocketChatFacade.removeUserFromGroup("user", "group");
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ doThrow(new RocketChatRemoveUserFromGroupException(""))
+ .when(this.rocketChatService)
+ .removeUserFromGroup(anyString(), anyString());
+
+ this.rocketChatFacade.removeUserFromGroup("user", "group");
+ });
}
@Test
@@ -151,14 +178,18 @@ public void getStandardMembersOfGroup_Should_getStandardMembersOfGroup() throws
verify(this.rocketChatService, times(1)).getStandardMembersOfGroup("group");
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void getStandardMembersOfGroup_Should_throwInternalServerError_When_rocketChatAccessFails()
throws Exception {
- doThrow(new RocketChatGetGroupMembersException(""))
- .when(this.rocketChatService)
- .getStandardMembersOfGroup(any());
-
- this.rocketChatFacade.getStandardMembersOfGroup("");
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ doThrow(new RocketChatGetGroupMembersException(""))
+ .when(this.rocketChatService)
+ .getStandardMembersOfGroup(any());
+
+ this.rocketChatFacade.getStandardMembersOfGroup("");
+ });
}
@Test
diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/SessionArchiveServiceIT.java b/src/test/java/de/caritas/cob/userservice/api/facade/SessionArchiveServiceIT.java
index d67afa7ea..96fb19459 100644
--- a/src/test/java/de/caritas/cob/userservice/api/facade/SessionArchiveServiceIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/facade/SessionArchiveServiceIT.java
@@ -2,6 +2,7 @@
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -20,8 +21,7 @@
import de.caritas.cob.userservice.api.testConfig.ConsultingTypeManagerTestConfig;
import java.util.Optional;
import java.util.UUID;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
@@ -29,9 +29,7 @@
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
-@RunWith(SpringRunner.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
@@ -56,36 +54,50 @@ public void archiveSession_Should_ChangeStatusOfSession_WhenConsultantHasPermiss
assertThat(session.get().getStatus(), is(SessionStatus.IN_ARCHIVE));
}
- @Test(expected = NotFoundException.class)
+ @Test
public void archiveSession_Should_ThrowNotFoundException_WhenSessionIsNotFound() {
- sessionArchiveService.archiveSession(99999999L);
+ assertThrows(
+ NotFoundException.class,
+ () -> {
+ sessionArchiveService.archiveSession(99999999L);
+ });
}
- @Test(expected = ForbiddenException.class)
+ @Test
public void archiveSession_Should_ThrowForbiddenException_WhenConsultantHasNoPermission() {
-
- when(authenticatedUser.getUserId()).thenReturn("88613f5d-0d40-47e0-b323-e792e7fba3ed");
- when(authenticatedUser.isConsultant()).thenReturn(true);
- sessionArchiveService.archiveSession(1L);
-
- verify(sessionRepository, times(0)).save(any());
+ assertThrows(
+ ForbiddenException.class,
+ () -> {
+ when(authenticatedUser.getUserId()).thenReturn("88613f5d-0d40-47e0-b323-e792e7fba3ed");
+ when(authenticatedUser.isConsultant()).thenReturn(true);
+ sessionArchiveService.archiveSession(1L);
+
+ verify(sessionRepository, times(0)).save(any());
+ });
}
- @Test(expected = ForbiddenException.class)
+ @Test
public void archiveSession_Should_ThrowForbiddenException_WhenUserHasNoPermission() {
-
- when(authenticatedUser.getUserId()).thenReturn("88613f5d-0d40-47e0-b323-e792e7fba3ed");
- when(authenticatedUser.isAdviceSeeker()).thenReturn(true);
- sessionArchiveService.archiveSession(1L);
-
- verify(sessionRepository, times(0)).save(any());
+ assertThrows(
+ ForbiddenException.class,
+ () -> {
+ when(authenticatedUser.getUserId()).thenReturn("88613f5d-0d40-47e0-b323-e792e7fba3ed");
+ when(authenticatedUser.isAdviceSeeker()).thenReturn(true);
+ sessionArchiveService.archiveSession(1L);
+
+ verify(sessionRepository, times(0)).save(any());
+ });
}
- @Test(expected = ConflictException.class)
+ @Test
public void archiveSession_Should_ThrowConflictException_WhenSessionIsNotInProgress() {
- when(authenticatedUser.getUserId()).thenReturn("75abe824-fb42-476d-a52a-66660113bdcc");
+ assertThrows(
+ ConflictException.class,
+ () -> {
+ when(authenticatedUser.getUserId()).thenReturn("75abe824-fb42-476d-a52a-66660113bdcc");
- sessionArchiveService.archiveSession(1214L);
+ sessionArchiveService.archiveSession(1214L);
+ });
}
@Test
@@ -114,21 +126,33 @@ public void reactivateSession_Should_ChangeStatusOfSession_WhenUserHasPermission
assertThat(session.get().getStatus(), is(SessionStatus.IN_PROGRESS));
}
- @Test(expected = NotFoundException.class)
+ @Test
public void reactivateSession_Should_ThrowNotFoundException_WhenSessionIsNotFound() {
- sessionArchiveService.dearchiveSession(99999999L);
+ assertThrows(
+ NotFoundException.class,
+ () -> {
+ sessionArchiveService.dearchiveSession(99999999L);
+ });
}
- @Test(expected = ForbiddenException.class)
+ @Test
public void reactivateSession_Should_ThrowForbiddenException_WhenUserHasNoPermission() {
- when(authenticatedUser.getUserId()).thenReturn(UUID.randomUUID().toString());
- sessionArchiveService.dearchiveSession(1210L);
+ assertThrows(
+ ForbiddenException.class,
+ () -> {
+ when(authenticatedUser.getUserId()).thenReturn(UUID.randomUUID().toString());
+ sessionArchiveService.dearchiveSession(1210L);
+ });
}
- @Test(expected = ConflictException.class)
+ @Test
public void reactivateSession_Should_ThrowConflictException_WhenSessionIsNotInArchive() {
- when(authenticatedUser.getUserId()).thenReturn("473f7c4b-f011-4fc2-847c-ceb636a5b399");
- when(authenticatedUser.isConsultant()).thenReturn(true);
- sessionArchiveService.dearchiveSession(1L);
+ assertThrows(
+ ConflictException.class,
+ () -> {
+ when(authenticatedUser.getUserId()).thenReturn("473f7c4b-f011-4fc2-847c-ceb636a5b399");
+ when(authenticatedUser.isConsultant()).thenReturn(true);
+ sessionArchiveService.dearchiveSession(1L);
+ });
}
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/StartChatFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/StartChatFacadeTest.java
index 0f0f73fb4..ce2fc4a46 100644
--- a/src/test/java/de/caritas/cob/userservice/api/facade/StartChatFacadeTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/facade/StartChatFacadeTest.java
@@ -4,8 +4,7 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.CONSULTANT;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.INACTIVE_CHAT;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.RC_GROUP_ID;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
@@ -20,13 +19,13 @@
import de.caritas.cob.userservice.api.helper.ChatPermissionVerifier;
import de.caritas.cob.userservice.api.model.Chat;
import de.caritas.cob.userservice.api.service.ChatService;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class StartChatFacadeTest {
@InjectMocks private StartChatFacade startChatFacade;
@@ -48,7 +47,7 @@ public class StartChatFacadeTest {
startChatFacade.startChat(ACTIVE_CHAT, CONSULTANT);
fail("Expected exception: RequestForbiddenException");
} catch (ForbiddenException sequestForbiddenException) {
- assertTrue("Excepted RequestForbiddenException thrown", true);
+ assertTrue(true, "Excepted RequestForbiddenException thrown");
}
}
@@ -60,7 +59,7 @@ public void startChat_Should_ThrowConflictException_WhenChatIsAlreadyStarted() {
startChatFacade.startChat(ACTIVE_CHAT, CONSULTANT);
fail("Expected exception: ConflictException");
} catch (ConflictException conflictException) {
- assertTrue("Excepted ConflictException thrown", true);
+ assertTrue(true, "Excepted ConflictException thrown");
}
}
@@ -75,7 +74,7 @@ public void startChat_Should_ThrowInternalServerError_WhenChatHasNoGroupId() {
startChatFacade.startChat(chat, CONSULTANT);
fail("Expected exception: InternalServerErrorException");
} catch (InternalServerErrorException internalServerErrorException) {
- assertTrue("Excepted InternalServerErrorException thrown", true);
+ assertTrue(true, "Excepted InternalServerErrorException thrown");
}
}
@@ -101,19 +100,23 @@ public void startChat_Should_SetChatActiveAndSaveChat() {
verify(chatService, times(1)).saveChat(chat);
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
startChat_Should_throwInternalServerErrorException_When_userCanNotBeAddedToGroupInRocketChat()
throws RocketChatAddUserToGroupException {
- when(chat.getGroupId()).thenReturn(RC_GROUP_ID);
- when(chatPermissionVerifier.hasSameAgencyAssigned(chat, CONSULTANT)).thenReturn(true);
- doThrow(new RocketChatAddUserToGroupException(""))
- .when(rocketChatService)
- .addUserToGroup(any(), any());
-
- startChatFacade.startChat(chat, CONSULTANT);
-
- verify(chat, times(1)).setActive(true);
- verify(chatService, times(1)).saveChat(chat);
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(chat.getGroupId()).thenReturn(RC_GROUP_ID);
+ when(chatPermissionVerifier.hasSameAgencyAssigned(chat, CONSULTANT)).thenReturn(true);
+ doThrow(new RocketChatAddUserToGroupException(""))
+ .when(rocketChatService)
+ .addUserToGroup(any(), any());
+
+ startChatFacade.startChat(chat, CONSULTANT);
+
+ verify(chat, times(1)).setActive(true);
+ verify(chatService, times(1)).saveChat(chat);
+ });
}
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/StopChatFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/StopChatFacadeTest.java
index 05f507e14..5216fdd79 100644
--- a/src/test/java/de/caritas/cob/userservice/api/facade/StopChatFacadeTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/facade/StopChatFacadeTest.java
@@ -2,8 +2,8 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.ACTIVE_CHAT;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.CONSULTANT;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -14,15 +14,18 @@
import de.caritas.cob.userservice.api.exception.httpresponses.ForbiddenException;
import de.caritas.cob.userservice.api.helper.ChatPermissionVerifier;
import de.caritas.cob.userservice.api.model.Chat;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
-@RunWith(MockitoJUnitRunner.class)
-public class StopChatFacadeTest {
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
+class StopChatFacadeTest {
@InjectMocks private StopChatFacade stopChatFacade;
@@ -32,27 +35,26 @@ public class StopChatFacadeTest {
private final ActionCommandMockProvider mockProvider = new ActionCommandMockProvider();
- @Before
- public void setup() {
+ @BeforeEach
+ void setup() {
when(this.actionsRegistry.buildContainerForType(Chat.class))
.thenReturn(mockProvider.getActionContainer(Chat.class));
}
@Test
- public void
- stopChat_Should_ThrowRequestForbiddenException_When_ConsultantHasNoPermissionToStopChat() {
+ void stopChat_Should_ThrowRequestForbiddenException_When_ConsultantHasNoPermissionToStopChat() {
when(chatPermissionVerifier.hasSameAgencyAssigned(ACTIVE_CHAT, CONSULTANT)).thenReturn(false);
try {
stopChatFacade.stopChat(ACTIVE_CHAT, CONSULTANT);
fail("Expected exception: RequestForbiddenException");
} catch (ForbiddenException sequestForbiddenException) {
- assertTrue("Excepted RequestForbiddenException thrown", true);
+ assertTrue(true, "Excepted RequestForbiddenException thrown");
}
}
@Test
- public void stopChat_Should_executeExpectedAction_When_ConsultantHasPermissionToStopChat() {
+ void stopChat_Should_executeExpectedAction_When_ConsultantHasPermissionToStopChat() {
when(chatPermissionVerifier.hasSameAgencyAssigned(ACTIVE_CHAT, CONSULTANT)).thenReturn(true);
stopChatFacade.stopChat(ACTIVE_CHAT, CONSULTANT);
diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignSessionFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignSessionFacadeTest.java
index 019c03fb1..afc02c6a0 100644
--- a/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignSessionFacadeTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignSessionFacadeTest.java
@@ -54,14 +54,14 @@
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.RandomStringUtils;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class AssignSessionFacadeTest {
private static final EasyRandom easyRandom = new EasyRandom();
diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/UnauthorizedMembersProviderTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/UnauthorizedMembersProviderTest.java
index a3c41db31..df5d2add1 100644
--- a/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/UnauthorizedMembersProviderTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/UnauthorizedMembersProviderTest.java
@@ -13,7 +13,8 @@
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.when;
import static org.springframework.test.util.ReflectionTestUtils.setField;
@@ -29,15 +30,18 @@
import java.util.List;
import java.util.Optional;
import org.jeasy.random.EasyRandom;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
-@RunWith(MockitoJUnitRunner.class)
-public class UnauthorizedMembersProviderTest {
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
+class UnauthorizedMembersProviderTest {
@InjectMocks UnauthorizedMembersProvider unauthorizedMembersProvider;
@@ -59,8 +63,8 @@ public class UnauthorizedMembersProviderTest {
RocketChatCredentials techUserRcCredentials = easyRandom.nextObject(RocketChatCredentials.class);
List initialMemberList;
- @Before
- public void setup() throws NoSuchFieldException, SecurityException {
+ @BeforeEach
+ void setup() throws NoSuchFieldException, SecurityException {
setField(
unauthorizedMembersProvider,
FIELD_NAME_ROCKET_CHAT_SYSTEM_USER_ID,
@@ -113,7 +117,7 @@ public void setup() throws NoSuchFieldException, SecurityException {
}
@Test
- public void obtainConsultantsToRemoveShouldNotIncludeConsultantToAssignIfNotAssignedAlready()
+ void obtainConsultantsToRemoveShouldNotIncludeConsultantToAssignIfNotAssignedAlready()
throws RocketChatUserNotInitializedException {
var consultant = easyRandom.nextObject(Consultant.class);
@@ -131,7 +135,7 @@ public void obtainConsultantsToRemoveShouldNotIncludeConsultantToAssignIfNotAssi
}
@Test
- public void obtainConsultantsToRemoveShouldNotIncludeConsultantToAssignIfAlreadyAssigned()
+ void obtainConsultantsToRemoveShouldNotIncludeConsultantToAssignIfAlreadyAssigned()
throws RocketChatUserNotInitializedException {
var consultant = easyRandom.nextObject(Consultant.class);
@@ -154,7 +158,7 @@ public void obtainConsultantsToRemoveShouldNotIncludeConsultantToAssignIfAlready
}
@Test
- public void obtainConsultantsToRemoveShouldNotIncludeConsultantToKeep()
+ void obtainConsultantsToRemoveShouldNotIncludeConsultantToKeep()
throws RocketChatUserNotInitializedException {
var consultant = easyRandom.nextObject(Consultant.class);
@@ -186,7 +190,7 @@ public void obtainConsultantsToRemoveShouldNotIncludeConsultantToKeep()
}
@Test
- public void
+ void
obtainConsultantsToRemove_Should_ReturnCorrectUnauthorizedMemberList_When_SessionIsNoTeamSession()
throws RocketChatUserNotInitializedException {
newConsultant.setTeamConsultant(false);
@@ -210,7 +214,7 @@ public void obtainConsultantsToRemoveShouldNotIncludeConsultantToKeep()
}
@Test
- public void
+ void
obtainConsultantsToRemove_Should_ReturnCorrectUnauthorizedMemberList_When_SessionIsNormalTeamSession()
throws RocketChatUserNotInitializedException {
newConsultant.setTeamConsultant(true);
@@ -237,7 +241,7 @@ public void obtainConsultantsToRemoveShouldNotIncludeConsultantToKeep()
}
@Test
- public void
+ void
obtainConsultantsToRemove_Should_ReturnCorrectUnauthorizedMemberList_When_SessionIsFeedbackSessionForNormalGroup()
throws RocketChatUserNotInitializedException {
newConsultant.setTeamConsultant(true);
@@ -279,7 +283,7 @@ public void obtainConsultantsToRemoveShouldNotIncludeConsultantToKeep()
}
@Test
- public void
+ void
obtainConsultantsToRemove_Should_ReturnCorrectUnauthorizedMemberList_When_SessionIsFeedbackSessionForFeedbackGroup()
throws RocketChatUserNotInitializedException {
newConsultant.setTeamConsultant(true);
@@ -316,14 +320,20 @@ public void obtainConsultantsToRemoveShouldNotIncludeConsultantToKeep()
normalConsultant, teamConsultant, teamConsultant2, peerConsultant, peerConsultant2));
}
- @Test(expected = InternalServerErrorException.class)
- public void
- obtainConsultantsToRemove_Should_ThrowInternalServerError_When_TechUserIsNotInitialized()
- throws RocketChatUserNotInitializedException {
- when(rocketChatCredentialsProvider.getTechnicalUser())
- .thenThrow(new RocketChatUserNotInitializedException(""));
-
- unauthorizedMembersProvider.obtainConsultantsToRemove(
- RC_GROUP_ID, FEEDBACK_SESSION_WITH_ASKER_AND_CONSULTANT, newConsultant, initialMemberList);
+ @Test
+ void obtainConsultantsToRemove_Should_ThrowInternalServerError_When_TechUserIsNotInitialized()
+ throws RocketChatUserNotInitializedException {
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(rocketChatCredentialsProvider.getTechnicalUser())
+ .thenThrow(new RocketChatUserNotInitializedException(""));
+
+ unauthorizedMembersProvider.obtainConsultantsToRemove(
+ RC_GROUP_ID,
+ FEEDBACK_SESSION_WITH_ASKER_AND_CONSULTANT,
+ newConsultant,
+ initialMemberList);
+ });
}
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/conversation/CreateAnonymousEnquiryFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/conversation/CreateAnonymousEnquiryFacadeTest.java
index 92e1d66f7..962e9e0f7 100644
--- a/src/test/java/de/caritas/cob/userservice/api/facade/conversation/CreateAnonymousEnquiryFacadeTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/facade/conversation/CreateAnonymousEnquiryFacadeTest.java
@@ -2,6 +2,7 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.CONSULTING_TYPE_ID_KREUZBUND;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.CONSULTING_TYPE_ID_SUCHT;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -20,13 +21,13 @@
import de.caritas.cob.userservice.api.model.Session;
import de.caritas.cob.userservice.consultingtypeservice.generated.web.model.ExtendedConsultingTypeResponseDTO;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
-@RunWith(SpringRunner.class)
+@ExtendWith(SpringExtension.class)
public class CreateAnonymousEnquiryFacadeTest {
@InjectMocks private CreateAnonymousEnquiryFacade createAnonymousEnquiryFacade;
@@ -38,23 +39,29 @@ public class CreateAnonymousEnquiryFacadeTest {
EasyRandom easyRandom = new EasyRandom();
- @Test(expected = BadRequestException.class)
+ @Test
public void
createAnonymousEnquiry_Should_ThrowBadRequestException_When_GivenConsultingTypeDoesNotSupportAnonymousConversations() {
- CreateAnonymousEnquiryDTO anonymousEnquiryDTO =
- easyRandom.nextObject(CreateAnonymousEnquiryDTO.class);
- anonymousEnquiryDTO.setConsultingType(CONSULTING_TYPE_ID_KREUZBUND);
- var consultingTypeResponseDTO = easyRandom.nextObject(ExtendedConsultingTypeResponseDTO.class);
- consultingTypeResponseDTO.setIsAnonymousConversationAllowed(false);
- when(consultingTypeManager.getConsultingTypeSettings(anonymousEnquiryDTO.getConsultingType()))
- .thenReturn(consultingTypeResponseDTO);
+ assertThrows(
+ BadRequestException.class,
+ () -> {
+ CreateAnonymousEnquiryDTO anonymousEnquiryDTO =
+ easyRandom.nextObject(CreateAnonymousEnquiryDTO.class);
+ anonymousEnquiryDTO.setConsultingType(CONSULTING_TYPE_ID_KREUZBUND);
+ var consultingTypeResponseDTO =
+ easyRandom.nextObject(ExtendedConsultingTypeResponseDTO.class);
+ consultingTypeResponseDTO.setIsAnonymousConversationAllowed(false);
+ when(consultingTypeManager.getConsultingTypeSettings(
+ anonymousEnquiryDTO.getConsultingType()))
+ .thenReturn(consultingTypeResponseDTO);
- createAnonymousEnquiryFacade.createAnonymousEnquiry(anonymousEnquiryDTO);
+ createAnonymousEnquiryFacade.createAnonymousEnquiry(anonymousEnquiryDTO);
- verifyNoInteractions(anonymousUserCreatorService);
- verifyNoInteractions(anonymousConversationCreatorService);
- verifyNoInteractions(usernameRegistry);
- verifyNoInteractions(userHelper);
+ verifyNoInteractions(anonymousUserCreatorService);
+ verifyNoInteractions(anonymousConversationCreatorService);
+ verifyNoInteractions(usernameRegistry);
+ verifyNoInteractions(userHelper);
+ });
}
@Test
diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/rollback/RollbackFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/rollback/RollbackFacadeTest.java
index 63117d8c9..60472b079 100644
--- a/src/test/java/de/caritas/cob/userservice/api/facade/rollback/RollbackFacadeTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/facade/rollback/RollbackFacadeTest.java
@@ -14,13 +14,13 @@
import de.caritas.cob.userservice.api.service.user.UserService;
import de.caritas.cob.userservice.api.workflow.delete.service.DeleteUserAccountService;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class RollbackFacadeTest {
@InjectMocks private RollbackFacade rollbackFacade;
diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/sessionlist/RocketChatRoomInformationProviderTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/sessionlist/RocketChatRoomInformationProviderTest.java
index 5bc1ecfbb..4c1ab78d5 100644
--- a/src/test/java/de/caritas/cob/userservice/api/facade/sessionlist/RocketChatRoomInformationProviderTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/facade/sessionlist/RocketChatRoomInformationProviderTest.java
@@ -13,10 +13,7 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.SUBSCRIPTIONS_UPDATE_LIST_DTO_WITH_ONE_FEEDBACK_UNREAD;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USERS_ROOMS_LIST;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USER_DTO_3;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when;
import de.caritas.cob.userservice.api.adapters.rocketchat.RocketChatService;
@@ -26,13 +23,13 @@
import java.util.Date;
import java.util.Objects;
import org.apache.commons.collections.CollectionUtils;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class RocketChatRoomInformationProviderTest {
@InjectMocks private RocketChatRoomInformationProvider rocketChatRoomInformationProvider;
diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/sessionlist/SessionListFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/sessionlist/SessionListFacadeTest.java
index 173b82d69..24165b61a 100644
--- a/src/test/java/de/caritas/cob/userservice/api/facade/sessionlist/SessionListFacadeTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/facade/sessionlist/SessionListFacadeTest.java
@@ -14,9 +14,7 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USER_ID;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USER_SESSION_RESPONSE_SESSION_CHAT_DTO_LIST;
import static java.util.Objects.nonNull;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when;
import de.caritas.cob.userservice.api.adapters.web.dto.ConsultantSessionListResponseDTO;
@@ -29,16 +27,16 @@
import de.caritas.cob.userservice.api.service.session.SessionTopicEnrichmentService;
import de.caritas.cob.userservice.api.service.sessionlist.ConsultantSessionListService;
import de.caritas.cob.userservice.api.service.sessionlist.UserSessionListService;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.util.ReflectionTestUtils;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class SessionListFacadeTest {
@InjectMocks private SessionListFacade sessionListFacade;
@@ -47,7 +45,7 @@ public class SessionListFacadeTest {
@Mock private SessionTopicEnrichmentService sessionTopicEnrichmentService;
/** Method: retrieveSessionsForAuthenticatedUser */
- @Before
+ @BeforeEach
public void setUp() {
ReflectionTestUtils.setField(
sessionListFacade, "sessionTopicEnrichmentService", sessionTopicEnrichmentService);
diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/userdata/AskerDataProviderTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/userdata/AskerDataProviderTest.java
index 912322dc7..18c19df85 100644
--- a/src/test/java/de/caritas/cob/userservice/api/facade/userdata/AskerDataProviderTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/facade/userdata/AskerDataProviderTest.java
@@ -9,11 +9,7 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USER;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USER_WITH_SESSIONS;
import static org.hibernate.validator.internal.util.CollectionHelper.asSet;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -37,15 +33,15 @@
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
-public class AskerDataProviderTest {
+@ExtendWith(MockitoExtension.class)
+class AskerDataProviderTest {
@InjectMocks private AskerDataProvider askerDataProvider;
@@ -62,8 +58,7 @@ public class AskerDataProviderTest {
@Mock EmailNotificationMapper emailNotificationMapper;
@Test
- public void
- retrieveData_Should_ReturnUserDataWithAgency_When_ProvidedWithUserWithAgencyInSession() {
+ void retrieveData_Should_ReturnUserDataWithAgency_When_ProvidedWithUserWithAgencyInSession() {
givenAnEmailDummySuffixConfig();
when(authenticatedUser.getRoles()).thenReturn(asSet(UserRole.USER.getValue()));
when(agencyService.getAgencies(Mockito.anyList()))
@@ -84,7 +79,7 @@ public class AskerDataProviderTest {
}
@Test
- public void retrieveData_Should_ReturnUserDataWithAgency_When_ProvidedWithUserWithAgencies() {
+ void retrieveData_Should_ReturnUserDataWithAgency_When_ProvidedWithUserWithAgencies() {
givenAnEmailDummySuffixConfig();
when(authenticatedUser.getRoles()).thenReturn(asSet(UserRole.USER.getValue()));
when(agencyService.getAgencies(Mockito.anyList()))
@@ -104,20 +99,23 @@ public void retrieveData_Should_ReturnUserDataWithAgency_When_ProvidedWithUserWi
assertEquals(AGENCY_DTO_KREUZBUND, agency);
}
- @Test(expected = InternalServerErrorException.class)
- public void
+ @Test
+ void
retrieveData_GetConsultingTypes_Should_ThrowInternalServerErrorException_When_AgencyServiceHelperFails() {
- givenAnEmailDummySuffixConfig();
- when(authenticatedUser.getRoles()).thenReturn(asSet(UserRole.USER.getValue()));
- when(agencyService.getAgencies(Mockito.anyList()))
- .thenThrow(new InternalServerErrorException(""));
-
- askerDataProvider.retrieveData(USER);
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ givenAnEmailDummySuffixConfig();
+ when(authenticatedUser.getRoles()).thenReturn(asSet(UserRole.USER.getValue()));
+ when(agencyService.getAgencies(Mockito.anyList()))
+ .thenThrow(new InternalServerErrorException(""));
+
+ askerDataProvider.retrieveData(USER);
+ });
}
@Test
- public void
- retrieveData_Should_ReturnUserDataResponseDTOWithValidEmail_When_ProvidedWithValidUser() {
+ void retrieveData_Should_ReturnUserDataResponseDTOWithValidEmail_When_ProvidedWithValidUser() {
givenAnEmailDummySuffixConfig();
when(authenticatedUser.getRoles()).thenReturn(asSet(UserRole.USER.getValue()));
when(consultingTypeManager.getAllConsultingTypeIds())
@@ -130,7 +128,7 @@ public void retrieveData_Should_ReturnUserDataWithAgency_When_ProvidedWithUserWi
}
@Test
- public void retrieveData_Should_ReturnUserDataResponseDTOWithoutEmail_When_UserHasDummyMail() {
+ void retrieveData_Should_ReturnUserDataResponseDTOWithoutEmail_When_UserHasDummyMail() {
givenAnEmailDummySuffixConfig();
when(authenticatedUser.getRoles()).thenReturn(asSet(UserRole.USER.getValue()));
User user = mock(User.class);
@@ -145,7 +143,7 @@ public void retrieveData_Should_ReturnUserDataResponseDTOWithoutEmail_When_UserH
}
@Test
- public void retrieveData_Should_ReturnValidData() {
+ void retrieveData_Should_ReturnValidData() {
givenAnEmailDummySuffixConfig();
when(agencyService.getAgencies(any())).thenReturn(Collections.singletonList(AGENCY_DTO_SUCHT));
LinkedHashMap sessionData = new LinkedHashMap<>();
@@ -184,7 +182,7 @@ public void retrieveData_Should_ReturnValidData() {
}
@Test
- public void retrieveData_Should_ReturnUserDataWithoutAgency_When_userHasNotAgencyInSession() {
+ void retrieveData_Should_ReturnUserDataWithoutAgency_When_userHasNotAgencyInSession() {
givenAnEmailDummySuffixConfig();
User user = new EasyRandom().nextObject(User.class);
diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/userdata/ConsultantDataFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/userdata/ConsultantDataFacadeTest.java
index c44fd9eff..3ddc5dc95 100644
--- a/src/test/java/de/caritas/cob/userservice/api/facade/userdata/ConsultantDataFacadeTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/facade/userdata/ConsultantDataFacadeTest.java
@@ -8,9 +8,7 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.GROUP_SESSION_RESPONSE_DTO;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.MESSAGE;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USER_SESSION_RESPONSE_DTO;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -27,15 +25,15 @@
import java.util.Map;
import java.util.Optional;
import org.apache.commons.lang3.RandomStringUtils;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class ConsultantDataFacadeTest {
@InjectMocks private ConsultantDataFacade consultantDataFacade;
diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/userdata/ConsultantDataProviderIT.java b/src/test/java/de/caritas/cob/userservice/api/facade/userdata/ConsultantDataProviderIT.java
index 50244d549..e01232f3a 100644
--- a/src/test/java/de/caritas/cob/userservice/api/facade/userdata/ConsultantDataProviderIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/facade/userdata/ConsultantDataProviderIT.java
@@ -1,8 +1,6 @@
package de.caritas.cob.userservice.api.facade.userdata;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.when;
@@ -21,17 +19,14 @@
import java.util.stream.Collectors;
import org.jeasy.random.EasyRandom;
import org.jetbrains.annotations.NotNull;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
-@RunWith(SpringRunner.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/userdata/ConsultantDataProviderTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/userdata/ConsultantDataProviderTest.java
index fa678472f..d5f311f47 100644
--- a/src/test/java/de/caritas/cob/userservice/api/facade/userdata/ConsultantDataProviderTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/facade/userdata/ConsultantDataProviderTest.java
@@ -6,11 +6,7 @@
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hibernate.validator.internal.util.CollectionHelper.asSet;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.when;
@@ -32,14 +28,14 @@
import java.util.Set;
import java.util.stream.Collectors;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class ConsultantDataProviderTest {
private final EasyRandom easyRandom = new EasyRandom();
@@ -56,12 +52,16 @@ public class ConsultantDataProviderTest {
@Mock private EmailNotificationMapper emailNotificationMapper;
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void retrieveData_Should_ThrowInternalServerErrorException_When_NoAgenciesFound() {
- Consultant consultant = Mockito.mock(Consultant.class);
- when(consultant.getConsultantAgencies()).thenReturn(new HashSet<>());
-
- underTest.retrieveData(consultant);
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ Consultant consultant = Mockito.mock(Consultant.class);
+ when(consultant.getConsultantAgencies()).thenReturn(new HashSet<>());
+
+ underTest.retrieveData(consultant);
+ });
}
@Test
diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/userdata/KeycloakUserDataProviderTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/userdata/KeycloakUserDataProviderTest.java
index 039264630..99ffd9920 100644
--- a/src/test/java/de/caritas/cob/userservice/api/facade/userdata/KeycloakUserDataProviderTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/facade/userdata/KeycloakUserDataProviderTest.java
@@ -1,7 +1,7 @@
package de.caritas.cob.userservice.api.facade.userdata;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import de.caritas.cob.userservice.api.adapters.keycloak.KeycloakService;
import de.caritas.cob.userservice.api.adapters.web.dto.UserDataResponseDTO;
diff --git a/src/test/java/de/caritas/cob/userservice/api/helper/AgencyVerifierTest.java b/src/test/java/de/caritas/cob/userservice/api/helper/AgencyVerifierTest.java
index 767aab6b6..2e9f2da9f 100644
--- a/src/test/java/de/caritas/cob/userservice/api/helper/AgencyVerifierTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/helper/AgencyVerifierTest.java
@@ -4,9 +4,7 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.AGENCY_ID;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.CONSULTING_TYPE_ID_KREUZBUND;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.CONSULTING_TYPE_ID_SUCHT;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
@@ -16,14 +14,14 @@
import de.caritas.cob.userservice.api.exception.httpresponses.InternalServerErrorException;
import de.caritas.cob.userservice.api.service.agency.AgencyService;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
-@RunWith(SpringRunner.class)
-public class AgencyVerifierTest {
+@ExtendWith(SpringExtension.class)
+class AgencyVerifierTest {
@InjectMocks private AgencyVerifier agencyVerifier;
@@ -32,8 +30,7 @@ public class AgencyVerifierTest {
private final EasyRandom easyRandom = new EasyRandom();
@Test
- public void
- getVerifiedAgency_Should_ThrowInternalServerErrorException_When_AgencyServiceHelperFails() {
+ void getVerifiedAgency_Should_ThrowInternalServerErrorException_When_AgencyServiceHelperFails() {
when(agencyService.getAgencyWithoutCaching(AGENCY_ID))
.thenThrow(new InternalServerErrorException(""));
@@ -41,12 +38,12 @@ public class AgencyVerifierTest {
agencyVerifier.getVerifiedAgency(AGENCY_ID, 0);
fail("Expected exception: InternalServerErrorException");
} catch (InternalServerErrorException serviceException) {
- assertTrue("Excepted InternalServerErrorException thrown", true);
+ assertTrue(true, "Excepted InternalServerErrorException thrown");
}
}
@Test
- public void
+ void
getVerifiedAgency_Should_ThrowBadRequestException_When_AgencyIsNotAssignedToGivenConsultingType() {
when(agencyService.getAgencyWithoutCaching(AGENCY_ID)).thenReturn(AGENCY_DTO_SUCHT);
@@ -54,30 +51,34 @@ public class AgencyVerifierTest {
agencyVerifier.getVerifiedAgency(AGENCY_ID, 15);
fail("Expected exception: BadRequestException");
} catch (BadRequestException badRequestException) {
- assertTrue("Excepted BadRequestException thrown", true);
+ assertTrue(true, "Excepted BadRequestException thrown");
}
}
@Test
- public void getVerifiedAgency_Should_ReturnCorrectAgency_When_AgencyIsFoundAndValid() {
+ void getVerifiedAgency_Should_ReturnCorrectAgency_When_AgencyIsFoundAndValid() {
when(agencyService.getAgencyWithoutCaching(AGENCY_ID)).thenReturn(AGENCY_DTO_SUCHT);
AgencyDTO agency = agencyVerifier.getVerifiedAgency(AGENCY_ID, 0);
assertEquals(AGENCY_ID, agency.getId());
}
- @Test(expected = BadRequestException.class)
- public void
+ @Test
+ void
checkIfConsultingTypeMatchesToAgency_Should_ThrowBadRequestException_When_ConsultingTypeDoesNotMatchToAgency() {
- when(agencyService.getAgencyWithoutCaching(any())).thenReturn(AGENCY_DTO_SUCHT);
-
- UserDTO userDTO = easyRandom.nextObject(UserDTO.class);
- userDTO.setConsultingType(String.valueOf(CONSULTING_TYPE_ID_KREUZBUND));
- agencyVerifier.checkIfConsultingTypeMatchesToAgency(userDTO);
+ assertThrows(
+ BadRequestException.class,
+ () -> {
+ when(agencyService.getAgencyWithoutCaching(any())).thenReturn(AGENCY_DTO_SUCHT);
+
+ UserDTO userDTO = easyRandom.nextObject(UserDTO.class);
+ userDTO.setConsultingType(String.valueOf(CONSULTING_TYPE_ID_KREUZBUND));
+ agencyVerifier.checkIfConsultingTypeMatchesToAgency(userDTO);
+ });
}
@Test
- public void
+ void
checkIfConsultingTypeMatchesToAgency_ShouldNot_ThrowException_When_ConsultingTypeMatchesToAgency() {
when(agencyService.getAgencyWithoutCaching(any())).thenReturn(AGENCY_DTO_SUCHT);
diff --git a/src/test/java/de/caritas/cob/userservice/api/helper/AuthenticatedUserTest.java b/src/test/java/de/caritas/cob/userservice/api/helper/AuthenticatedUserTest.java
index f092de35b..66edf2e89 100644
--- a/src/test/java/de/caritas/cob/userservice/api/helper/AuthenticatedUserTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/helper/AuthenticatedUserTest.java
@@ -1,36 +1,54 @@
package de.caritas.cob.userservice.api.helper;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.junit.MockitoJUnitRunner;
+import static org.junit.jupiter.api.Assertions.assertThrows;
-@RunWith(MockitoJUnitRunner.class)
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+@ExtendWith(MockitoExtension.class)
public class AuthenticatedUserTest {
- @Test(expected = NullPointerException.class)
+ @Test
public void AuthenticatedUser_Should_ThrowNullPointerExceptionWhenArgumentsAreNull()
throws Exception {
- new AuthenticatedUser(null, null, null, null, null);
+ assertThrows(
+ NullPointerException.class,
+ () -> {
+ new AuthenticatedUser(null, null, null, null, null);
+ });
}
- @Test(expected = NullPointerException.class)
+ @Test
public void AuthenticatedUser_Should_ThrowNullPointerExceptionWhenUserIdIsNull()
throws Exception {
- AuthenticatedUser authenticatedUser = new AuthenticatedUser();
- authenticatedUser.setUserId(null);
+ assertThrows(
+ NullPointerException.class,
+ () -> {
+ AuthenticatedUser authenticatedUser = new AuthenticatedUser();
+ authenticatedUser.setUserId(null);
+ });
}
- @Test(expected = NullPointerException.class)
+ @Test
public void AuthenticatedUser_Should_ThrowNullPointerExceptionWhenUsernameIsNull()
throws Exception {
- AuthenticatedUser authenticatedUser = new AuthenticatedUser();
- authenticatedUser.setUsername(null);
+ assertThrows(
+ NullPointerException.class,
+ () -> {
+ AuthenticatedUser authenticatedUser = new AuthenticatedUser();
+ authenticatedUser.setUsername(null);
+ });
}
- @Test(expected = NullPointerException.class)
+ @Test
public void AuthenticatedUser_Should_ThrowNullPointerExceptionWhenAccessTokenIsNull()
throws Exception {
- AuthenticatedUser authenticatedUser = new AuthenticatedUser();
- authenticatedUser.setAccessToken(null);
+ assertThrows(
+ NullPointerException.class,
+ () -> {
+ AuthenticatedUser authenticatedUser = new AuthenticatedUser();
+ authenticatedUser.setAccessToken(null);
+ });
}
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/helper/ChatPermissionVerifierTest.java b/src/test/java/de/caritas/cob/userservice/api/helper/ChatPermissionVerifierTest.java
index 64f602df3..9ad23ae06 100644
--- a/src/test/java/de/caritas/cob/userservice/api/helper/ChatPermissionVerifierTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/helper/ChatPermissionVerifierTest.java
@@ -5,9 +5,7 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.AGENCY_ID_2;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.AGENCY_ID_3;
import static org.hibernate.validator.internal.util.CollectionHelper.asSet;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when;
import de.caritas.cob.userservice.api.config.auth.UserRole;
@@ -26,14 +24,14 @@
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
-public class ChatPermissionVerifierTest {
+@ExtendWith(MockitoExtension.class)
+class ChatPermissionVerifierTest {
@InjectMocks private ChatPermissionVerifier chatPermissionVerifier;
@@ -50,7 +48,7 @@ public class ChatPermissionVerifierTest {
@Mock private User user;
@Test
- public void hasSameAgencyAssigned_Should_ReturnTrue_When_ChatAgenciesContainConsultantAgency() {
+ void hasSameAgencyAssigned_Should_ReturnTrue_When_ChatAgenciesContainConsultantAgency() {
ChatAgency[] chatAgencyArray = new ChatAgency[] {new ChatAgency(chat, AGENCY_ID_2)};
Set chatAgencySet = new HashSet<>(Arrays.asList(chatAgencyArray));
@@ -71,8 +69,7 @@ AGENCY_ID_2, consultant, AGENCY_ID_2, nowInUtc(), nowInUtc(), nowInUtc(), null,
}
@Test
- public void
- hasSameAgencyAssigned_Should_ReturnFalse_When_ChatAgenciesNotContainConsultantAgency() {
+ void hasSameAgencyAssigned_Should_ReturnFalse_When_ChatAgenciesNotContainConsultantAgency() {
ConsultantAgency[] consultantAgencyArray =
new ConsultantAgency[] {
new ConsultantAgency(
@@ -88,7 +85,7 @@ AGENCY_ID_3, consultant, AGENCY_ID_3, nowInUtc(), nowInUtc(), nowInUtc(), null,
}
@Test
- public void hasSameAgencyAssigned_Should_ReturnTrue_When_ChatAgenciesContainUserAgency() {
+ void hasSameAgencyAssigned_Should_ReturnTrue_When_ChatAgenciesContainUserAgency() {
ChatAgency[] chatAgencyArray = new ChatAgency[] {new ChatAgency(chat, AGENCY_ID_2)};
Set chatAgencySet = new HashSet<>(Arrays.asList(chatAgencyArray));
@@ -107,7 +104,7 @@ public void hasSameAgencyAssigned_Should_ReturnTrue_When_ChatAgenciesContainUser
}
@Test
- public void hasSameAgencyAssigned_Should_ReturnFalse_When_ChatAgenciesNotContainUserAgency() {
+ void hasSameAgencyAssigned_Should_ReturnFalse_When_ChatAgenciesNotContainUserAgency() {
UserAgency[] userAgencyArray =
new UserAgency[] {
new UserAgency(AGENCY_ID, user, AGENCY_ID, null, null),
@@ -121,14 +118,14 @@ public void hasSameAgencyAssigned_Should_ReturnFalse_When_ChatAgenciesNotContain
}
@Test
- public void hasSameAgencyAssigned_Should_ReturnFalse_When_UsersChatAgenciesAreNull() {
+ void hasSameAgencyAssigned_Should_ReturnFalse_When_UsersChatAgenciesAreNull() {
Chat chat = new Chat();
assertFalse(chatPermissionVerifier.hasSameAgencyAssigned(chat, user));
}
@Test
- public void hasChatUserAssignment_Should_ReturnTrue_When_UserHasUserChatAssignment() {
+ void hasChatUserAssignment_Should_ReturnTrue_When_UserHasUserChatAssignment() {
Chat chat = new Chat();
UserChat userChat = UserChat.builder().chat(chat).user(user).build();
chat.setChatUsers(Set.of(userChat));
@@ -137,7 +134,7 @@ public void hasChatUserAssignment_Should_ReturnTrue_When_UserHasUserChatAssignme
}
@Test
- public void hasChatUserAssignment_Should_ReturnFalse_When_UserHasNoUserChatAssignment() {
+ void hasChatUserAssignment_Should_ReturnFalse_When_UserHasNoUserChatAssignment() {
Chat chat = new Chat();
UserChat userChat = UserChat.builder().chat(chat).user(new User()).build();
chat.setChatUsers(Set.of(userChat));
@@ -146,14 +143,14 @@ public void hasChatUserAssignment_Should_ReturnFalse_When_UserHasNoUserChatAssig
}
@Test
- public void hasChatUserAssignment_Should_ReturnFalse_When_UsersChatUsersAreNull() {
+ void hasChatUserAssignment_Should_ReturnFalse_When_UsersChatUsersAreNull() {
Chat chat = new Chat();
assertFalse(chatPermissionVerifier.hasChatUserAssignment(chat, user));
}
@Test
- public void
+ void
verifyPermissionForChat_Should_verifyConsultantPermission_When_ChatAgenciesContainConsultantAgency() {
Consultant consultant = new Consultant();
ConsultantAgency consultantAgency = new ConsultantAgency();
@@ -170,37 +167,44 @@ public void hasChatUserAssignment_Should_ReturnFalse_When_UsersChatUsersAreNull(
assertDoesNotThrow(() -> this.chatPermissionVerifier.verifyPermissionForChat(chat));
}
- @Test(expected = NotFoundException.class)
- public void
+ @Test
+ void
verifyPermissionForChat_Should_throwNotFoundException_When_consultantDoesNotExistInDatabase() {
- when(authenticatedUser.getRoles()).thenReturn(asSet(UserRole.CONSULTANT.getValue()));
- when(consultantService.getConsultantViaAuthenticatedUser(authenticatedUser))
- .thenReturn(Optional.empty());
-
- this.chatPermissionVerifier.verifyPermissionForChat(chat);
+ assertThrows(
+ NotFoundException.class,
+ () -> {
+ when(authenticatedUser.getRoles()).thenReturn(asSet(UserRole.CONSULTANT.getValue()));
+ when(consultantService.getConsultantViaAuthenticatedUser(authenticatedUser))
+ .thenReturn(Optional.empty());
+
+ this.chatPermissionVerifier.verifyPermissionForChat(chat);
+ });
}
- @Test(expected = ForbiddenException.class)
- public void
+ @Test
+ void
verifyPermissionForChat_Should_throwForbiddenException_When_agenciesOfChatAndConsultantAreDifferent() {
- Consultant consultant = new Consultant();
- ConsultantAgency consultantAgency = new ConsultantAgency();
- consultantAgency.setAgencyId(1L);
- consultant.setConsultantAgencies(asSet(consultantAgency));
- ChatAgency chatAgency = new ChatAgency();
- chatAgency.setAgencyId(2L);
- Chat chat = new Chat();
- chat.setChatAgencies(asSet(chatAgency));
- when(authenticatedUser.getRoles()).thenReturn(asSet(UserRole.CONSULTANT.getValue()));
- when(consultantService.getConsultantViaAuthenticatedUser(authenticatedUser))
- .thenReturn(Optional.of(consultant));
-
- this.chatPermissionVerifier.verifyPermissionForChat(chat);
+ assertThrows(
+ ForbiddenException.class,
+ () -> {
+ Consultant consultant = new Consultant();
+ ConsultantAgency consultantAgency = new ConsultantAgency();
+ consultantAgency.setAgencyId(1L);
+ consultant.setConsultantAgencies(asSet(consultantAgency));
+ ChatAgency chatAgency = new ChatAgency();
+ chatAgency.setAgencyId(2L);
+ Chat chat = new Chat();
+ chat.setChatAgencies(asSet(chatAgency));
+ when(authenticatedUser.getRoles()).thenReturn(asSet(UserRole.CONSULTANT.getValue()));
+ when(consultantService.getConsultantViaAuthenticatedUser(authenticatedUser))
+ .thenReturn(Optional.of(consultant));
+
+ this.chatPermissionVerifier.verifyPermissionForChat(chat);
+ });
}
@Test
- public void
- verifyPermissionForChat_Should_verifyUserPermission_When_ChatAgenciesContainUserAgency() {
+ void verifyPermissionForChat_Should_verifyUserPermission_When_ChatAgenciesContainUserAgency() {
User user = new User();
UserAgency userAgency = new UserAgency();
userAgency.setAgencyId(1L);
@@ -216,7 +220,7 @@ public void hasChatUserAssignment_Should_ReturnFalse_When_UsersChatUsersAreNull(
}
@Test
- public void verifyPermissionForChat_Should_verifyUserPermission_When_UserHasUserChatAssignment() {
+ void verifyPermissionForChat_Should_verifyUserPermission_When_UserHasUserChatAssignment() {
UserChat userChat = UserChat.builder().chat(chat).user(user).build();
when(chat.getChatUsers()).thenReturn(Set.of(userChat));
when(authenticatedUser.getRoles()).thenReturn(asSet(UserRole.USER.getValue()));
@@ -226,8 +230,7 @@ public void verifyPermissionForChat_Should_verifyUserPermission_When_UserHasUser
}
@Test
- public void
- verifyCanModerateChat_Should_AllowToModerate_When_ConsultantHasAccessToSameAgencyAsChat() {
+ void verifyCanModerateChat_Should_AllowToModerate_When_ConsultantHasAccessToSameAgencyAsChat() {
Consultant consultant = new Consultant();
ConsultantAgency consultantAgency = new ConsultantAgency();
consultantAgency.setAgencyId(1L);
@@ -242,69 +245,90 @@ public void verifyPermissionForChat_Should_verifyUserPermission_When_UserHasUser
assertDoesNotThrow(() -> this.chatPermissionVerifier.verifyCanModerateChat(chat));
}
- @Test(expected = ForbiddenException.class)
- public void
+ @Test
+ void
verifyCanModerateChat_Should_Not_AllowToModerate_When_ConsultantDoesNotHaveAccessToSameAgencyAsChat() {
- Consultant consultant = new Consultant();
- ConsultantAgency consultantAgency = new ConsultantAgency();
- consultantAgency.setAgencyId(2L);
- consultant.setConsultantAgencies(asSet(consultantAgency));
- ChatAgency chatAgency = new ChatAgency();
- chatAgency.setAgencyId(1L);
- Chat chat = new Chat();
- chat.setChatAgencies(asSet(chatAgency));
- when(authenticatedUser.getRoles()).thenReturn(asSet(UserRole.CONSULTANT.getValue()));
- when(consultantService.getConsultantViaAuthenticatedUser(authenticatedUser))
- .thenReturn(Optional.of(consultant));
- this.chatPermissionVerifier.verifyCanModerateChat(chat);
+ assertThrows(
+ ForbiddenException.class,
+ () -> {
+ Consultant consultant = new Consultant();
+ ConsultantAgency consultantAgency = new ConsultantAgency();
+ consultantAgency.setAgencyId(2L);
+ consultant.setConsultantAgencies(asSet(consultantAgency));
+ ChatAgency chatAgency = new ChatAgency();
+ chatAgency.setAgencyId(1L);
+ Chat chat = new Chat();
+ chat.setChatAgencies(asSet(chatAgency));
+ when(authenticatedUser.getRoles()).thenReturn(asSet(UserRole.CONSULTANT.getValue()));
+ when(consultantService.getConsultantViaAuthenticatedUser(authenticatedUser))
+ .thenReturn(Optional.of(consultant));
+ this.chatPermissionVerifier.verifyCanModerateChat(chat);
+ });
}
- @Test(expected = ForbiddenException.class)
- public void verifyCanModerateChat_Should_Not_AllowToModerate_When_AccessedAsUser() {
- ChatAgency chatAgency = new ChatAgency();
- chatAgency.setAgencyId(1L);
- Chat chat = new Chat();
- chat.setChatAgencies(asSet(chatAgency));
- when(authenticatedUser.getRoles()).thenReturn(asSet(UserRole.USER.getValue()));
- this.chatPermissionVerifier.verifyCanModerateChat(chat);
+ @Test
+ void verifyCanModerateChat_Should_Not_AllowToModerate_When_AccessedAsUser() {
+ assertThrows(
+ ForbiddenException.class,
+ () -> {
+ ChatAgency chatAgency = new ChatAgency();
+ chatAgency.setAgencyId(1L);
+ Chat chat = new Chat();
+ chat.setChatAgencies(asSet(chatAgency));
+ when(authenticatedUser.getRoles()).thenReturn(asSet(UserRole.USER.getValue()));
+ this.chatPermissionVerifier.verifyCanModerateChat(chat);
+ });
}
- @Test(expected = NotFoundException.class)
- public void
- verifyPermissionForChat_Should_throwNotFoundException_When_UserDoesNotExistInDatabase() {
- when(authenticatedUser.getRoles()).thenReturn(asSet(UserRole.USER.getValue()));
- when(userService.getUserViaAuthenticatedUser(authenticatedUser)).thenReturn(Optional.empty());
-
- this.chatPermissionVerifier.verifyPermissionForChat(chat);
+ @Test
+ void verifyPermissionForChat_Should_throwNotFoundException_When_UserDoesNotExistInDatabase() {
+ assertThrows(
+ NotFoundException.class,
+ () -> {
+ when(authenticatedUser.getRoles()).thenReturn(asSet(UserRole.USER.getValue()));
+ when(userService.getUserViaAuthenticatedUser(authenticatedUser))
+ .thenReturn(Optional.empty());
+
+ this.chatPermissionVerifier.verifyPermissionForChat(chat);
+ });
}
- @Test(expected = ForbiddenException.class)
- public void
+ @Test
+ void
verifyPermissionForChat_Should_throwForbiddenException_When_AgenciesOfChatAndUserAreDifferent() {
- User user = new User();
- UserAgency userAgency = new UserAgency();
- userAgency.setAgencyId(1L);
- user.setUserAgencies(asSet(userAgency));
- ChatAgency chatAgency = new ChatAgency();
- chatAgency.setAgencyId(2L);
- Chat chat = new Chat();
- chat.setChatAgencies(asSet(chatAgency));
- when(authenticatedUser.getRoles()).thenReturn(asSet(UserRole.USER.getValue()));
- when(userService.getUserViaAuthenticatedUser(authenticatedUser)).thenReturn(Optional.of(user));
-
- this.chatPermissionVerifier.verifyPermissionForChat(chat);
+ assertThrows(
+ ForbiddenException.class,
+ () -> {
+ User user = new User();
+ UserAgency userAgency = new UserAgency();
+ userAgency.setAgencyId(1L);
+ user.setUserAgencies(asSet(userAgency));
+ ChatAgency chatAgency = new ChatAgency();
+ chatAgency.setAgencyId(2L);
+ Chat chat = new Chat();
+ chat.setChatAgencies(asSet(chatAgency));
+ when(authenticatedUser.getRoles()).thenReturn(asSet(UserRole.USER.getValue()));
+ when(userService.getUserViaAuthenticatedUser(authenticatedUser))
+ .thenReturn(Optional.of(user));
+
+ this.chatPermissionVerifier.verifyPermissionForChat(chat);
+ });
}
- @Test(expected = ForbiddenException.class)
- public void
- verifyPermissionForChat_Should_throwForbiddenException_When_UserHasNoChatUserAssignment() {
- Chat chat = new Chat();
- UserChat userChat = UserChat.builder().user(new User()).chat(chat).build();
- chat.setChatUsers(Set.of(userChat));
-
- when(authenticatedUser.getRoles()).thenReturn(asSet(UserRole.USER.getValue()));
- when(userService.getUserViaAuthenticatedUser(authenticatedUser)).thenReturn(Optional.of(user));
-
- this.chatPermissionVerifier.verifyPermissionForChat(chat);
+ @Test
+ void verifyPermissionForChat_Should_throwForbiddenException_When_UserHasNoChatUserAssignment() {
+ assertThrows(
+ ForbiddenException.class,
+ () -> {
+ Chat chat = new Chat();
+ UserChat userChat = UserChat.builder().user(new User()).chat(chat).build();
+ chat.setChatUsers(Set.of(userChat));
+
+ when(authenticatedUser.getRoles()).thenReturn(asSet(UserRole.USER.getValue()));
+ when(userService.getUserViaAuthenticatedUser(authenticatedUser))
+ .thenReturn(Optional.of(user));
+
+ this.chatPermissionVerifier.verifyPermissionForChat(chat);
+ });
}
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/helper/EmptyObjectSerializerTest.java b/src/test/java/de/caritas/cob/userservice/api/helper/EmptyObjectSerializerTest.java
index 5cf5541f7..160e75a6c 100644
--- a/src/test/java/de/caritas/cob/userservice/api/helper/EmptyObjectSerializerTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/helper/EmptyObjectSerializerTest.java
@@ -1,15 +1,15 @@
package de.caritas.cob.userservice.api.helper;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.caritas.cob.userservice.api.adapters.rocketchat.dto.login.LdapLoginDTO;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class EmptyObjectSerializerTest {
private final String USERNAME = "username";
diff --git a/src/test/java/de/caritas/cob/userservice/api/helper/HelperTest.java b/src/test/java/de/caritas/cob/userservice/api/helper/HelperTest.java
index 956df3b88..632151e01 100644
--- a/src/test/java/de/caritas/cob/userservice/api/helper/HelperTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/helper/HelperTest.java
@@ -3,16 +3,16 @@
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
import java.util.Date;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class HelperTest {
private static String TEXT = "Lorem Ipsum";
diff --git a/src/test/java/de/caritas/cob/userservice/api/helper/RocketChatRoomNameGeneratorTest.java b/src/test/java/de/caritas/cob/userservice/api/helper/RocketChatRoomNameGeneratorTest.java
index 10d258dd3..eaac86de7 100644
--- a/src/test/java/de/caritas/cob/userservice/api/helper/RocketChatRoomNameGeneratorTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/helper/RocketChatRoomNameGeneratorTest.java
@@ -4,19 +4,19 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.SESSION;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class RocketChatRoomNameGeneratorTest {
private RocketChatRoomNameGenerator rocketChatRoomNameGenerator;
- @Before
+ @BeforeEach
public void setup() {
this.rocketChatRoomNameGenerator = new RocketChatRoomNameGenerator();
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/helper/SessionDataProviderTest.java b/src/test/java/de/caritas/cob/userservice/api/helper/SessionDataProviderTest.java
index 95088a112..f117bfd2b 100644
--- a/src/test/java/de/caritas/cob/userservice/api/helper/SessionDataProviderTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/helper/SessionDataProviderTest.java
@@ -18,11 +18,7 @@
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when;
import com.neovisionaries.i18n.LanguageCode;
@@ -44,13 +40,13 @@
import java.util.List;
import java.util.Map;
import org.jeasy.random.EasyRandom;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class SessionDataProviderTest {
private SessionDataProvider sessionDataProvider;
@@ -186,7 +182,7 @@ public class SessionDataProviderTest {
.roles(null)
.registration(null);
- @Before
+ @BeforeEach
public void setup() {
consultingTypeManager = Mockito.mock(ConsultingTypeManager.class);
sessionDataProvider = new SessionDataProvider(consultingTypeManager);
diff --git a/src/test/java/de/caritas/cob/userservice/api/helper/SessionListAnalyserTest.java b/src/test/java/de/caritas/cob/userservice/api/helper/SessionListAnalyserTest.java
index 238ae7f63..066e4371d 100644
--- a/src/test/java/de/caritas/cob/userservice/api/helper/SessionListAnalyserTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/helper/SessionListAnalyserTest.java
@@ -12,9 +12,7 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.ROOMS_LAST_MESSAGE_DTO_2;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.ROOMS_LAST_MESSAGE_DTO_MAP;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.ROOMS_LAST_MESSAGE_DTO_WITHOUT_ATTACHMENT;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -22,13 +20,13 @@
import de.caritas.cob.userservice.api.adapters.web.dto.SessionAttachmentDTO;
import de.caritas.cob.userservice.api.exception.CustomCryptoException;
import de.caritas.cob.userservice.api.service.DecryptionService;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class SessionListAnalyserTest {
@InjectMocks private SessionListAnalyser sessionListAnalyser;
diff --git a/src/test/java/de/caritas/cob/userservice/api/helper/UserHelperTest.java b/src/test/java/de/caritas/cob/userservice/api/helper/UserHelperTest.java
index f4a247ee1..2d39487fc 100644
--- a/src/test/java/de/caritas/cob/userservice/api/helper/UserHelperTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/helper/UserHelperTest.java
@@ -9,24 +9,25 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USERNAME_TOO_SHORT;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USER_ID;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when;
import static org.springframework.test.util.ReflectionTestUtils.setField;
import de.caritas.cob.userservice.api.port.out.IdentityClientConfig;
import java.util.List;
import org.jeasy.random.EasyRandom;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
-@RunWith(MockitoJUnitRunner.class)
-public class UserHelperTest {
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
+class UserHelperTest {
private static final EasyRandom easyRandom = new EasyRandom();
private final UsernameTranscoder usernameTranscoder = new UsernameTranscoder();
@@ -34,38 +35,38 @@ public class UserHelperTest {
@InjectMocks private UserHelper userHelper;
@Mock private IdentityClientConfig identityClientConfig;
- @Before
- public void setup() throws NoSuchFieldException, SecurityException {
+ @BeforeEach
+ void setup() throws NoSuchFieldException, SecurityException {
when(identityClientConfig.getEmailDummySuffix()).thenReturn(FIELD_VALUE_EMAIL_DUMMY_SUFFIX);
setField(userHelper, "usernameTranscoder", usernameTranscoder);
}
@Test
- public void isUsernameValid_Should_ReturnFalse_WhenUsernameIsTooShort() {
+ void isUsernameValid_Should_ReturnFalse_WhenUsernameIsTooShort() {
assertFalse(userHelper.isUsernameValid(USERNAME_TOO_SHORT));
}
@Test
- public void isUsernameValid_Should_ReturnFalse_WhenUsernameIsTooLong() {
+ void isUsernameValid_Should_ReturnFalse_WhenUsernameIsTooLong() {
assertFalse(userHelper.isUsernameValid(USERNAME_TOO_LONG));
}
@Test
- public void isValidEmailShouldReturnTrueOnValidAddress() {
+ void isValidEmailShouldReturnTrueOnValidAddress() {
var emailAddress = givenARandomEmail();
assertTrue(userHelper.isValidEmail(emailAddress));
}
@Test
- public void isValidEmailShouldReturnTrueOnAddressWithUmlaut() {
+ void isValidEmailShouldReturnTrueOnAddressWithUmlaut() {
var emailAddress = givenARandomEmailWithAnUmlaut();
assertTrue(userHelper.isValidEmail(emailAddress));
}
@Test
- public void isValidEmailShouldReturnFalseOnEmptyAddress() {
+ void isValidEmailShouldReturnFalseOnEmptyAddress() {
assertFalse(userHelper.isValidEmail(null));
assertFalse(userHelper.isValidEmail(""));
assertFalse(userHelper.isValidEmail("@"));
@@ -74,37 +75,37 @@ public void isValidEmailShouldReturnFalseOnEmptyAddress() {
}
@Test
- public void getDummyEmail_Should_ReturnRcUserIdWithDummyEmailSuffix() {
+ void getDummyEmail_Should_ReturnRcUserIdWithDummyEmailSuffix() {
assertEquals(USER_ID + FIELD_VALUE_EMAIL_DUMMY_SUFFIX, userHelper.getDummyEmail(USER_ID));
}
@Test
- public void doUsernamesMatch_Should_ReturnFalse_WhenDecodedUsernamesDontMatch() {
+ void doUsernamesMatch_Should_ReturnFalse_WhenDecodedUsernamesDontMatch() {
assertFalse(userHelper.doUsernamesMatch(USERNAME_CONSULTANT_DECODED, USERNAME_DECODED));
}
@Test
- public void doUsernamesMatch_Should_ReturnFalse_WhenEncodedUsernamesDontMatch() {
+ void doUsernamesMatch_Should_ReturnFalse_WhenEncodedUsernamesDontMatch() {
assertFalse(userHelper.doUsernamesMatch(USERNAME_CONSULTANT_ENCODED, USERNAME_ENCODED));
}
@Test
- public void doUsernamesMatch_Should_ReturnFalse_WhenEncodedAndDecodedUsernamesDontMatch() {
+ void doUsernamesMatch_Should_ReturnFalse_WhenEncodedAndDecodedUsernamesDontMatch() {
assertFalse(userHelper.doUsernamesMatch(USERNAME_CONSULTANT_ENCODED, USERNAME_DECODED));
}
@Test
- public void doUsernamesMatch_Should_ReturnTrue_WhenDecodedUsernamesMatch() {
+ void doUsernamesMatch_Should_ReturnTrue_WhenDecodedUsernamesMatch() {
assertTrue(userHelper.doUsernamesMatch(USERNAME_DECODED, USERNAME_DECODED));
}
@Test
- public void doUsernamesMatch_Should_ReturnTrue_WhenEncodedUsernamesMatch() {
+ void doUsernamesMatch_Should_ReturnTrue_WhenEncodedUsernamesMatch() {
assertTrue(userHelper.doUsernamesMatch(USERNAME_ENCODED, USERNAME_ENCODED));
}
@Test
- public void doUsernamesMatch_Should_ReturnTrue_WhenEncodedAndDecodedUsernamesMatch() {
+ void doUsernamesMatch_Should_ReturnTrue_WhenEncodedAndDecodedUsernamesMatch() {
assertTrue(userHelper.doUsernamesMatch(USERNAME_ENCODED, USERNAME_DECODED));
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/helper/UserVerifierTest.java b/src/test/java/de/caritas/cob/userservice/api/helper/UserVerifierTest.java
index 378644057..ac33e3cfc 100644
--- a/src/test/java/de/caritas/cob/userservice/api/helper/UserVerifierTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/helper/UserVerifierTest.java
@@ -2,8 +2,8 @@
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.when;
import de.caritas.cob.userservice.api.adapters.keycloak.KeycloakService;
diff --git a/src/test/java/de/caritas/cob/userservice/api/helper/UsernameTranscoderTest.java b/src/test/java/de/caritas/cob/userservice/api/helper/UsernameTranscoderTest.java
index 2dc376ba3..5a449b632 100644
--- a/src/test/java/de/caritas/cob/userservice/api/helper/UsernameTranscoderTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/helper/UsernameTranscoderTest.java
@@ -2,9 +2,9 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USERNAME_DECODED;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USERNAME_ENCODED;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class UsernameTranscoderTest {
diff --git a/src/test/java/de/caritas/cob/userservice/api/manager/consultingtype/ConsultingTypeManagerTest.java b/src/test/java/de/caritas/cob/userservice/api/manager/consultingtype/ConsultingTypeManagerTest.java
index 6da802b9e..0ca72b466 100644
--- a/src/test/java/de/caritas/cob/userservice/api/manager/consultingtype/ConsultingTypeManagerTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/manager/consultingtype/ConsultingTypeManagerTest.java
@@ -1,9 +1,6 @@
package de.caritas.cob.userservice.api.manager.consultingtype;
-import static org.junit.Assert.assertThrows;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.when;
diff --git a/src/test/java/de/caritas/cob/userservice/api/model/ChatAgencyTest.java b/src/test/java/de/caritas/cob/userservice/api/model/ChatAgencyTest.java
index dcf055322..2f1df5510 100644
--- a/src/test/java/de/caritas/cob/userservice/api/model/ChatAgencyTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/model/ChatAgencyTest.java
@@ -4,7 +4,7 @@
import static org.hamcrest.Matchers.is;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class ChatAgencyTest {
diff --git a/src/test/java/de/caritas/cob/userservice/api/model/ChatTest.java b/src/test/java/de/caritas/cob/userservice/api/model/ChatTest.java
index 9b329d826..37236ad33 100644
--- a/src/test/java/de/caritas/cob/userservice/api/model/ChatTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/model/ChatTest.java
@@ -3,10 +3,11 @@
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import de.caritas.cob.userservice.api.exception.httpresponses.InternalServerErrorException;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class ChatTest {
@@ -52,12 +53,16 @@ public void equals_Should_returnTrue_When_sessionIdsAreEqual() {
assertThat(equals, is(true));
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void nextDateShouldThrowExceptionWhenChatIsRepetitiveButNoStartDate() {
- var chat = new Chat();
- chat.setRepetitive(true);
-
- chat.nextStart();
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ var chat = new Chat();
+ chat.setRepetitive(true);
+
+ chat.nextStart();
+ });
}
@Test
diff --git a/src/test/java/de/caritas/cob/userservice/api/model/ConsultantAgencyTest.java b/src/test/java/de/caritas/cob/userservice/api/model/ConsultantAgencyTest.java
index 191b93761..d963f81cb 100644
--- a/src/test/java/de/caritas/cob/userservice/api/model/ConsultantAgencyTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/model/ConsultantAgencyTest.java
@@ -4,7 +4,7 @@
import static org.hamcrest.Matchers.is;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class ConsultantAgencyTest {
diff --git a/src/test/java/de/caritas/cob/userservice/api/model/ConsultantTest.java b/src/test/java/de/caritas/cob/userservice/api/model/ConsultantTest.java
index dfda9cf2f..71bb565ed 100644
--- a/src/test/java/de/caritas/cob/userservice/api/model/ConsultantTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/model/ConsultantTest.java
@@ -2,15 +2,15 @@
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import com.neovisionaries.i18n.LanguageCode;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class ConsultantTest {
private static final String FIRSTNAME = "firstname";
diff --git a/src/test/java/de/caritas/cob/userservice/api/model/LiquibaseHibernateIT.java b/src/test/java/de/caritas/cob/userservice/api/model/LiquibaseHibernateIT.java
deleted file mode 100644
index 0a9c430aa..000000000
--- a/src/test/java/de/caritas/cob/userservice/api/model/LiquibaseHibernateIT.java
+++ /dev/null
@@ -1,44 +0,0 @@
-package de.caritas.cob.userservice.api.model;
-
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import de.caritas.cob.userservice.api.port.out.UserRepository;
-import org.junit.jupiter.api.Test;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
-import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
-import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.test.context.DynamicPropertyRegistry;
-import org.springframework.test.context.DynamicPropertySource;
-import org.testcontainers.containers.MariaDBContainer;
-import org.testcontainers.junit.jupiter.Container;
-import org.testcontainers.junit.jupiter.Testcontainers;
-
-@Testcontainers
-@AutoConfigureTestDatabase(replace = Replace.NONE)
-@SpringBootTest(
- properties = {
- "spring.jpa.hibernate.ddl-auto=validate",
- "identity.technical-user.username=tech-user",
- "identity.technical-user.password=tech-pass"
- })
-class LiquibaseHibernateIT {
- @Container
- @SuppressWarnings("resource")
- static MariaDBContainer> DB =
- new MariaDBContainer<>("mariadb:10.5.10").withDatabaseName("userservice");
-
- @Autowired UserRepository userRepository;
-
- @DynamicPropertySource
- static void registerMySQLProperties(DynamicPropertyRegistry registry) {
- registry.add("spring.datasource.url", DB::getJdbcUrl);
- registry.add("spring.datasource.username", DB::getUsername);
- registry.add("spring.datasource.password", DB::getPassword);
- }
-
- @Test
- void databaseAndEntityMappingsShouldBeInSync() {
- assertTrue(userRepository.count() > -1);
- }
-}
diff --git a/src/test/java/de/caritas/cob/userservice/api/model/SessionDataTest.java b/src/test/java/de/caritas/cob/userservice/api/model/SessionDataTest.java
index 49b7527e4..630231053 100644
--- a/src/test/java/de/caritas/cob/userservice/api/model/SessionDataTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/model/SessionDataTest.java
@@ -4,7 +4,7 @@
import static org.hamcrest.Matchers.is;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class SessionDataTest {
diff --git a/src/test/java/de/caritas/cob/userservice/api/model/SessionTest.java b/src/test/java/de/caritas/cob/userservice/api/model/SessionTest.java
index 1173ac90f..e56c276bd 100644
--- a/src/test/java/de/caritas/cob/userservice/api/model/SessionTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/model/SessionTest.java
@@ -4,7 +4,7 @@
import static org.hamcrest.Matchers.is;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class SessionTest {
diff --git a/src/test/java/de/caritas/cob/userservice/api/model/UserAgencyTest.java b/src/test/java/de/caritas/cob/userservice/api/model/UserAgencyTest.java
index c876109af..cd5bdcec5 100644
--- a/src/test/java/de/caritas/cob/userservice/api/model/UserAgencyTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/model/UserAgencyTest.java
@@ -4,7 +4,7 @@
import static org.hamcrest.Matchers.is;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class UserAgencyTest {
diff --git a/src/test/java/de/caritas/cob/userservice/api/model/UserTest.java b/src/test/java/de/caritas/cob/userservice/api/model/UserTest.java
index 3b0643334..06825c4c9 100644
--- a/src/test/java/de/caritas/cob/userservice/api/model/UserTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/model/UserTest.java
@@ -4,7 +4,7 @@
import static org.hamcrest.Matchers.is;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class UserTest {
diff --git a/src/test/java/de/caritas/cob/userservice/api/port/out/UserChatRepositoryTest.java b/src/test/java/de/caritas/cob/userservice/api/port/out/UserChatRepositoryTest.java
index 16ae96cb2..03d440ff0 100644
--- a/src/test/java/de/caritas/cob/userservice/api/port/out/UserChatRepositoryTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/port/out/UserChatRepositoryTest.java
@@ -13,10 +13,12 @@
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
+import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.TestPropertySource;
@DataJpaTest
@TestPropertySource(properties = "spring.profiles.active=testing")
+@ActiveProfiles("testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
class UserChatRepositoryTest {
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/ChatServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/service/ChatServiceTest.java
index edd787836..05d925f37 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/ChatServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/ChatServiceTest.java
@@ -17,11 +17,7 @@
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -45,18 +41,18 @@
import java.time.LocalTime;
import java.util.List;
import java.util.Optional;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
-@RunWith(MockitoJUnitRunner.class)
-public class ChatServiceTest {
+@ExtendWith(MockitoExtension.class)
+class ChatServiceTest {
@InjectMocks private ChatService chatService;
@@ -72,13 +68,13 @@ public class ChatServiceTest {
@Mock private AgencyService agencyService;
- @Before
- public void setup() {
+ @BeforeEach
+ void setup() {
setInternalState(LogService.class, "LOGGER", logger);
}
@Test
- public void getChatsForUserId_Should_CallFindByUserIdAndFindAssignedByUserIdOnChatRepository() {
+ void getChatsForUserId_Should_CallFindByUserIdAndFindAssignedByUserIdOnChatRepository() {
chatService.getChatsForUserId(USER_ID);
verify(chatRepository).findByUserId(USER_ID);
@@ -86,7 +82,7 @@ public void getChatsForUserId_Should_CallFindByUserIdAndFindAssignedByUserIdOnCh
}
@Test
- public void getChatsForUserId_Should_ConcatChatsAndAssignedChats() {
+ void getChatsForUserId_Should_ConcatChatsAndAssignedChats() {
when(chatRepository.findByUserId(USER_ID)).thenReturn(singletonList(ACTIVE_CHAT));
when(chatRepository.findAssignedByUserId(USER_ID)).thenReturn(singletonList(CHAT_V2));
@@ -96,7 +92,7 @@ public void getChatsForUserId_Should_ConcatChatsAndAssignedChats() {
}
@Test
- public void getChatsForUserId_Should_ReturnListOfUserSessionResponseDTOWithChats() {
+ void getChatsForUserId_Should_ReturnListOfUserSessionResponseDTOWithChats() {
when(chatRepository.findByUserId(USER_ID)).thenReturn(singletonList(ACTIVE_CHAT));
when(consultantService.findConsultantsByAgencyIds(Mockito.any()))
.thenReturn(singletonList(CONSULTANT));
@@ -130,7 +126,7 @@ public void getChatsForUserId_Should_ReturnListOfUserSessionResponseDTOWithChats
}
@Test
- public void
+ void
getChatsForUserId_Should_ReturnListOfUserSessionResponseDTOWithChats_When_AssignedChatIsFound() {
when(chatRepository.findAssignedByUserId(USER_ID)).thenReturn(singletonList(CHAT_V2));
when(consultantService.findConsultantsByAgencyIds(Mockito.any()))
@@ -177,7 +173,7 @@ public void getChatsForUserId_Should_ReturnListOfUserSessionResponseDTOWithChats
}
@Test
- public void getChatsForConsultant_Should_ReturnListOfConsultantSessionResponseDTOWithChats() {
+ void getChatsForConsultant_Should_ReturnListOfConsultantSessionResponseDTOWithChats() {
Consultant consultant = Mockito.mock(Consultant.class);
when(chatRepository.findByAgencyIds(Mockito.any())).thenReturn(singletonList(ACTIVE_CHAT));
@@ -213,7 +209,7 @@ public void getChatsForConsultant_Should_ReturnListOfConsultantSessionResponseDT
}
@Test
- public void getChatsForConsultant_Should_ReturnEmptyListWhenListOfChatsIsEmpty() {
+ void getChatsForConsultant_Should_ReturnEmptyListWhenListOfChatsIsEmpty() {
Consultant consultant = Mockito.mock(Consultant.class);
List resultList = chatService.getChatsForConsultant(consultant);
@@ -222,7 +218,7 @@ public void getChatsForConsultant_Should_ReturnEmptyListWhenListOfChatsIsEmpty()
}
@Test
- public void getChat_Should_ReturnChatObject() {
+ void getChat_Should_ReturnChatObject() {
when(chatRepository.findById(CHAT_ID)).thenReturn(Optional.of(ACTIVE_CHAT));
Optional result = chatService.getChat(CHAT_ID);
@@ -233,7 +229,7 @@ public void getChat_Should_ReturnChatObject() {
}
@Test
- public void getChatByGroupId_Should_ReturnChatObject() {
+ void getChatByGroupId_Should_ReturnChatObject() {
when(chatRepository.findByGroupId(RC_GROUP_ID)).thenReturn(Optional.of(ACTIVE_CHAT));
Optional result = chatService.getChatByGroupId(RC_GROUP_ID);
@@ -244,43 +240,43 @@ public void getChatByGroupId_Should_ReturnChatObject() {
}
@Test
- public void updateChat_Should_ThrowBadRequestException_WhenChatDoesNotExist() {
+ void updateChat_Should_ThrowBadRequestException_WhenChatDoesNotExist() {
when(chatRepository.findById(CHAT_ID)).thenReturn(Optional.empty());
try {
chatService.updateChat(CHAT_ID, CHAT_DTO, AUTHENTICATED_USER);
fail("Expected exception: BadRequestException");
} catch (BadRequestException badRequestException) {
- assertTrue("Excepted BadRequestException thrown", true);
+ assertTrue(true, "Excepted BadRequestException thrown");
}
}
@Test
- public void updateChat_Should_ThrowForbiddenException_WhenCallingConsultantNotOwnerOfChat() {
+ void updateChat_Should_ThrowForbiddenException_WhenCallingConsultantNotOwnerOfChat() {
when(chatRepository.findById(CHAT_ID)).thenReturn(Optional.of(INACTIVE_CHAT));
try {
chatService.updateChat(CHAT_ID, CHAT_DTO, AUTHENTICATED_USER_3);
fail("Expected exception: ForbiddenException");
} catch (ForbiddenException forbiddenException) {
- assertTrue("Excepted ForbiddenException thrown", true);
+ assertTrue(true, "Excepted ForbiddenException thrown");
}
}
@Test
- public void updateChat_Should_ThrowConflictException_WhenChatIsActive() {
+ void updateChat_Should_ThrowConflictException_WhenChatIsActive() {
when(chatRepository.findById(CHAT_ID)).thenReturn(Optional.of(ACTIVE_CHAT));
try {
chatService.updateChat(CHAT_ID, CHAT_DTO, AUTHENTICATED_USER_CONSULTANT);
fail("Expected exception: ConflictException");
} catch (ConflictException conflictException) {
- assertTrue("Excepted ConflictException thrown", true);
+ assertTrue(true, "Excepted ConflictException thrown");
}
}
@Test
- public void updateChat_Should_SaveNewChatSettings() {
+ void updateChat_Should_SaveNewChatSettings() {
// given
Chat inactiveChat = new Chat();
inactiveChat.setActive(false);
@@ -298,7 +294,7 @@ public void updateChat_Should_SaveNewChatSettings() {
}
@Test
- public void saveChatAgencyRelation_Should_saveChatAgencyInRepository() {
+ void saveChatAgencyRelation_Should_saveChatAgencyInRepository() {
ChatAgency chatAgency = new ChatAgency();
chatService.saveChatAgencyRelation(chatAgency);
@@ -307,7 +303,7 @@ public void saveChatAgencyRelation_Should_saveChatAgencyInRepository() {
}
@Test
- public void saveUserChatRelation_Should_saveUserChatInRepository() {
+ void saveUserChatRelation_Should_saveUserChatInRepository() {
UserChat chatUser = new UserChat();
chatService.saveUserChatRelation(chatUser);
@@ -316,7 +312,7 @@ public void saveUserChatRelation_Should_saveUserChatInRepository() {
}
@Test
- public void deleteChat_Should_deleteChatInRepository() {
+ void deleteChat_Should_deleteChatInRepository() {
Chat chat = new Chat();
chatService.deleteChat(chat);
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/ConsultantAgencyServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/service/ConsultantAgencyServiceTest.java
index 6acd4637b..0f5f18cc2 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/ConsultantAgencyServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/ConsultantAgencyServiceTest.java
@@ -7,9 +7,7 @@
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -31,16 +29,16 @@
import java.util.List;
import java.util.stream.Collectors;
import org.jeasy.random.EasyRandom;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.slf4j.Logger;
-import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
-@RunWith(SpringRunner.class)
+@ExtendWith(SpringExtension.class)
public class ConsultantAgencyServiceTest {
private final String CONSULTANT_ID = "1b71cc46-650d-42bb-8299-f8e3f6d7249a";
@@ -105,7 +103,7 @@ public class ConsultantAgencyServiceTest {
@SuppressWarnings("unused")
private UserDtoMapper userDtoMapper;
- @Before
+ @BeforeEach
public void setup() {
setInternalState(LogService.class, "LOGGER", logger);
}
@@ -142,7 +140,7 @@ public void findConsultantsByAgencyId_Should_ReturnListOfConsultantAgency_WhenAg
consultantAgencyService.getConsultantsOfAgency(AGENCY_ID);
fail("Expected exception: InternalServerErrorException");
} catch (InternalServerErrorException serviceException) {
- assertTrue("Excepted InternalServerErrorException thrown", true);
+ assertTrue(true, "Excepted InternalServerErrorException thrown");
}
}
@@ -158,7 +156,7 @@ public void findConsultantsByAgencyId_Should_ReturnListOfConsultantAgency_WhenAg
consultantAgencyService.getConsultantsOfAgency(AGENCY_ID);
fail("Expected exception: InternalServerErrorException");
} catch (InternalServerErrorException serviceException) {
- assertTrue("Excepted InternalServerErrorException thrown", true);
+ assertTrue(true, "Excepted InternalServerErrorException thrown");
}
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/ConsultantServiceIT.java b/src/test/java/de/caritas/cob/userservice/api/service/ConsultantServiceIT.java
index 29faa4633..453cf9178 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/ConsultantServiceIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/ConsultantServiceIT.java
@@ -3,14 +3,11 @@
import de.caritas.cob.userservice.api.UserServiceApplication;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
-import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
-@RunWith(SpringRunner.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/ConsultingTypeServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/service/ConsultingTypeServiceTest.java
index 633cdd3aa..cc27f520c 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/ConsultingTypeServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/ConsultingTypeServiceTest.java
@@ -1,6 +1,6 @@
package de.caritas.cob.userservice.api.service;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/DecryptionServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/service/DecryptionServiceTest.java
index 2d3b88da6..b206b04bb 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/DecryptionServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/DecryptionServiceTest.java
@@ -1,19 +1,17 @@
package de.caritas.cob.userservice.api.service;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
import de.caritas.cob.userservice.api.exception.CustomCryptoException;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.util.ReflectionTestUtils;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class DecryptionServiceTest {
private final String KEY_MASTER = "MasterKeyTestKey";
@@ -30,7 +28,7 @@ public class DecryptionServiceTest {
@Mock private LogService logService;
- @Before
+ @BeforeEach
public void setup() throws NoSuchFieldException {
ReflectionTestUtils.setField(encryptionService, FIELD_NAME_FRAGMENT_APP_KEY, KEY_APPLICATION);
encryptionService.updateMasterKey(KEY_MASTER);
@@ -38,24 +36,24 @@ public void setup() throws NoSuchFieldException {
@Test
public void check_setup() {
- assertEquals("MasterKey was not properly set", KEY_MASTER, encryptionService.getMasterKey());
+ assertEquals(KEY_MASTER, encryptionService.getMasterKey(), "MasterKey was not properly set");
assertEquals(
- "ApplicationKey was not properly set",
KEY_APPLICATION,
- encryptionService.getApplicationKey());
+ encryptionService.getApplicationKey(),
+ "ApplicationKey was not properly set");
}
@Test
public void updateMasterKey_Should_UpdateMasterKeyFragment() {
encryptionService.updateMasterKey(KEY_MASTER);
- assertEquals("Cannot properly set MasterKey", KEY_MASTER, encryptionService.getMasterKey());
+ assertEquals(KEY_MASTER, encryptionService.getMasterKey(), "Cannot properly set MasterKey");
}
@Test
public void decrypt_Should_ReturnDecryptedText_WhenProvidedWithValidParameters()
throws Exception {
String decryptedMessage = encryptionService.decrypt(MESSAGE_ENCRYPTED, KEY_SESSION);
- assertEquals("Did not get the expected decrypted result.", MESSAGE_PLAIN, decryptedMessage);
+ assertEquals(MESSAGE_PLAIN, decryptedMessage, "Did not get the expected decrypted result.");
}
@Test
@@ -64,7 +62,7 @@ public void decrypt_Should_ReturnWrongDecryptedText_WhenProvidedWithInvalidParam
encryptionService.decrypt(MESSAGE_ENCRYPTED, KEY_SESSION_WRONG);
fail("The expected BadPaddingException due to wrong password was not thrown.");
} catch (CustomCryptoException ex) {
- assertTrue("Expected BadPaddingException thrown", true);
+ assertTrue(true, "Expected BadPaddingException thrown");
}
}
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/LogServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/service/LogServiceTest.java
index 02849e0c3..f72b87a48 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/LogServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/LogServiceTest.java
@@ -13,14 +13,14 @@
import static org.powermock.reflect.Whitebox.setInternalState;
import java.io.PrintWriter;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class LogServiceTest {
private final String ERROR_MESSAGE = "Error message";
@@ -29,7 +29,7 @@ public class LogServiceTest {
@Mock private Logger logger;
- @Before
+ @BeforeEach
public void setup() {
setInternalState(LogService.class, "LOGGER", logger);
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/RocketChatServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/service/RocketChatServiceTest.java
index f04954fef..153bbca19 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/RocketChatServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/RocketChatServiceTest.java
@@ -30,13 +30,7 @@
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
-import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
@@ -100,15 +94,17 @@
import org.bson.Document;
import org.bson.conversions.Bson;
import org.jeasy.random.EasyRandom;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatchers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
import org.slf4j.Logger;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
@@ -119,8 +115,9 @@
import org.springframework.web.client.RestClientResponseException;
import org.springframework.web.client.RestTemplate;
-@RunWith(MockitoJUnitRunner.class)
-public class RocketChatServiceTest {
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
+class RocketChatServiceTest {
private final String MESSAGE = "Lorem Ipsum";
private final String GROUP_ID = "xxxYYY";
@@ -195,8 +192,8 @@ public class RocketChatServiceTest {
@Mock private FindIterable findIterable;
- @Before
- public void setup() {
+ @BeforeEach
+ void setup() {
rocketChatConfig.setBaseUrl("http://localhost/api/v1");
setField(rocketChatService, "rocketChatConfig", rocketChatConfig);
@@ -205,7 +202,7 @@ public void setup() {
/** Method: createPrivateGroup */
@Test
- public void createPrivateGroup_Should_ReturnTheGroupId_WhenRocketChatApiCallWasSuccessfully()
+ void createPrivateGroup_Should_ReturnTheGroupId_WhenRocketChatApiCallWasSuccessfully()
throws SecurityException, RocketChatCreateGroupException {
when(restTemplate.postForObject(
@@ -220,7 +217,7 @@ public void createPrivateGroup_Should_ReturnTheGroupId_WhenRocketChatApiCallWasS
}
@Test
- public void
+ void
createPrivateGroup_Should_ThrowRocketChatCreateGroupException_WhenApiCallFailsWithAnException()
throws SecurityException {
@@ -234,13 +231,13 @@ public void createPrivateGroup_Should_ReturnTheGroupId_WhenRocketChatApiCallWasS
rocketChatService.createPrivateGroup(GROUP_NAME, RC_CREDENTIALS);
fail("Expected exception: RocketChatCreateGroupException");
} catch (RocketChatCreateGroupException rocketChatCreateGroupException) {
- assertTrue("Excepted RocketChatCreateGroupException thrown", true);
+ assertTrue(true, "Excepted RocketChatCreateGroupException thrown");
}
}
/** Method: deleteGroup */
@Test
- public void deleteGroup_Should_ReturnTrue_WhenApiCallIsSuccessful() throws SecurityException {
+ void deleteGroup_Should_ReturnTrue_WhenApiCallIsSuccessful() throws SecurityException {
GroupDeleteResponseDTO response = new GroupDeleteResponseDTO(true);
@@ -256,8 +253,7 @@ public void deleteGroup_Should_ReturnTrue_WhenApiCallIsSuccessful() throws Secur
}
@Test
- public void deleteGroup_Should_ReturnFalseAndLog_WhenApiCallIsNotSuccessful()
- throws SecurityException {
+ void deleteGroup_Should_ReturnFalseAndLog_WhenApiCallIsNotSuccessful() throws SecurityException {
GroupDeleteResponseDTO response = new GroupDeleteResponseDTO(false);
@@ -275,7 +271,7 @@ public void deleteGroup_Should_ReturnFalseAndLog_WhenApiCallIsNotSuccessful()
}
@Test
- public void rollbackGroup_Should_Log_WhenApiCallFailsWithAnException() throws SecurityException {
+ void rollbackGroup_Should_Log_WhenApiCallFailsWithAnException() throws SecurityException {
HttpServerErrorException httpServerErrorException =
new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, "HttpServerErrorException");
@@ -290,18 +286,18 @@ public void rollbackGroup_Should_Log_WhenApiCallFailsWithAnException() throws Se
/** Method: addUserToGroup */
@Test
- public void addUserToGroup_Should_ThrowRocketChatAddUserToGroupException_WheApiCallFails() {
+ void addUserToGroup_Should_ThrowRocketChatAddUserToGroupException_WheApiCallFails() {
try {
rocketChatService.addUserToGroup(RC_USER_ID, GROUP_ID);
fail("Expected exception: RocketChatAddUserToGroupException");
} catch (RocketChatAddUserToGroupException rcAddToGroupEx) {
- assertTrue("Excepted RocketChatAddUserToGroupException thrown", true);
+ assertTrue(true, "Excepted RocketChatAddUserToGroupException thrown");
}
}
@Test
- public void addUserToGroup_Should_ThrowRocketChatLoginException_WhenResponseIsNotSuccessful()
+ void addUserToGroup_Should_ThrowRocketChatLoginException_WhenResponseIsNotSuccessful()
throws RocketChatUserNotInitializedException {
GroupResponseDTO groupResponseDTO = new GroupResponseDTO(null, false, "error", "errorType");
@@ -316,13 +312,13 @@ public void addUserToGroup_Should_ThrowRocketChatLoginException_WhenResponseIsNo
rocketChatService.addUserToGroup(RC_USER_ID, GROUP_ID);
fail("Expected exception: RocketChatAddUserToGroupException");
} catch (RocketChatAddUserToGroupException rcAddToGroupEx) {
- assertTrue("Excepted RocketChatAddUserToGroupException thrown", true);
+ assertTrue(true, "Excepted RocketChatAddUserToGroupException thrown");
}
}
/** Method: removeUserFromGroup */
@Test
- public void
+ void
removeUserFromGroup_Should_ThrowRocketChatRemoveUserFromGroupException_WhenAPICallIsNotSuccessful()
throws RocketChatUserNotInitializedException {
@@ -338,12 +334,12 @@ public void addUserToGroup_Should_ThrowRocketChatLoginException_WhenResponseIsNo
rocketChatService.removeUserFromGroup(RC_USER_ID, GROUP_ID);
fail("Expected exception: RocketChatRemoveUserFromGroupException");
} catch (RocketChatRemoveUserFromGroupException ex) {
- assertTrue("Excepted RocketChatRemoveUserFromGroupException thrown", true);
+ assertTrue(true, "Excepted RocketChatRemoveUserFromGroupException thrown");
}
}
@Test
- public void
+ void
removeUserFromGroup_Should_ThrowRocketChatRemoveUserFromGroupException_WhenAPIResponseIsUnSuccessful()
throws Exception {
@@ -357,13 +353,13 @@ public void addUserToGroup_Should_ThrowRocketChatLoginException_WhenResponseIsNo
rocketChatService.removeUserFromGroup(RC_USER_ID, GROUP_ID);
fail("Expected exception: RocketChatRemoveUserFromGroupException");
} catch (RocketChatRemoveUserFromGroupException ex) {
- assertTrue("Excepted RocketChatRemoveUserFromGroupException thrown", true);
+ assertTrue(true, "Excepted RocketChatRemoveUserFromGroupException thrown");
}
}
/** Method: createPrivateGroupWithSystemUser */
@Test
- public void
+ void
createPrivateGroupWithSystemUser_Should_ReturnTheGroupId_When_RocketChatApiCallWasSuccessful()
throws Exception {
@@ -382,7 +378,7 @@ public void addUserToGroup_Should_ThrowRocketChatLoginException_WhenResponseIsNo
/** Method: removeSystemMessages */
@Test
- public void
+ void
removeSystemMessages_Should_ThrowRocketChatRemoveSystemMessagesException_WhenApiCallFailsWithAnException()
throws RocketChatUserNotInitializedException {
@@ -401,12 +397,12 @@ public void addUserToGroup_Should_ThrowRocketChatLoginException_WhenResponseIsNo
rocketChatService.removeSystemMessages(GROUP_ID, DATETIME_OLDEST, DATETIME_LATEST);
fail("Expected exception: RocketChatRemoveSystemMessagesException");
} catch (RocketChatRemoveSystemMessagesException rocketChatRemoveSystemMessagesException) {
- assertTrue("Excepted RocketChatRemoveSystemMessagesException thrown", true);
+ assertTrue(true, "Excepted RocketChatRemoveSystemMessagesException thrown");
}
}
@Test
- public void
+ void
removeSystemMessages_Should_ThrowRocketChatRemoveSystemMessagesException_WhenDateFormatIsWrong()
throws RocketChatUserNotInitializedException {
@@ -416,30 +412,32 @@ public void addUserToGroup_Should_ThrowRocketChatLoginException_WhenResponseIsNo
rocketChatService.removeSystemMessages(GROUP_ID, DATETIME_OLDEST, null);
fail("Expected exception: RocketChatRemoveSystemMessagesException");
} catch (RocketChatRemoveSystemMessagesException rocketChatRemoveSystemMessagesException) {
- assertTrue("Excepted RocketChatRemoveSystemMessagesException thrown", true);
+ assertTrue(true, "Excepted RocketChatRemoveSystemMessagesException thrown");
}
}
- @Test(expected = RocketChatRemoveSystemMessagesException.class)
- public void removeSystemMessages_Should_ReturnFalseAndLogError_WhenApiCallIsUnSuccessful()
+ @Test
+ void removeSystemMessages_Should_ReturnFalseAndLogError_WhenApiCallIsUnSuccessful()
throws Exception {
+ assertThrows(
+ RocketChatRemoveSystemMessagesException.class,
+ () -> {
+ when(restTemplate.postForObject(
+ ArgumentMatchers.anyString(),
+ any(),
+ ArgumentMatchers.>any()))
+ .thenReturn(STANDARD_RESPONSE_DTO_ERROR);
- when(restTemplate.postForObject(
- ArgumentMatchers.anyString(),
- any(),
- ArgumentMatchers.>any()))
- .thenReturn(STANDARD_RESPONSE_DTO_ERROR);
-
- when(rcCredentialsHelper.getTechnicalUser()).thenReturn(RC_CREDENTIALS_TECHNICAL_A);
+ when(rcCredentialsHelper.getTechnicalUser()).thenReturn(RC_CREDENTIALS_TECHNICAL_A);
- rocketChatService.removeSystemMessages(GROUP_ID, DATETIME_OLDEST, DATETIME_LATEST);
+ rocketChatService.removeSystemMessages(GROUP_ID, DATETIME_OLDEST, DATETIME_LATEST);
- verify(logger, atLeastOnce()).error(anyString(), anyString(), anyString());
+ verify(logger, atLeastOnce()).error(anyString(), anyString(), anyString());
+ });
}
@Test
- public void removeSystemMessages_Should_NotThrowException_WhenApiCallIsSuccessful()
- throws Exception {
+ void removeSystemMessages_Should_NotThrowException_WhenApiCallIsSuccessful() throws Exception {
when(restTemplate.postForObject(
ArgumentMatchers.anyString(),
@@ -455,7 +453,7 @@ public void removeSystemMessages_Should_NotThrowException_WhenApiCallIsSuccessfu
/** Method: getUserId */
@Test
- public void getUserId_Should_LoginUser() throws RocketChatLoginException {
+ void getUserId_Should_LoginUser() throws RocketChatLoginException {
when(rcCredentialsHelper.loginUser(any(), any()))
.thenReturn(new ResponseEntity<>(LOGIN_RESPONSE_DTO_TECH_USER, HttpStatus.OK));
@@ -472,7 +470,7 @@ public void getUserId_Should_LoginUser() throws RocketChatLoginException {
}
@Test
- public void getUserId_Should_LogoutUser() throws RocketChatLoginException {
+ void getUserId_Should_LogoutUser() throws RocketChatLoginException {
when(rcCredentialsHelper.loginUser(any(), any()))
.thenReturn(new ResponseEntity<>(LOGIN_RESPONSE_DTO_TECH_USER, HttpStatus.OK));
@@ -489,7 +487,7 @@ public void getUserId_Should_LogoutUser() throws RocketChatLoginException {
}
@Test
- public void getUserId_Should_ReturnCorrectUserId() throws RocketChatLoginException {
+ void getUserId_Should_ReturnCorrectUserId() throws RocketChatLoginException {
when(rcCredentialsHelper.loginUser(any(), any()))
.thenReturn(new ResponseEntity<>(LOGIN_RESPONSE_DTO_TECH_USER, HttpStatus.OK));
@@ -507,7 +505,7 @@ public void getUserId_Should_ReturnCorrectUserId() throws RocketChatLoginExcepti
/** Method: getSubscriptionsOfUser */
@Test
- public void
+ void
getSubscriptionsOfUser_Should_ThrowInternalServerErrorException_When_APICallIsNotSuccessful() {
when(restTemplate.exchange(
@@ -521,12 +519,12 @@ public void getUserId_Should_ReturnCorrectUserId() throws RocketChatLoginExcepti
rocketChatService.getSubscriptionsOfUser(RC_CREDENTIALS);
fail("Expected exception: InternalServerErrorException");
} catch (InternalServerErrorException ex) {
- assertTrue("Excepted InternalServerErrorException thrown", true);
+ assertTrue(true, "Excepted InternalServerErrorException thrown");
}
}
@Test
- public void
+ void
getSubscriptionsOfUser_Should_ThrowInternalServerErrorException_When_APIResponseIsUnSuccessful() {
when(restTemplate.exchange(
@@ -540,12 +538,12 @@ public void getUserId_Should_ReturnCorrectUserId() throws RocketChatLoginExcepti
rocketChatService.getSubscriptionsOfUser(RC_CREDENTIALS);
fail("Expected exception: InternalServerErrorException");
} catch (InternalServerErrorException ex) {
- assertTrue("Excepted InternalServerErrorException thrown", true);
+ assertTrue(true, "Excepted InternalServerErrorException thrown");
}
}
@Test
- public void
+ void
getSubscriptionsOfUser_Should_ThrowUnauthorizedException_When_RocketChatReturnsUnauthorized() {
when(restTemplate.exchange(
@@ -565,8 +563,7 @@ public void getUserId_Should_ReturnCorrectUserId() throws RocketChatLoginExcepti
}
@Test
- public void
- getSubscriptionsOfUser_Should_ReturnListOfSubscriptionsUpdateDTO_When_APICallIsSuccessful() {
+ void getSubscriptionsOfUser_Should_ReturnListOfSubscriptionsUpdateDTO_When_APICallIsSuccessful() {
when(restTemplate.exchange(
ArgumentMatchers.anyString(),
@@ -582,8 +579,7 @@ public void getUserId_Should_ReturnCorrectUserId() throws RocketChatLoginExcepti
/** Method: getRoomsOfUser */
@Test
- public void
- getRoomsOfUser_Should_ThrowInternalServerErrorException_When_APICallIsNotSuccessful() {
+ void getRoomsOfUser_Should_ThrowInternalServerErrorException_When_APICallIsNotSuccessful() {
Exception exception = new RuntimeException(MESSAGE);
@@ -595,13 +591,12 @@ public void getUserId_Should_ReturnCorrectUserId() throws RocketChatLoginExcepti
rocketChatService.getRoomsOfUser(RC_CREDENTIALS);
fail("Expected exception: InternalServerErrorException");
} catch (InternalServerErrorException ex) {
- assertTrue("Excepted InternalServerErrorException thrown", true);
+ assertTrue(true, "Excepted InternalServerErrorException thrown");
}
}
@Test
- public void
- getRoomsOfUser_Should_ThrowInternalServerErrorException_When_APIResponseIsUnSuccessful() {
+ void getRoomsOfUser_Should_ThrowInternalServerErrorException_When_APIResponseIsUnSuccessful() {
when(restTemplate.exchange(
ArgumentMatchers.anyString(), any(), any(), ArgumentMatchers.>any()))
@@ -611,12 +606,12 @@ public void getUserId_Should_ReturnCorrectUserId() throws RocketChatLoginExcepti
rocketChatService.getRoomsOfUser(RC_CREDENTIALS);
fail("Expected exception: InternalServerErrorException");
} catch (InternalServerErrorException ex) {
- assertTrue("Excepted InternalServerErrorException thrown", true);
+ assertTrue(true, "Excepted InternalServerErrorException thrown");
}
}
@Test
- public void getRoomsOfUser_Should_ReturnListOfRoomsUpdateDTO_WhenAPICallIsSuccessful() {
+ void getRoomsOfUser_Should_ReturnListOfRoomsUpdateDTO_WhenAPICallIsSuccessful() {
when(restTemplate.exchange(
ArgumentMatchers.anyString(), any(), any(), ArgumentMatchers.>any()))
@@ -629,7 +624,7 @@ public void getRoomsOfUser_Should_ReturnListOfRoomsUpdateDTO_WhenAPICallIsSucces
/** Method: removeAllStandardUsersFromGroup */
@Test
- public void
+ void
removeAllStandardUsersFromGroup_Should_ThrowRocketChatGetGroupMembersException_WhenGroupListIsEmpty()
throws Exception {
@@ -641,14 +636,13 @@ public void getRoomsOfUser_Should_ReturnListOfRoomsUpdateDTO_WhenAPICallIsSucces
spy.removeAllStandardUsersFromGroup(GROUP_ID);
fail("Expected exception: RocketChatGetGroupMembersException");
} catch (RocketChatGetGroupMembersException rocketChatGetGroupMembersException) {
- assertTrue("Excepted RocketChatGetGroupMembersException thrown", true);
+ assertTrue(true, "Excepted RocketChatGetGroupMembersException thrown");
}
}
@Test
- public void
- removeAllStandardUsersFromGroup_Should_RemoveAllStandardUsersAndNotTechnicalOrSystemUser()
- throws Exception {
+ void removeAllStandardUsersFromGroup_Should_RemoveAllStandardUsersAndNotTechnicalOrSystemUser()
+ throws Exception {
RocketChatService spy = Mockito.spy(rocketChatService);
@@ -669,8 +663,7 @@ public void getRoomsOfUser_Should_ReturnListOfRoomsUpdateDTO_WhenAPICallIsSucces
/** Method: removeAllMessages */
@Test
- public void removeAllMessages_Should_NotThrowException_WhenRemoveMessagesSucceeded()
- throws Exception {
+ void removeAllMessages_Should_NotThrowException_WhenRemoveMessagesSucceeded() throws Exception {
when(restTemplate.postForObject(
ArgumentMatchers.anyString(),
@@ -683,25 +676,28 @@ public void removeAllMessages_Should_NotThrowException_WhenRemoveMessagesSucceed
assertDoesNotThrow(() -> rocketChatService.removeAllMessages(GROUP_ID));
}
- @Test(expected = RocketChatRemoveSystemMessagesException.class)
- public void
+ @Test
+ void
removeAllMessages_Should_ThrowRocketChatRemoveSystemMessagesException_WhenRemoveMessagesFails()
throws Exception {
-
- when(restTemplate.postForObject(
- ArgumentMatchers.anyString(),
- any(),
- ArgumentMatchers.>any()))
- .thenReturn(STANDARD_RESPONSE_DTO_ERROR);
-
- when(rcCredentialsHelper.getTechnicalUser()).thenReturn(RC_CREDENTIALS_TECHNICAL_A);
-
- rocketChatService.removeAllMessages(GROUP_ID);
+ assertThrows(
+ RocketChatRemoveSystemMessagesException.class,
+ () -> {
+ when(restTemplate.postForObject(
+ ArgumentMatchers.anyString(),
+ any(),
+ ArgumentMatchers.>any()))
+ .thenReturn(STANDARD_RESPONSE_DTO_ERROR);
+
+ when(rcCredentialsHelper.getTechnicalUser()).thenReturn(RC_CREDENTIALS_TECHNICAL_A);
+
+ rocketChatService.removeAllMessages(GROUP_ID);
+ });
}
/** Method: getStandardMembersOfGroup */
@Test
- public void
+ void
getStandardMembersOfGroup_Should_ThrowRocketChatGetGroupMembersException_WhenAPICallIsNotSuccessful() {
Exception exception = new RuntimeException(MESSAGE);
@@ -712,26 +708,25 @@ public void removeAllMessages_Should_NotThrowException_WhenRemoveMessagesSucceed
rocketChatService.getStandardMembersOfGroup(GROUP_ID);
fail("Expected exception: RocketChatGetGroupMembersException");
} catch (RocketChatGetGroupMembersException | RocketChatUserNotInitializedException ex) {
- assertTrue("Excepted RocketChatGetGroupMembersException thrown", true);
+ assertTrue(true, "Excepted RocketChatGetGroupMembersException thrown");
}
}
@Test
- public void
+ void
getStandardMembersOfGroup_Should_ThrowRocketChatGetGroupMembersException_WhenAPIResponseIsUnSuccessful()
throws Exception {
try {
rocketChatService.getStandardMembersOfGroup(GROUP_ID);
fail("Expected exception: RocketChatGetGroupMembersException");
} catch (RocketChatGetGroupMembersException ex) {
- assertTrue("Excepted RocketChatGetGroupMembersException thrown", true);
+ assertTrue(true, "Excepted RocketChatGetGroupMembersException thrown");
}
}
@Test
- public void
- getStandardMembersOfGroup_Should_ReturnListFilteredOfGroupMemberDTO_WhenAPICallIsSuccessful()
- throws Exception {
+ void getStandardMembersOfGroup_Should_ReturnListFilteredOfGroupMemberDTO_WhenAPICallIsSuccessful()
+ throws Exception {
var doc1 = givenSubscription(RC_CREDENTIALS_SYSTEM_A.getRocketChatUserId(), "s");
givenMongoResponseWith(doc1);
@@ -749,40 +744,50 @@ public void removeAllMessages_Should_NotThrowException_WhenRemoveMessagesSucceed
}
/** Method: getUserInfo */
- @Test(expected = InternalServerErrorException.class)
- public void getUserInfo_Should_ThrowInternalServerExceptionException_WhenAPICallFails()
+ @Test
+ void getUserInfo_Should_ThrowInternalServerExceptionException_WhenAPICallFails()
throws RocketChatUserNotInitializedException {
-
- Exception exception =
- new RestClientResponseException(
- MESSAGE, HttpStatus.BAD_REQUEST.value(), ERROR, null, null, null);
-
- when(rcCredentialsHelper.getTechnicalUser()).thenReturn(RC_CREDENTIALS_TECHNICAL_A);
- when(restTemplate.exchange(
- ArgumentMatchers.anyString(),
- any(),
- any(),
- ArgumentMatchers.>any(),
- anyString()))
- .thenThrow(exception);
-
- rocketChatService.getUserInfo(RC_USER_ID);
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ Exception exception =
+ new RestClientResponseException(
+ MESSAGE, HttpStatus.BAD_REQUEST.value(), ERROR, null, null, null);
+
+ when(rcCredentialsHelper.getTechnicalUser()).thenReturn(RC_CREDENTIALS_TECHNICAL_A);
+ when(restTemplate.exchange(
+ ArgumentMatchers.anyString(),
+ any(),
+ any(),
+ ArgumentMatchers.>any(),
+ anyString()))
+ .thenThrow(exception);
+
+ rocketChatService.getUserInfo(RC_USER_ID);
+ });
}
- @Test(expected = InternalServerErrorException.class)
- public void getUserInfo_Should_ThrowInternalServerErrorException_WhenAPICallIsNotSuccessful()
+ @Test
+ void getUserInfo_Should_ThrowInternalServerErrorException_WhenAPICallIsNotSuccessful()
throws RocketChatUserNotInitializedException {
-
- when(rcCredentialsHelper.getTechnicalUser()).thenReturn(RC_CREDENTIALS_TECHNICAL_A);
- when(restTemplate.exchange(
- anyString(), eq(HttpMethod.GET), any(), eq(UserInfoResponseDTO.class), anyString()))
- .thenReturn(new ResponseEntity<>(USER_INFO_RESPONSE_DTO_FAILED, HttpStatus.OK));
-
- rocketChatService.getUserInfo(RC_USER_ID);
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(rcCredentialsHelper.getTechnicalUser()).thenReturn(RC_CREDENTIALS_TECHNICAL_A);
+ when(restTemplate.exchange(
+ anyString(),
+ eq(HttpMethod.GET),
+ any(),
+ eq(UserInfoResponseDTO.class),
+ anyString()))
+ .thenReturn(new ResponseEntity<>(USER_INFO_RESPONSE_DTO_FAILED, HttpStatus.OK));
+
+ rocketChatService.getUserInfo(RC_USER_ID);
+ });
}
@Test
- public void getUserInfo_Should_ReturnUserInfoResponseDTOWithSameUserId_WhenAPICallIsSuccessful()
+ void getUserInfo_Should_ReturnUserInfoResponseDTOWithSameUserId_WhenAPICallIsSuccessful()
throws Exception {
when(rcCredentialsHelper.getTechnicalUser()).thenReturn(RC_CREDENTIALS_TECHNICAL_A);
@@ -800,8 +805,7 @@ public void getUserInfo_Should_ReturnUserInfoResponseDTOWithSameUserId_WhenAPICa
}
@Test
- public void updateUser_Should_performRocketChatUpdate()
- throws RocketChatUserNotInitializedException {
+ void updateUser_Should_performRocketChatUpdate() throws RocketChatUserNotInitializedException {
UserUpdateRequestDTO userUpdateRequestDTO =
new EasyRandom().nextObject(UserUpdateRequestDTO.class);
when(rcCredentialsHelper.getTechnicalUser()).thenReturn(RC_CREDENTIALS_TECHNICAL_A);
@@ -816,34 +820,48 @@ public void updateUser_Should_performRocketChatUpdate()
eq(RC_URL_CHAT_USER_UPDATE), eq(HttpMethod.POST), any(), eq(UserInfoResponseDTO.class));
}
- @Test(expected = InternalServerErrorException.class)
- public void updateUser_Should_throwInternalServerErrorException_When_rocketChatUpdateFails()
+ @Test
+ void updateUser_Should_throwInternalServerErrorException_When_rocketChatUpdateFails()
throws RocketChatUserNotInitializedException {
- UserUpdateRequestDTO userUpdateRequestDTO =
- new EasyRandom().nextObject(UserUpdateRequestDTO.class);
- when(rcCredentialsHelper.getTechnicalUser()).thenReturn(RC_CREDENTIALS_TECHNICAL_A);
- when(restTemplate.exchange(
- eq(RC_URL_CHAT_USER_UPDATE), eq(HttpMethod.POST), any(), eq(UserInfoResponseDTO.class)))
- .thenReturn(new ResponseEntity<>(new UserInfoResponseDTO(), HttpStatus.OK));
-
- this.rocketChatService.updateUser(userUpdateRequestDTO);
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ UserUpdateRequestDTO userUpdateRequestDTO =
+ new EasyRandom().nextObject(UserUpdateRequestDTO.class);
+ when(rcCredentialsHelper.getTechnicalUser()).thenReturn(RC_CREDENTIALS_TECHNICAL_A);
+ when(restTemplate.exchange(
+ eq(RC_URL_CHAT_USER_UPDATE),
+ eq(HttpMethod.POST),
+ any(),
+ eq(UserInfoResponseDTO.class)))
+ .thenReturn(new ResponseEntity<>(new UserInfoResponseDTO(), HttpStatus.OK));
+
+ this.rocketChatService.updateUser(userUpdateRequestDTO);
+ });
}
- @Test(expected = InternalServerErrorException.class)
- public void updateUser_Should_throwInternalServerErrorException_When_rocketChatIsNotReachable()
+ @Test
+ void updateUser_Should_throwInternalServerErrorException_When_rocketChatIsNotReachable()
throws RocketChatUserNotInitializedException {
- UserUpdateRequestDTO userUpdateRequestDTO =
- new EasyRandom().nextObject(UserUpdateRequestDTO.class);
- when(rcCredentialsHelper.getTechnicalUser()).thenReturn(RC_CREDENTIALS_TECHNICAL_A);
- when(restTemplate.exchange(
- eq(RC_URL_CHAT_USER_UPDATE), eq(HttpMethod.POST), any(), eq(UserInfoResponseDTO.class)))
- .thenThrow(mock(RestClientResponseException.class));
-
- this.rocketChatService.updateUser(userUpdateRequestDTO);
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ UserUpdateRequestDTO userUpdateRequestDTO =
+ new EasyRandom().nextObject(UserUpdateRequestDTO.class);
+ when(rcCredentialsHelper.getTechnicalUser()).thenReturn(RC_CREDENTIALS_TECHNICAL_A);
+ when(restTemplate.exchange(
+ eq(RC_URL_CHAT_USER_UPDATE),
+ eq(HttpMethod.POST),
+ any(),
+ eq(UserInfoResponseDTO.class)))
+ .thenThrow(mock(RestClientResponseException.class));
+
+ this.rocketChatService.updateUser(userUpdateRequestDTO);
+ });
}
@Test
- public void deleteUser_Should_performRocketDeleteUser() throws Exception {
+ void deleteUser_Should_performRocketDeleteUser() throws Exception {
when(rcCredentialsHelper.getTechnicalUser()).thenReturn(RC_CREDENTIALS_TECHNICAL_A);
when(restTemplate.exchange(
eq(RC_URL_CHAT_USER_DELETE), eq(HttpMethod.POST), any(), eq(UserInfoResponseDTO.class)))
@@ -857,7 +875,7 @@ public void deleteUser_Should_performRocketDeleteUser() throws Exception {
}
@Test
- public void deleteUser_Should_performRocketDeleteUserOnAlreadyDeletedResponse() throws Exception {
+ void deleteUser_Should_performRocketDeleteUserOnAlreadyDeletedResponse() throws Exception {
when(rcCredentialsHelper.getTechnicalUser()).thenReturn(RC_CREDENTIALS_TECHNICAL_A);
var response =
new UserInfoResponseDTO(
@@ -876,19 +894,26 @@ public void deleteUser_Should_performRocketDeleteUserOnAlreadyDeletedResponse()
eq(RC_URL_CHAT_USER_DELETE), eq(HttpMethod.POST), any(), eq(UserInfoResponseDTO.class));
}
- @Test(expected = RocketChatDeleteUserException.class)
- public void deleteUser_Should_throwRocketChatDeleteUserException_When_responseIsNotSuccess()
+ @Test
+ void deleteUser_Should_throwRocketChatDeleteUserException_When_responseIsNotSuccess()
throws Exception {
- when(rcCredentialsHelper.getTechnicalUser()).thenReturn(RC_CREDENTIALS_TECHNICAL_A);
- when(restTemplate.exchange(
- eq(RC_URL_CHAT_USER_DELETE), eq(HttpMethod.POST), any(), eq(UserInfoResponseDTO.class)))
- .thenReturn(new ResponseEntity<>(new UserInfoResponseDTO(), HttpStatus.OK));
-
- this.rocketChatService.deleteUser("");
+ assertThrows(
+ RocketChatDeleteUserException.class,
+ () -> {
+ when(rcCredentialsHelper.getTechnicalUser()).thenReturn(RC_CREDENTIALS_TECHNICAL_A);
+ when(restTemplate.exchange(
+ eq(RC_URL_CHAT_USER_DELETE),
+ eq(HttpMethod.POST),
+ any(),
+ eq(UserInfoResponseDTO.class)))
+ .thenReturn(new ResponseEntity<>(new UserInfoResponseDTO(), HttpStatus.OK));
+
+ this.rocketChatService.deleteUser("");
+ });
}
@Test
- public void deleteGroupAsTechnicalUser_Should_performRocketDeleteUser() throws Exception {
+ void deleteGroupAsTechnicalUser_Should_performRocketDeleteUser() throws Exception {
when(rcCredentialsHelper.getTechnicalUser()).thenReturn(RC_CREDENTIALS_TECHNICAL_A);
when(restTemplate.postForObject(eq(RC_URL_GROUPS_DELETE), any(), any()))
.thenReturn(new ResponseEntity<>(new GroupDeleteResponseDTO(true), HttpStatus.OK));
@@ -898,17 +923,21 @@ public void deleteGroupAsTechnicalUser_Should_performRocketDeleteUser() throws E
verify(this.restTemplate, times(1)).postForObject(eq(RC_URL_GROUPS_DELETE), any(), any());
}
- @Test(expected = RocketChatDeleteGroupException.class)
- public void
+ @Test
+ void
deleteGroupAsTechnicalUser_Should_throwRocketChatDeleteUserException_When_responseIsNotSuccess()
throws Exception {
- when(rcCredentialsHelper.getTechnicalUser()).thenThrow(new RuntimeException());
+ assertThrows(
+ RocketChatDeleteGroupException.class,
+ () -> {
+ when(rcCredentialsHelper.getTechnicalUser()).thenThrow(new RuntimeException());
- this.rocketChatService.deleteGroupAsTechnicalUser("");
+ this.rocketChatService.deleteGroupAsTechnicalUser("");
+ });
}
@Test
- public void deleteGroupAsSystemUser_Should_performRocketDeleteUser() throws Exception {
+ void deleteGroupAsSystemUser_Should_performRocketDeleteUser() throws Exception {
when(rcCredentialsHelper.getSystemUser()).thenReturn(RC_CREDENTIALS_SYSTEM_A);
when(restTemplate.postForObject(eq(RC_URL_GROUPS_DELETE), any(), any()))
.thenReturn(new ResponseEntity<>(new GroupDeleteResponseDTO(true), HttpStatus.OK));
@@ -918,19 +947,22 @@ public void deleteGroupAsSystemUser_Should_performRocketDeleteUser() throws Exce
verify(this.restTemplate, times(1)).postForObject(eq(RC_URL_GROUPS_DELETE), any(), any());
}
- @Test(expected = InternalServerErrorException.class)
- public void
- deleteGroupAsSystemUser_Should_throwInternalServerErrorException_When_responseIsNotSuccess()
- throws Exception {
- when(rcCredentialsHelper.getSystemUser())
- .thenThrow(new RocketChatUserNotInitializedException(""));
-
- this.rocketChatService.deleteGroupAsSystemUser("");
+ @Test
+ void deleteGroupAsSystemUser_Should_throwInternalServerErrorException_When_responseIsNotSuccess()
+ throws Exception {
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(rcCredentialsHelper.getSystemUser())
+ .thenThrow(new RocketChatUserNotInitializedException(""));
+
+ this.rocketChatService.deleteGroupAsSystemUser("");
+ });
}
@Test
@SuppressWarnings("unchecked")
- public void setRoomReadOnly_Should_performRocketChatSetRoomReadOnly() throws Exception {
+ void setRoomReadOnly_Should_performRocketChatSetRoomReadOnly() throws Exception {
when(rcCredentialsHelper.getSystemUser()).thenReturn(RC_CREDENTIALS_SYSTEM_A);
when(restTemplate.exchange(
eq(RC_URL_GROUPS_SET_READ_ONLY),
@@ -956,7 +988,7 @@ public void setRoomReadOnly_Should_performRocketChatSetRoomReadOnly() throws Exc
}
@Test
- public void setRoomReadOnly_Should_logError_When_responseIsNotSuccess() throws Exception {
+ void setRoomReadOnly_Should_logError_When_responseIsNotSuccess() throws Exception {
when(rcCredentialsHelper.getSystemUser()).thenReturn(RC_CREDENTIALS_SYSTEM_A);
GroupResponseDTO groupResponseDTO = new GroupResponseDTO();
groupResponseDTO.setSuccess(false);
@@ -974,7 +1006,7 @@ public void setRoomReadOnly_Should_logError_When_responseIsNotSuccess() throws E
@Test
@SuppressWarnings("unchecked")
- public void setRoomWriteable_Should_performRocketChatSetRoomReadOnly() throws Exception {
+ void setRoomWriteable_Should_performRocketChatSetRoomReadOnly() throws Exception {
when(rcCredentialsHelper.getSystemUser()).thenReturn(RC_CREDENTIALS_SYSTEM_A);
when(restTemplate.exchange(
eq(RC_URL_GROUPS_SET_READ_ONLY),
@@ -1000,7 +1032,7 @@ public void setRoomWriteable_Should_performRocketChatSetRoomReadOnly() throws Ex
}
@Test
- public void setRoomWriteable_Should_logError_When_responseIsNotSuccess() throws Exception {
+ void setRoomWriteable_Should_logError_When_responseIsNotSuccess() throws Exception {
when(rcCredentialsHelper.getSystemUser()).thenReturn(RC_CREDENTIALS_SYSTEM_A);
GroupResponseDTO groupResponseDTO = new GroupResponseDTO();
groupResponseDTO.setSuccess(false);
@@ -1017,9 +1049,8 @@ public void setRoomWriteable_Should_logError_When_responseIsNotSuccess() throws
}
@Test
- public void
- fetchAllInactivePrivateGroupsSinceGivenDate_ShouldThrowException_WhenRocketChatCallFails()
- throws RocketChatUserNotInitializedException {
+ void fetchAllInactivePrivateGroupsSinceGivenDate_ShouldThrowException_WhenRocketChatCallFails()
+ throws RocketChatUserNotInitializedException {
when(rcCredentialsHelper.getTechnicalUser()).thenReturn(RC_CREDENTIALS_TECHNICAL_A);
HttpServerErrorException httpServerErrorException =
@@ -1036,13 +1067,13 @@ public void setRoomWriteable_Should_logError_When_responseIsNotSuccess() throws
this.rocketChatService.fetchAllInactivePrivateGroupsSinceGivenDate(LocalDateTime.now());
fail("Expected exception: RocketChatGetGroupsListAllException");
} catch (RocketChatGetGroupsListAllException ex) {
- assertTrue("Excepted RocketChatGetGroupsListAllException thrown", true);
+ assertTrue(true, "Excepted RocketChatGetGroupsListAllException thrown");
assertEquals("Could not get all rocket chat groups", ex.getMessage());
}
}
@Test
- public void
+ void
fetchAllInactivePrivateGroupsSinceGivenDate_Should_ThrowException_WhenHttpStatusFromRocketChatCallIsNotOk()
throws RocketChatUserNotInitializedException {
@@ -1060,13 +1091,13 @@ public void setRoomWriteable_Should_logError_When_responseIsNotSuccess() throws
this.rocketChatService.fetchAllInactivePrivateGroupsSinceGivenDate(LocalDateTime.now());
fail("Expected exception: RocketChatGetGroupsListAllException");
} catch (RocketChatGetGroupsListAllException ex) {
- assertTrue("Excepted RocketChatGetGroupsListAllException thrown", true);
+ assertTrue(true, "Excepted RocketChatGetGroupsListAllException thrown");
assertEquals("Could not get all rocket chat groups", ex.getMessage());
}
}
@Test
- public void fetchAllInactivePrivateGroupsSinceGivenDate_Should_ReturnCorrectGroupDtoList()
+ void fetchAllInactivePrivateGroupsSinceGivenDate_Should_ReturnCorrectGroupDtoList()
throws RocketChatUserNotInitializedException, RocketChatGetGroupsListAllException {
when(rcCredentialsHelper.getTechnicalUser()).thenReturn(RC_CREDENTIALS_TECHNICAL_A);
@@ -1087,7 +1118,7 @@ public void fetchAllInactivePrivateGroupsSinceGivenDate_Should_ReturnCorrectGrou
}
@Test
- public void fetchAllInactivePrivateGroupsSinceGivenDate_Should_UseCorrectMongoQuery()
+ void fetchAllInactivePrivateGroupsSinceGivenDate_Should_UseCorrectMongoQuery()
throws RocketChatUserNotInitializedException, RocketChatGetGroupsListAllException {
LocalDateTime dateToCheck = LocalDateTime.of(2021, 1, 1, 0, 0, 0);
@@ -1116,7 +1147,7 @@ public void fetchAllInactivePrivateGroupsSinceGivenDate_Should_UseCorrectMongoQu
}
@Test
- public void
+ void
fetchAllInactivePrivateGroupsSinceGivenDate_Should_CallRocketChatApiMultipleTimes_When_ResultIsPaginated()
throws RocketChatUserNotInitializedException, RocketChatGetGroupsListAllException {
@@ -1146,7 +1177,7 @@ public void fetchAllInactivePrivateGroupsSinceGivenDate_Should_UseCorrectMongoQu
}
@Test
- public void
+ void
fetchAllInactivePrivateGroupsSinceGivenDate_Should_CallRocketChatApiOnlyOnce_When_ResponseContainsTotalOfZeroElements()
throws RocketChatUserNotInitializedException, RocketChatGetGroupsListAllException {
@@ -1178,7 +1209,7 @@ public void fetchAllInactivePrivateGroupsSinceGivenDate_Should_UseCorrectMongoQu
}
@Test
- public void getRocketChatUserIdByUsername_Should_ThrowException_WhenRocketChatCallFails()
+ void getRocketChatUserIdByUsername_Should_ThrowException_WhenRocketChatCallFails()
throws RocketChatUserNotInitializedException {
when(rcCredentialsHelper.getTechnicalUser()).thenReturn(RC_CREDENTIALS_TECHNICAL_A);
@@ -1197,13 +1228,13 @@ public void getRocketChatUserIdByUsername_Should_ThrowException_WhenRocketChatCa
this.rocketChatService.getRocketChatUserIdByUsername(USERNAME);
fail("Expected exception: RocketChatGetUserIdException");
} catch (RocketChatGetUserIdException ex) {
- assertTrue("Excepted RocketChatGetUserIdException thrown", true);
+ assertTrue(true, "Excepted RocketChatGetUserIdException thrown");
assertEquals("Could not get users list from Rocket.Chat", ex.getMessage());
}
}
@Test
- public void getRocketChatUserIdByUsername_Should_ThrowException_WhenFoundNoUserByUsername()
+ void getRocketChatUserIdByUsername_Should_ThrowException_WhenFoundNoUserByUsername()
throws RocketChatUserNotInitializedException {
when(rcCredentialsHelper.getTechnicalUser()).thenReturn(RC_CREDENTIALS_TECHNICAL_A);
@@ -1220,13 +1251,13 @@ public void getRocketChatUserIdByUsername_Should_ThrowException_WhenFoundNoUserB
this.rocketChatService.getRocketChatUserIdByUsername(USERNAME);
fail("Expected exception: RocketChatGetUserIdException");
} catch (RocketChatGetUserIdException ex) {
- assertTrue("Excepted RocketChatGetUserIdException thrown", true);
+ assertTrue(true, "Excepted RocketChatGetUserIdException thrown");
assertEquals("Found 0 users by username", ex.getMessage());
}
}
@Test
- public void getRocketChatUserIdByUsername_Should_ThrowException_WhenFound2UsersByUsername()
+ void getRocketChatUserIdByUsername_Should_ThrowException_WhenFound2UsersByUsername()
throws RocketChatUserNotInitializedException {
when(rcCredentialsHelper.getTechnicalUser()).thenReturn(RC_CREDENTIALS_TECHNICAL_A);
@@ -1243,15 +1274,14 @@ public void getRocketChatUserIdByUsername_Should_ThrowException_WhenFound2UsersB
this.rocketChatService.getRocketChatUserIdByUsername(USERNAME);
fail("Expected exception: RocketChatGetUserIdException");
} catch (RocketChatGetUserIdException ex) {
- assertTrue("Excepted RocketChatGetUserIdException thrown", true);
+ assertTrue(true, "Excepted RocketChatGetUserIdException thrown");
assertEquals("Found 2 users by username", ex.getMessage());
}
}
@Test
- public void
- getRocketChatUserIdByUsername_Should_ThrowException_WhenHttpStatusFromRocketChatCallIsNotOk()
- throws RocketChatUserNotInitializedException {
+ void getRocketChatUserIdByUsername_Should_ThrowException_WhenHttpStatusFromRocketChatCallIsNotOk()
+ throws RocketChatUserNotInitializedException {
when(rcCredentialsHelper.getTechnicalUser()).thenReturn(RC_CREDENTIALS_TECHNICAL_A);
when(restTemplate.exchange(
@@ -1267,13 +1297,13 @@ public void getRocketChatUserIdByUsername_Should_ThrowException_WhenFound2UsersB
this.rocketChatService.getRocketChatUserIdByUsername(USERNAME);
fail("Expected exception: RocketChatGetUserIdException");
} catch (RocketChatGetUserIdException ex) {
- assertTrue("Excepted RocketChatGetUserIdException thrown", true);
+ assertTrue(true, "Excepted RocketChatGetUserIdException thrown");
assertEquals("Could not get users list from Rocket.Chat", ex.getMessage());
}
}
@Test
- public void getRocketChatUserIdByUsername_Should_ReturnRocketChatUserId()
+ void getRocketChatUserIdByUsername_Should_ReturnRocketChatUserId()
throws RocketChatUserNotInitializedException, RocketChatGetUserIdException {
when(rcCredentialsHelper.getTechnicalUser()).thenReturn(RC_CREDENTIALS_TECHNICAL_A);
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/SessionDataServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/service/SessionDataServiceTest.java
index 315765601..d8d8b2ae2 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/SessionDataServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/SessionDataServiceTest.java
@@ -1,6 +1,7 @@
package de.caritas.cob.userservice.api.service;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.SESSION_ID;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -14,13 +15,13 @@
import de.caritas.cob.userservice.api.service.session.SessionService;
import java.util.Optional;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class SessionDataServiceTest {
@InjectMocks private SessionDataService sessionDataService;
@@ -30,12 +31,16 @@ public class SessionDataServiceTest {
private final EasyRandom easyRandom = new EasyRandom();
- @Test(expected = NotFoundException.class)
+ @Test
public void saveSessionDataForSessionId_Should_ThrowNotFoundException_When_SessionNotFound() {
- SessionDataDTO sessionData = easyRandom.nextObject(SessionDataDTO.class);
- when(sessionService.getSession(any())).thenReturn(Optional.empty());
+ assertThrows(
+ NotFoundException.class,
+ () -> {
+ SessionDataDTO sessionData = easyRandom.nextObject(SessionDataDTO.class);
+ when(sessionService.getSession(any())).thenReturn(Optional.empty());
- sessionDataService.saveSessionData(SESSION_ID, sessionData);
+ sessionDataService.saveSessionData(SESSION_ID, sessionData);
+ });
}
@Test
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/UserAgencyServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/service/UserAgencyServiceTest.java
index 2f5a2db22..d398a1591 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/UserAgencyServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/UserAgencyServiceTest.java
@@ -7,10 +7,7 @@
import static org.hamcrest.CoreMatchers.everyItem;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -20,15 +17,15 @@
import de.caritas.cob.userservice.api.model.UserAgency;
import de.caritas.cob.userservice.api.port.out.UserAgencyRepository;
import java.util.List;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.dao.DataAccessException;
-import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
-@RunWith(SpringRunner.class)
+@ExtendWith(SpringExtension.class)
public class UserAgencyServiceTest {
@InjectMocks private UserAgencyService userAgencyService;
@@ -47,7 +44,7 @@ public void saveUserAgency_Should_ThrowInternalServerErrorException_When_Databas
userAgencyService.saveUserAgency(USER_AGENCY);
fail("Expected exception: InternalServerErrorException");
} catch (InternalServerErrorException serviceException) {
- assertTrue("Excepted InternalServerErrorException thrown", true);
+ assertTrue(true, "Excepted InternalServerErrorException thrown");
}
}
@@ -75,7 +72,7 @@ public void getUserAgenciesByUser_Should_ReturnInternalServerErrorException_When
userAgencyService.getUserAgenciesByUser(USER);
fail("Expected exception: InternalServerErrorException");
} catch (InternalServerErrorException serviceEx) {
- assertTrue("Excepted InternalServerErrorException thrown", true);
+ assertTrue(true, "Excepted InternalServerErrorException thrown");
}
}
@@ -102,7 +99,7 @@ public void deleteUserAgency_Should_ThrowInternalServerErrorException_When_Datab
userAgencyService.deleteUserAgency(USER_AGENCY);
fail("Expected exception: InternalServerErrorException");
} catch (InternalServerErrorException serviceEx) {
- assertTrue("Excepted InternalServerErrorException thrown", true);
+ assertTrue(true, "Excepted InternalServerErrorException thrown");
}
}
@@ -116,7 +113,7 @@ public void deleteUserAgency_Should_ThrowIllegalArgumentException_When_UserAgenc
userAgencyService.deleteUserAgency(null);
fail("Expected exception: InternalServerErrorException");
} catch (InternalServerErrorException serviceEx) {
- assertTrue("Excepted InternalServerErrorException thrown", true);
+ assertTrue(true, "Excepted InternalServerErrorException thrown");
}
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/archive/SessionArchiveServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/service/archive/SessionArchiveServiceTest.java
index a3bd88221..e4d39709e 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/archive/SessionArchiveServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/archive/SessionArchiveServiceTest.java
@@ -2,6 +2,7 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.SESSION_ID;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
@@ -25,17 +26,17 @@
import de.caritas.cob.userservice.api.service.statistics.event.StatisticsEvent;
import de.caritas.cob.userservice.statisticsservice.generated.web.model.EventType;
import java.util.Optional;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class SessionArchiveServiceTest {
@InjectMocks SessionArchiveService sessionArchiveService;
@@ -63,44 +64,53 @@ public class SessionArchiveServiceTest {
@Mock private Logger logger;
- @Before
+ @BeforeEach
public void setUp() {
setInternalState(SessionArchiveService.class, "log", logger);
}
- @Test(expected = NotFoundException.class)
+ @Test
public void archiveSession_Should_ThrowNotFoundException_WhenSessionIsNotFound() {
+ assertThrows(
+ NotFoundException.class,
+ () -> {
+ when(sessionRepository.findById(SESSION_ID)).thenReturn(Optional.empty());
- when(sessionRepository.findById(SESSION_ID)).thenReturn(Optional.empty());
-
- sessionArchiveService.archiveSession(SESSION_ID);
+ sessionArchiveService.archiveSession(SESSION_ID);
+ });
}
- @Test(expected = ConflictException.class)
+ @Test
public void
archiveSession_Should_ThrowConflictException_WhenSessionShouldBeArchivedAndIsNotInProgress() {
-
- Session session = Mockito.mock(Session.class);
- when(session.isAdvised(any())).thenReturn(true);
- when(sessionRepository.findById(SESSION_ID)).thenReturn(Optional.of(session));
- doThrow(new ConflictException("Conflict"))
- .when(sessionArchiveValidator)
- .isValidForArchiving(session);
-
- sessionArchiveService.archiveSession(SESSION_ID);
- verify(session, times(0)).setStatus(SessionStatus.IN_ARCHIVE);
+ assertThrows(
+ ConflictException.class,
+ () -> {
+ Session session = Mockito.mock(Session.class);
+ when(session.isAdvised(any())).thenReturn(true);
+ when(sessionRepository.findById(SESSION_ID)).thenReturn(Optional.of(session));
+ doThrow(new ConflictException("Conflict"))
+ .when(sessionArchiveValidator)
+ .isValidForArchiving(session);
+
+ sessionArchiveService.archiveSession(SESSION_ID);
+ verify(session, times(0)).setStatus(SessionStatus.IN_ARCHIVE);
+ });
}
- @Test(expected = ForbiddenException.class)
+ @Test
public void
archiveSession_Should_ThrowForbiddenException_WhenConsultantHasaNoAuthorizationForTheSession() {
+ assertThrows(
+ ForbiddenException.class,
+ () -> {
+ Session session = Mockito.mock(Session.class);
+ when(sessionRepository.findById(SESSION_ID)).thenReturn(Optional.of(session));
- Session session = Mockito.mock(Session.class);
- when(sessionRepository.findById(SESSION_ID)).thenReturn(Optional.of(session));
-
- sessionArchiveService.archiveSession(SESSION_ID);
+ sessionArchiveService.archiveSession(SESSION_ID);
- verify(session, times(0)).setStatus(SessionStatus.IN_ARCHIVE);
+ verify(session, times(0)).setStatus(SessionStatus.IN_ARCHIVE);
+ });
}
@Test
@@ -115,16 +125,19 @@ public void archiveSession_Should_ChangeStatusOfSession_WhenConsultantHasPermiss
verify(session, times(1)).setStatus(SessionStatus.IN_ARCHIVE);
}
- @Test(expected = ForbiddenException.class)
+ @Test
public void
archiveSession_Should_ThrowForbiddenException_WhenUserHasNoAuthorizationForTheSession() {
+ assertThrows(
+ ForbiddenException.class,
+ () -> {
+ Session session = Mockito.mock(Session.class);
+ when(sessionRepository.findById(SESSION_ID)).thenReturn(Optional.of(session));
- Session session = Mockito.mock(Session.class);
- when(sessionRepository.findById(SESSION_ID)).thenReturn(Optional.of(session));
-
- sessionArchiveService.archiveSession(SESSION_ID);
+ sessionArchiveService.archiveSession(SESSION_ID);
- verify(session, times(0)).setStatus(SessionStatus.IN_ARCHIVE);
+ verify(session, times(0)).setStatus(SessionStatus.IN_ARCHIVE);
+ });
}
@Test
@@ -171,61 +184,77 @@ public void archiveSession_Should_LogButNotFail_WhenErrorDuringStatisticsArchive
.error("Could not create session archive statistics event", illegalStateException);
}
- @Test(expected = NotFoundException.class)
+ @Test
public void dearchiveSession_Should_ThrowNotFoundException_WhenSessionIsNotFound() {
- when(sessionRepository.findById(SESSION_ID)).thenReturn(Optional.empty());
- sessionArchiveService.dearchiveSession(SESSION_ID);
+ assertThrows(
+ NotFoundException.class,
+ () -> {
+ when(sessionRepository.findById(SESSION_ID)).thenReturn(Optional.empty());
+ sessionArchiveService.dearchiveSession(SESSION_ID);
+ });
}
- @Test(expected = ConflictException.class)
+ @Test
public void
dearchiveSession_Should_ThrowConflictException_WhenSessionShouldBeReactivatedAndIsAlreadyInProgress() {
-
- Session session = Mockito.mock(Session.class);
- when(session.isAdvised(any())).thenReturn(true);
- when(sessionRepository.findById(SESSION_ID)).thenReturn(Optional.of(session));
- doThrow(new ConflictException("Conflict"))
- .when(sessionArchiveValidator)
- .isValidForDearchiving(session);
-
- sessionArchiveService.dearchiveSession(SESSION_ID);
-
- verify(session, times(0)).setStatus(SessionStatus.IN_PROGRESS);
+ assertThrows(
+ ConflictException.class,
+ () -> {
+ Session session = Mockito.mock(Session.class);
+ when(session.isAdvised(any())).thenReturn(true);
+ when(sessionRepository.findById(SESSION_ID)).thenReturn(Optional.of(session));
+ doThrow(new ConflictException("Conflict"))
+ .when(sessionArchiveValidator)
+ .isValidForDearchiving(session);
+
+ sessionArchiveService.dearchiveSession(SESSION_ID);
+
+ verify(session, times(0)).setStatus(SessionStatus.IN_PROGRESS);
+ });
}
- @Test(expected = ForbiddenException.class)
+ @Test
public void
dearchiveSession_Should_ThrowForbiddenException_WhenConsultantHasNoAuthorizationForTheSession() {
+ assertThrows(
+ ForbiddenException.class,
+ () -> {
+ Session session = Mockito.mock(Session.class);
+ when(sessionRepository.findById(SESSION_ID)).thenReturn(Optional.of(session));
- Session session = Mockito.mock(Session.class);
- when(sessionRepository.findById(SESSION_ID)).thenReturn(Optional.of(session));
+ sessionArchiveService.dearchiveSession(SESSION_ID);
- sessionArchiveService.dearchiveSession(SESSION_ID);
-
- verify(session, times(0)).setStatus(SessionStatus.IN_PROGRESS);
+ verify(session, times(0)).setStatus(SessionStatus.IN_PROGRESS);
+ });
}
- @Test(expected = ForbiddenException.class)
+ @Test
public void
dearchiveSession_Should_ThrowForbiddenException_WhenSessionIsNotTeamSessionAndConsultantNotAssigned() {
+ assertThrows(
+ ForbiddenException.class,
+ () -> {
+ Session session = Mockito.mock(Session.class);
+ when(sessionRepository.findById(SESSION_ID)).thenReturn(Optional.of(session));
- Session session = Mockito.mock(Session.class);
- when(sessionRepository.findById(SESSION_ID)).thenReturn(Optional.of(session));
-
- sessionArchiveService.dearchiveSession(SESSION_ID);
+ sessionArchiveService.dearchiveSession(SESSION_ID);
- verify(session, times(1)).setStatus(SessionStatus.IN_ARCHIVE);
+ verify(session, times(1)).setStatus(SessionStatus.IN_ARCHIVE);
+ });
}
- @Test(expected = ForbiddenException.class)
+ @Test
public void dearchiveSession_Should_ThrowForbiddenException_WhenNoConsultantOrUserRole() {
+ assertThrows(
+ ForbiddenException.class,
+ () -> {
+ Session session = Mockito.mock(Session.class);
+ when(sessionRepository.findById(SESSION_ID)).thenReturn(Optional.of(session));
- Session session = Mockito.mock(Session.class);
- when(sessionRepository.findById(SESSION_ID)).thenReturn(Optional.of(session));
-
- sessionArchiveService.dearchiveSession(SESSION_ID);
+ sessionArchiveService.dearchiveSession(SESSION_ID);
- verify(session, times(0)).setStatus(SessionStatus.IN_PROGRESS);
+ verify(session, times(0)).setStatus(SessionStatus.IN_PROGRESS);
+ });
}
@Test
@@ -239,16 +268,19 @@ public void dearchiveSession_Should_ChangeStatusOfSession_WhenConsultantHasPermi
verify(session, times(1)).setStatus(SessionStatus.IN_PROGRESS);
}
- @Test(expected = ForbiddenException.class)
+ @Test
public void
dearchiveSession_Should_ThrowForbiddenException_WhenUserHasNoAuthorizationForTheSession() {
+ assertThrows(
+ ForbiddenException.class,
+ () -> {
+ Session session = Mockito.mock(Session.class);
+ when(sessionRepository.findById(SESSION_ID)).thenReturn(Optional.of(session));
- Session session = Mockito.mock(Session.class);
- when(sessionRepository.findById(SESSION_ID)).thenReturn(Optional.of(session));
-
- sessionArchiveService.dearchiveSession(SESSION_ID);
+ sessionArchiveService.dearchiveSession(SESSION_ID);
- verify(session, times(1)).setStatus(SessionStatus.IN_ARCHIVE);
+ verify(session, times(1)).setStatus(SessionStatus.IN_ARCHIVE);
+ });
}
@Test
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/conversation/anonymous/AnonymousConversationCreatorServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/service/conversation/anonymous/AnonymousConversationCreatorServiceTest.java
index 41978291b..da37ee373 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/conversation/anonymous/AnonymousConversationCreatorServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/conversation/anonymous/AnonymousConversationCreatorServiceTest.java
@@ -6,6 +6,7 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USER_DTO_SUCHT;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
@@ -32,14 +33,14 @@
import de.caritas.cob.userservice.api.service.user.UserService;
import java.util.Optional;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
-@RunWith(SpringRunner.class)
-public class AnonymousConversationCreatorServiceTest {
+@ExtendWith(SpringExtension.class)
+class AnonymousConversationCreatorServiceTest {
@InjectMocks private AnonymousConversationCreatorService anonymousConversationCreatorService;
@Mock private UserService userService;
@@ -52,70 +53,88 @@ public class AnonymousConversationCreatorServiceTest {
EasyRandom easyRandom = new EasyRandom();
- @Test(expected = InternalServerErrorException.class)
- public void
+ @Test
+ void
createAnonymousConversation_Should_ThrowInternalServerErrorException_When_ProvidedUserDoesNotExist() {
- when(userService.getUser(anyString())).thenReturn(Optional.empty());
- AnonymousUserCredentials credentials = easyRandom.nextObject(AnonymousUserCredentials.class);
-
- anonymousConversationCreatorService.createAnonymousConversation(USER_DTO_SUCHT, credentials);
-
- verifyNoInteractions(sessionService);
- verifyNoInteractions(rollbackFacade);
- verifyNoInteractions(createEnquiryMessageFacade);
- verifyNoInteractions(agencyService);
- verifyNoInteractions(consultantAgencyService);
- verifyNoInteractions(liveEventNotificationService);
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(userService.getUser(anyString())).thenReturn(Optional.empty());
+ AnonymousUserCredentials credentials =
+ easyRandom.nextObject(AnonymousUserCredentials.class);
+
+ anonymousConversationCreatorService.createAnonymousConversation(
+ USER_DTO_SUCHT, credentials);
+
+ verifyNoInteractions(sessionService);
+ verifyNoInteractions(rollbackFacade);
+ verifyNoInteractions(createEnquiryMessageFacade);
+ verifyNoInteractions(agencyService);
+ verifyNoInteractions(consultantAgencyService);
+ verifyNoInteractions(liveEventNotificationService);
+ });
}
- @Test(expected = InternalServerErrorException.class)
- public void
+ @Test
+ void
createAnonymousConversation_Should_ThrowInternalServerErrorExceptionAndPerformRollback_When_InitializingSessionFails() {
- when(userService.getUser(anyString())).thenReturn(Optional.of(USER));
- when(sessionService.initializeSession(
- any(User.class),
- any(UserDTO.class),
- anyBoolean(),
- any(RegistrationType.class),
- any(SessionStatus.class)))
- .thenThrow(new IllegalArgumentException());
- AnonymousUserCredentials credentials = easyRandom.nextObject(AnonymousUserCredentials.class);
-
- anonymousConversationCreatorService.createAnonymousConversation(USER_DTO_SUCHT, credentials);
-
- verifyNoInteractions(rollbackFacade);
- verifyNoInteractions(createEnquiryMessageFacade);
- verifyNoInteractions(agencyService);
- verifyNoInteractions(consultantAgencyService);
- verifyNoInteractions(liveEventNotificationService);
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(userService.getUser(anyString())).thenReturn(Optional.of(USER));
+ when(sessionService.initializeSession(
+ any(User.class),
+ any(UserDTO.class),
+ anyBoolean(),
+ any(RegistrationType.class),
+ any(SessionStatus.class)))
+ .thenThrow(new IllegalArgumentException());
+ AnonymousUserCredentials credentials =
+ easyRandom.nextObject(AnonymousUserCredentials.class);
+
+ anonymousConversationCreatorService.createAnonymousConversation(
+ USER_DTO_SUCHT, credentials);
+
+ verifyNoInteractions(rollbackFacade);
+ verifyNoInteractions(createEnquiryMessageFacade);
+ verifyNoInteractions(agencyService);
+ verifyNoInteractions(consultantAgencyService);
+ verifyNoInteractions(liveEventNotificationService);
+ });
}
- @Test(expected = InternalServerErrorException.class)
- public void
+ @Test
+ void
createAnonymousConversation_Should_ThrowInternalServerErrorExceptionAndPerformRollback_When_CreateRcRoomFails()
throws CreateEnquiryException {
- when(userService.getUser(anyString())).thenReturn(Optional.of(USER));
- when(sessionService.initializeSession(
- any(User.class),
- any(UserDTO.class),
- anyBoolean(),
- any(RegistrationType.class),
- any(SessionStatus.class)))
- .thenReturn(SESSION);
- CreateEnquiryException exception = easyRandom.nextObject(CreateEnquiryException.class);
- when(createEnquiryMessageFacade.createRocketChatRoomAndAddUsers(any(), any(), any()))
- .thenThrow(exception);
- AnonymousUserCredentials credentials = easyRandom.nextObject(AnonymousUserCredentials.class);
-
- anonymousConversationCreatorService.createAnonymousConversation(USER_DTO_SUCHT, credentials);
-
- verifyNoInteractions(agencyService);
- verifyNoInteractions(consultantAgencyService);
- verifyNoInteractions(liveEventNotificationService);
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(userService.getUser(anyString())).thenReturn(Optional.of(USER));
+ when(sessionService.initializeSession(
+ any(User.class),
+ any(UserDTO.class),
+ anyBoolean(),
+ any(RegistrationType.class),
+ any(SessionStatus.class)))
+ .thenReturn(SESSION);
+ CreateEnquiryException exception = easyRandom.nextObject(CreateEnquiryException.class);
+ when(createEnquiryMessageFacade.createRocketChatRoomAndAddUsers(any(), any(), any()))
+ .thenThrow(exception);
+ AnonymousUserCredentials credentials =
+ easyRandom.nextObject(AnonymousUserCredentials.class);
+
+ anonymousConversationCreatorService.createAnonymousConversation(
+ USER_DTO_SUCHT, credentials);
+
+ verifyNoInteractions(agencyService);
+ verifyNoInteractions(consultantAgencyService);
+ verifyNoInteractions(liveEventNotificationService);
+ });
}
@Test
- public void createAnonymousConversation_Should_ReturnSessionAndTriggerLiveEvent()
+ void createAnonymousConversation_Should_ReturnSessionAndTriggerLiveEvent()
throws CreateEnquiryException {
when(userService.getUser(anyString())).thenReturn(Optional.of(USER));
when(sessionService.initializeSession(
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/emailsupplier/AssignEnquiryEmailSupplierTest.java b/src/test/java/de/caritas/cob/userservice/api/service/emailsupplier/AssignEnquiryEmailSupplierTest.java
index 4e59ccbc0..230ca8b56 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/emailsupplier/AssignEnquiryEmailSupplierTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/emailsupplier/AssignEnquiryEmailSupplierTest.java
@@ -18,14 +18,14 @@
import de.caritas.cob.userservice.mailservice.generated.web.model.TemplateDataDTO;
import java.util.List;
import java.util.Optional;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class AssignEnquiryEmailSupplierTest {
private AssignEnquiryEmailSupplier assignEnquiryEmailSupplier;
@@ -36,7 +36,7 @@ public class AssignEnquiryEmailSupplierTest {
@Mock private Logger logger;
- @Before
+ @BeforeEach
public void setup() {
String applicationBaseUrl = "application base url";
String askerUserName = "asker user name";
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/emailsupplier/NewDirectEnquiryEmailSupplierTest.java b/src/test/java/de/caritas/cob/userservice/api/service/emailsupplier/NewDirectEnquiryEmailSupplierTest.java
index 4ea28d9ba..c456023a4 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/emailsupplier/NewDirectEnquiryEmailSupplierTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/emailsupplier/NewDirectEnquiryEmailSupplierTest.java
@@ -24,13 +24,13 @@
import de.caritas.cob.userservice.mailservice.generated.web.model.MailDTO;
import java.util.List;
import org.assertj.core.api.Assertions;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class NewDirectEnquiryEmailSupplierTest {
private NewDirectEnquiryEmailSupplier newDirectEnquiryEmailSupplier;
@@ -38,7 +38,7 @@ public class NewDirectEnquiryEmailSupplierTest {
@Mock private ConsultantAgencyRepository consultantAgencyRepository;
@Mock private ReleaseToggleService releaseToggleService;
- @Before
+ @BeforeEach
public void setup() {
newDirectEnquiryEmailSupplier =
new NewDirectEnquiryEmailSupplier(consultantAgencyRepository, null, releaseToggleService);
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/emailsupplier/NewEnquiryEmailSupplierTest.java b/src/test/java/de/caritas/cob/userservice/api/service/emailsupplier/NewEnquiryEmailSupplierTest.java
index ca21f4692..408978d55 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/emailsupplier/NewEnquiryEmailSupplierTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/emailsupplier/NewEnquiryEmailSupplierTest.java
@@ -22,13 +22,13 @@
import de.caritas.cob.userservice.mailservice.generated.web.model.MailDTO;
import de.caritas.cob.userservice.mailservice.generated.web.model.TemplateDataDTO;
import java.util.List;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class NewEnquiryEmailSupplierTest {
private NewEnquiryEmailSupplier newEnquiryEmailSupplier;
@@ -41,7 +41,7 @@ public class NewEnquiryEmailSupplierTest {
@Mock private ReleaseToggleService releaseToggleService;
- @Before
+ @BeforeEach
public void setup() {
this.newEnquiryEmailSupplier =
new NewEnquiryEmailSupplier(
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/emailsupplier/NewFeedbackEmailSupplierTest.java b/src/test/java/de/caritas/cob/userservice/api/service/emailsupplier/NewFeedbackEmailSupplierTest.java
index f2f67703e..08b6c25b4 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/emailsupplier/NewFeedbackEmailSupplierTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/emailsupplier/NewFeedbackEmailSupplierTest.java
@@ -31,14 +31,14 @@
import java.util.Optional;
import java.util.UUID;
import org.apache.commons.lang3.RandomStringUtils;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class NewFeedbackEmailSupplierTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
@@ -55,7 +55,7 @@ public class NewFeedbackEmailSupplierTest {
@Mock private Logger logger;
- @Before
+ @BeforeEach
public void setup() {
this.newFeedbackEmailSupplier =
new NewFeedbackEmailSupplier(
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/emailsupplier/NewMessageEmailSupplierTest.java b/src/test/java/de/caritas/cob/userservice/api/service/emailsupplier/NewMessageEmailSupplierTest.java
index 23db51ef4..fe4ee49bd 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/emailsupplier/NewMessageEmailSupplierTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/emailsupplier/NewMessageEmailSupplierTest.java
@@ -12,6 +12,7 @@
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
@@ -45,16 +46,19 @@
import java.util.Optional;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
import org.slf4j.Logger;
import org.springframework.test.util.ReflectionTestUtils;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
public class NewMessageEmailSupplierTest {
private NewMessageEmailSupplier newMessageEmailSupplier;
@@ -77,7 +81,7 @@ public class NewMessageEmailSupplierTest {
@Mock private ReleaseToggleService releaseToggleService;
- @Before
+ @BeforeEach
public void setup() {
this.newMessageEmailSupplier =
NewMessageEmailSupplier.builder()
@@ -367,16 +371,20 @@ public void generateEmails_Should_ReturnExpectedEmailToAdviceSeeker_When_AdviceS
TenantContext.clear();
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void generateEmails_Should_ThrowInternalServerException_When_ConsultantIsNotFound() {
- when(roles.contains(UserRole.CONSULTANT.getValue())).thenReturn(true);
- Consultant consultant = mock(Consultant.class);
- when(session.getConsultant()).thenReturn(consultant);
- when(consultant.getId()).thenReturn(CONSULTANT_ID);
- when(session.getUser()).thenReturn(USER);
- when(consultantService.getConsultant(USER.getUserId())).thenReturn(Optional.empty());
-
- this.newMessageEmailSupplier.generateEmails();
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(roles.contains(UserRole.CONSULTANT.getValue())).thenReturn(true);
+ Consultant consultant = mock(Consultant.class);
+ when(session.getConsultant()).thenReturn(consultant);
+ when(consultant.getId()).thenReturn(CONSULTANT_ID);
+ when(session.getUser()).thenReturn(USER);
+ when(consultantService.getConsultant(USER.getUserId())).thenReturn(Optional.empty());
+
+ this.newMessageEmailSupplier.generateEmails();
+ });
}
private void givenCurrentTenantDataIsSet() {
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/helper/AgencySecurityHeaderSupplierTest.java b/src/test/java/de/caritas/cob/userservice/api/service/helper/AgencySecurityHeaderSupplierTest.java
index 9f1c97e7b..14e63504b 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/helper/AgencySecurityHeaderSupplierTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/helper/AgencySecurityHeaderSupplierTest.java
@@ -5,7 +5,7 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.AGENCY_ID_LIST;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -21,19 +21,22 @@
import java.util.List;
import java.util.stream.Collectors;
import lombok.SneakyThrows;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentMatchers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
-@RunWith(MockitoJUnitRunner.class)
-public class AgencySecurityHeaderSupplierTest {
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
+class AgencySecurityHeaderSupplierTest {
private final String GET_AGENCY_METHOD_NAME = "getAgency";
private final String GET_AGENCIES_METHOD_NAME = "getAgencies";
@@ -52,8 +55,8 @@ public class AgencySecurityHeaderSupplierTest {
@Mock private AgencyServiceApiControllerFactory agencyServiceApiControllerFactory;
- @Before
- public void setup() throws NoSuchFieldException, SecurityException {
+ @BeforeEach
+ void setup() throws NoSuchFieldException, SecurityException {
when(agencyServiceApiControllerFactory.createControllerApi()).thenReturn(agencyControllerApi);
this.agencyResponseDTOS =
AGENCY_DTO_LIST.stream().map(this::toAgencyResponseDTO).collect(Collectors.toList());
@@ -72,7 +75,7 @@ private AgencyResponseDTO toAgencyResponseDTO(AgencyDTO agencyDTO) {
}
@Test
- public void getAgencies_Should_ReturnAgencyDTOList_When_ProvidedWithValidAgencyIds() {
+ void getAgencies_Should_ReturnAgencyDTOList_When_ProvidedWithValidAgencyIds() {
when(agencyControllerApi.getAgenciesByIds(ArgumentMatchers.any()))
.thenReturn(this.agencyResponseDTOS);
@@ -82,9 +85,8 @@ public void getAgencies_Should_ReturnAgencyDTOList_When_ProvidedWithValidAgencyI
@SuppressWarnings({"unchecked", "rawtypes"})
@Test
- public void
- test_Should_Fail_When_MethodgetAgenciesFromAgencyServiceDoesNotHaveCacheableAnnotation()
- throws NoSuchMethodException, SecurityException {
+ void test_Should_Fail_When_MethodgetAgenciesFromAgencyServiceDoesNotHaveCacheableAnnotation()
+ throws NoSuchMethodException, SecurityException {
AgencyService agencyService =
new AgencyService(
@@ -100,7 +102,7 @@ public void getAgencies_Should_ReturnAgencyDTOList_When_ProvidedWithValidAgencyI
}
@Test
- public void getAgency_Should_ReturnAgencyDTO_When_ProvidedWithValidAgencyId() {
+ void getAgency_Should_ReturnAgencyDTO_When_ProvidedWithValidAgencyId() {
when(agencyControllerApi.getAgenciesByIds(ArgumentMatchers.any()))
.thenReturn(this.agencyResponseDTOS);
@@ -111,7 +113,7 @@ public void getAgency_Should_ReturnAgencyDTO_When_ProvidedWithValidAgencyId() {
@SuppressWarnings({"unchecked", "rawtypes"})
@Test
- public void test_Should_Fail_When_MethodgetAgencyFromAgencyServiceDoesNotHaveCacheableAnnotation()
+ void test_Should_Fail_When_MethodgetAgencyFromAgencyServiceDoesNotHaveCacheableAnnotation()
throws NoSuchMethodException, SecurityException {
AgencyService agencyService =
@@ -128,7 +130,7 @@ public void test_Should_Fail_When_MethodgetAgencyFromAgencyServiceDoesNotHaveCac
}
@Test
- public void getAgencyWithoutCaching_Should_ReturnAgencyDTO_WhenProvidedWithValidAgencyId() {
+ void getAgencyWithoutCaching_Should_ReturnAgencyDTO_WhenProvidedWithValidAgencyId() {
when(agencyControllerApi.getAgenciesByIds(ArgumentMatchers.any()))
.thenReturn(this.agencyResponseDTOS);
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/helper/MailServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/service/helper/MailServiceTest.java
index ad1d250dd..efa0888b3 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/helper/MailServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/helper/MailServiceTest.java
@@ -16,17 +16,17 @@
import de.caritas.cob.userservice.mailservice.generated.web.model.ErrorMailDTO;
import de.caritas.cob.userservice.mailservice.generated.web.model.MailsDTO;
import java.util.UUID;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class MailServiceTest {
@Mock private Logger logger;
@@ -41,7 +41,7 @@ public class MailServiceTest {
@InjectMocks private MailService mailService;
- @Before
+ @BeforeEach
public void setup() throws NoSuchFieldException, SecurityException {
setInternalState(MailService.class, "log", logger);
when(mailServiceApiControllerFactory.createControllerApi()).thenReturn(mailsControllerApi);
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/helper/RocketChatCredentialsProviderTest.java b/src/test/java/de/caritas/cob/userservice/api/service/helper/RocketChatCredentialsProviderTest.java
index d44673e7d..8eedaca25 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/helper/RocketChatCredentialsProviderTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/helper/RocketChatCredentialsProviderTest.java
@@ -18,11 +18,7 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.TECHNICAL_USER_B_ID;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.TECHNICAL_USER_B_TOKEN;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.TECHNICAL_USER_B_USERNAME;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -36,13 +32,13 @@
import de.caritas.cob.userservice.api.adapters.rocketchat.dto.logout.LogoutResponseDTO;
import de.caritas.cob.userservice.api.exception.rocketchat.RocketChatUserNotInitializedException;
import java.util.concurrent.atomic.AtomicReference;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentMatchers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
@@ -53,7 +49,7 @@
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class RocketChatCredentialsProviderTest {
/** FIELD Names */
@@ -134,7 +130,7 @@ public class RocketChatCredentialsProviderTest {
@Mock private RestTemplate restTemplate;
- @Before
+ @BeforeEach
public void setup() throws NoSuchFieldException {
setField(rcCredentialHelper, FIELD_NAME_TECHNICAL_USERNAME, TECHNICAL_USER_USERNAME);
setField(rcCredentialHelper, FIELD_NAME_TECHNICAL_PASSWORD, TECHNICAL_USER_PW);
@@ -383,7 +379,7 @@ public void updateCredentials_Should_LogoutAndReLoginBUsers_WhenAllUsersArePrese
rcCredentialHelper.getTechnicalUser();
fail("Expected exception: RocketChatUserNotInitializedException");
} catch (RocketChatUserNotInitializedException ex) {
- assertTrue("Excepted RocketChatUserNotInitializedException thrown", true);
+ assertTrue(true, "Excepted RocketChatUserNotInitializedException thrown");
}
}
@@ -455,7 +451,7 @@ public void getTechnicalUser_Should_ReturnUserB_WhenUserBIsNewer() throws Except
rcCredentialHelper.getSystemUser();
fail("Expected exception: RocketChatUserNotInitializedException");
} catch (RocketChatUserNotInitializedException ex) {
- assertTrue("Excepted RocketChatUserNotInitializedException thrown", true);
+ assertTrue(true, "Excepted RocketChatUserNotInitializedException thrown");
}
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/helper/RocketChatRollbackServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/service/helper/RocketChatRollbackServiceTest.java
index f4f43ddde..a0965f082 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/helper/RocketChatRollbackServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/helper/RocketChatRollbackServiceTest.java
@@ -17,16 +17,16 @@
import de.caritas.cob.userservice.api.exception.rocketchat.RocketChatLeaveFromGroupException;
import java.util.Arrays;
import java.util.List;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class RocketChatRollbackServiceTest {
private final String MEMBER_ID = "asdkds9";
@@ -51,7 +51,7 @@ public class RocketChatRollbackServiceTest {
@Mock Logger logger;
@Mock private RocketChatCredentialsProvider rcCredentialHelper;
- @Before
+ @BeforeEach
public void setup() {
setInternalState(RocketChatRollbackService.class, "log", logger);
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/httpheader/SecurityHeaderSupplierTest.java b/src/test/java/de/caritas/cob/userservice/api/service/httpheader/SecurityHeaderSupplierTest.java
index 144de3b3e..4ad8776c3 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/httpheader/SecurityHeaderSupplierTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/httpheader/SecurityHeaderSupplierTest.java
@@ -3,22 +3,22 @@
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.startsWith;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.when;
import static org.springframework.test.util.ReflectionTestUtils.setField;
import de.caritas.cob.userservice.api.helper.AuthenticatedUser;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class SecurityHeaderSupplierTest {
private final String CSRF_TOKEN_HEADER_VALUE = "X-CSRF-TOKEN";
@@ -28,7 +28,7 @@ public class SecurityHeaderSupplierTest {
@InjectMocks private SecurityHeaderSupplier securityHeaderSupplier;
@Mock private AuthenticatedUser authenticatedUser;
- @Before
+ @BeforeEach
public void setup() throws NoSuchFieldException, SecurityException {
setField(securityHeaderSupplier, "csrfHeaderProperty", CSRF_TOKEN_HEADER_VALUE);
setField(securityHeaderSupplier, "csrfCookieProperty", CSRF_TOKEN_COOKIE_VALUE);
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/liveevents/LiveEventNotificationServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/service/liveevents/LiveEventNotificationServiceTest.java
index 881b4d64a..2fde9b046 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/liveevents/LiveEventNotificationServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/liveevents/LiveEventNotificationServiceTest.java
@@ -6,7 +6,7 @@
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
@@ -26,16 +26,19 @@
import de.caritas.cob.userservice.liveservice.generated.web.model.StatusSource;
import de.caritas.cob.userservice.liveservice.generated.web.model.StatusSource.FinishConversationPhaseEnum;
import java.util.List;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
import org.slf4j.Logger;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
public class LiveEventNotificationServiceTest {
private static final LiveEventMessage MESSAGE = new LiveEventMessage().eventType(DIRECTMESSAGE);
@@ -58,7 +61,7 @@ public class LiveEventNotificationServiceTest {
@Mock private LiveServiceApiControllerFactory liveServiceApiControllerFactory;
- @Before
+ @BeforeEach
public void setup() {
setInternalState(LiveEventNotificationService.class, "log", logger);
when(liveServiceApiControllerFactory.createControllerApi()).thenReturn(liveControllerApi);
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/liveevents/RelevantUserAccountIdsByChatProviderTest.java b/src/test/java/de/caritas/cob/userservice/api/service/liveevents/RelevantUserAccountIdsByChatProviderTest.java
index 9b44f7046..daadae433 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/liveevents/RelevantUserAccountIdsByChatProviderTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/liveevents/RelevantUserAccountIdsByChatProviderTest.java
@@ -18,14 +18,17 @@
import java.util.Optional;
import org.apache.commons.lang3.RandomStringUtils;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
-@RunWith(MockitoJUnitRunner.class)
-public class RelevantUserAccountIdsByChatProviderTest {
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
+class RelevantUserAccountIdsByChatProviderTest {
private static final EasyRandom easyRandom = new EasyRandom();
@@ -38,7 +41,7 @@ public class RelevantUserAccountIdsByChatProviderTest {
@Mock private ConsultantService consultantService;
@Test
- public void collectUserIds_Should_returnAllMergedDependingIds_When_rcGroupHasMembers() {
+ void collectUserIds_Should_returnAllMergedDependingIds_When_rcGroupHasMembers() {
List groupMembers =
asList(memberDTOWithRcId("rc1"), memberDTOWithRcId("rc2"), memberDTOWithRcId("rc3"));
when(this.rocketChatService.getChatUsers(any())).thenReturn(groupMembers);
@@ -81,7 +84,7 @@ private User userWithId(String userId) {
}
@Test
- public void
+ void
collectUserIds_Should_returnAllMergedDependingIdsInsteadOfNotAvailableUser_When_rcGroupHasMembers() {
List groupMembers =
asList(memberDTOWithRcId("rc1"), memberDTOWithRcId("rc2"), memberDTOWithRcId("rc3"));
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/liveevents/RelevantUserAccountIdsBySessionProviderTest.java b/src/test/java/de/caritas/cob/userservice/api/service/liveevents/RelevantUserAccountIdsBySessionProviderTest.java
index b5d2664a4..fb518fbfe 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/liveevents/RelevantUserAccountIdsBySessionProviderTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/liveevents/RelevantUserAccountIdsBySessionProviderTest.java
@@ -13,13 +13,13 @@
import java.util.List;
import java.util.Optional;
import org.apache.commons.lang3.RandomStringUtils;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class RelevantUserAccountIdsBySessionProviderTest {
@InjectMocks private RelevantUserAccountIdsBySessionProvider bySessionProvider;
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/liveevents/UserIdsProviderFactoryTest.java b/src/test/java/de/caritas/cob/userservice/api/service/liveevents/UserIdsProviderFactoryTest.java
index e81a4b662..991884656 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/liveevents/UserIdsProviderFactoryTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/liveevents/UserIdsProviderFactoryTest.java
@@ -8,13 +8,13 @@
import de.caritas.cob.userservice.api.port.out.ChatRepository;
import java.util.Optional;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class UserIdsProviderFactoryTest {
@InjectMocks private UserIdsProviderFactory userIdsProviderFactory;
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/message/MessageServiceProviderTest.java b/src/test/java/de/caritas/cob/userservice/api/service/message/MessageServiceProviderTest.java
index 9132623ac..bf801e395 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/message/MessageServiceProviderTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/message/MessageServiceProviderTest.java
@@ -11,10 +11,7 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USER;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
@@ -43,19 +40,22 @@
import de.caritas.cob.userservice.messageservice.generated.web.model.MessageDTO;
import de.caritas.cob.userservice.messageservice.generated.web.model.MessageType;
import org.jeasy.random.EasyRandom;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
import org.springframework.http.HttpHeaders;
-import org.springframework.util.StringUtils;
+import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestClientException;
-@RunWith(MockitoJUnitRunner.class)
-public class MessageServiceProviderTest {
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
+class MessageServiceProviderTest {
@InjectMocks private MessageServiceProvider messageServiceProvider;
@@ -75,13 +75,13 @@ public class MessageServiceProviderTest {
@Mock private MessageServiceApiControllerFactory messageServiceApiControllerFactory;
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
when(messageServiceApiControllerFactory.createControllerApi()).thenReturn(messageControllerApi);
}
@Test
- public void
+ void
postEnquiryMessage_Should_ThrowRocketChatPostMessageExceptionWithExceptionInformation_When_PostRcMessageFails() {
CreateEnquiryExceptionInformation exceptionInformation =
mock(CreateEnquiryExceptionInformation.class);
@@ -96,13 +96,13 @@ public void setUp() {
this.messageServiceProvider.postEnquiryMessage(rocketChatData, exceptionInformation);
fail("Expected exception: RocketChatPostMessageException");
} catch (RocketChatPostMessageException exception) {
- assertTrue("Excepted RocketChatPostMessageException thrown", true);
+ assertTrue(true, "Excepted RocketChatPostMessageException thrown");
assertNotNull(exception.getExceptionInformation());
}
}
@Test
- public void
+ void
postEnquiryMessage_Should_CallCreateMessageFromMessageServiceWithCorrectParams_When_EverythingSucceeds()
throws RocketChatPostMessageException {
CreateEnquiryExceptionInformation exceptionInformation =
@@ -124,9 +124,8 @@ public void setUp() {
}
@Test
- public void
- postWelcomeMessageIfConfigured_ShouldNot_CallMessageService_When_NoWelcomeMessageConfigured()
- throws RocketChatPostWelcomeMessageException {
+ void postWelcomeMessageIfConfigured_ShouldNot_CallMessageService_When_NoWelcomeMessageConfigured()
+ throws RocketChatPostWelcomeMessageException {
CreateEnquiryExceptionInformation exceptionInformation =
mock(CreateEnquiryExceptionInformation.class);
@@ -138,7 +137,7 @@ public void setUp() {
}
@Test
- public void
+ void
postWelcomeMessageIfConfigured_Should_ThrowRocketChatPostMessageExceptionWithExceptionInformation_When_GetSystemUserFails()
throws RocketChatUserNotInitializedException {
CreateEnquiryExceptionInformation exceptionInformation =
@@ -150,13 +149,13 @@ public void setUp() {
RC_GROUP_ID, USER, CONSULTING_TYPE_SETTINGS_U25, exceptionInformation);
fail("Expected exception: RocketChatPostWelcomeMessageException");
} catch (RocketChatPostWelcomeMessageException exception) {
- assertTrue("Excepted RocketChatPostWelcomeMessageException thrown", true);
+ assertTrue(true, "Excepted RocketChatPostWelcomeMessageException thrown");
assertNotNull(exception.getExceptionInformation());
}
}
@Test
- public void
+ void
postWelcomeMessageIfConfigured_Should_ThrowRocketChatPostMessageExceptionWithExceptionInformation_When_PostRcMessageFails()
throws RocketChatUserNotInitializedException {
CreateEnquiryExceptionInformation exceptionInformation =
@@ -174,13 +173,13 @@ public void setUp() {
RC_GROUP_ID, USER, CONSULTING_TYPE_SETTINGS_U25, exceptionInformation);
fail("Expected exception: RocketChatPostWelcomeMessageException");
} catch (RocketChatPostWelcomeMessageException exception) {
- assertTrue("Excepted RocketChatPostWelcomeMessageException thrown", true);
+ assertTrue(true, "Excepted RocketChatPostWelcomeMessageException thrown");
assertNotNull(exception.getExceptionInformation());
}
}
@Test
- public void
+ void
postWelcomeMessageIfConfigured_Should_CallCreateMessageFromMessageServiceWithCorrectParams_When_EverythingSucceeds()
throws RocketChatUserNotInitializedException, RocketChatPostWelcomeMessageException {
EasyRandom easyRandom = new EasyRandom();
@@ -200,14 +199,13 @@ public void setUp() {
verify(messageControllerApi)
.createMessage(anyString(), anyString(), eq(RC_GROUP_ID), captor.capture());
- assertFalse(StringUtils.isEmpty(USER.getUsername()));
+ assertFalse(ObjectUtils.isEmpty(USER.getUsername()));
assertThat(captor.getValue().getMessage(), is("Hallo " + USER.getUsername()));
}
@Test
- public void
- postFurtherStepsIfConfigured_ShouldNot_CallMessageService_When_NoFurtherStepsIfConfigured()
- throws RocketChatPostFurtherStepsMessageException {
+ void postFurtherStepsIfConfigured_ShouldNot_CallMessageService_When_NoFurtherStepsIfConfigured()
+ throws RocketChatPostFurtherStepsMessageException {
CreateEnquiryExceptionInformation exceptionInformation =
mock(CreateEnquiryExceptionInformation.class);
@@ -219,22 +217,30 @@ public void setUp() {
verifyNoInteractions(messageControllerApi);
}
- @Test(expected = RocketChatPostFurtherStepsMessageException.class)
- public void
+ @Test
+ void
postFurtherStepsIfConfigured_Should_ThrowRocketChatPostFurtherStepsMessageExceptionWithExceptionInformation_When_PostRcMessageFails()
throws RocketChatPostFurtherStepsMessageException {
- CreateEnquiryExceptionInformation exceptionInformation =
- mock(CreateEnquiryExceptionInformation.class);
- HttpHeaders headers = mock(HttpHeaders.class);
- when(securityHeaderSupplier.getKeycloakAndCsrfHttpHeaders()).thenReturn(headers);
- doThrow(restClientException).when(this.messageControllerApi).saveAliasOnlyMessage(any(), any());
-
- this.messageServiceProvider.postFurtherStepsIfConfigured(
- RC_GROUP_ID, CONSULTING_TYPE_SETTINGS_WITH_FURTHER_STEPS_MESSAGE, exceptionInformation);
+ assertThrows(
+ RocketChatPostFurtherStepsMessageException.class,
+ () -> {
+ CreateEnquiryExceptionInformation exceptionInformation =
+ mock(CreateEnquiryExceptionInformation.class);
+ HttpHeaders headers = mock(HttpHeaders.class);
+ when(securityHeaderSupplier.getKeycloakAndCsrfHttpHeaders()).thenReturn(headers);
+ doThrow(restClientException)
+ .when(this.messageControllerApi)
+ .saveAliasOnlyMessage(any(), any());
+
+ this.messageServiceProvider.postFurtherStepsIfConfigured(
+ RC_GROUP_ID,
+ CONSULTING_TYPE_SETTINGS_WITH_FURTHER_STEPS_MESSAGE,
+ exceptionInformation);
+ });
}
@Test
- public void postFurtherStepsIfConfigured_Should_SaveFurtherStepsMessage_When_Configured()
+ void postFurtherStepsIfConfigured_Should_SaveFurtherStepsMessage_When_Configured()
throws RocketChatPostFurtherStepsMessageException {
CreateEnquiryExceptionInformation exceptionInformation =
mock(CreateEnquiryExceptionInformation.class);
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/mobilepushmessage/FirebasePushMessageServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/service/mobilepushmessage/FirebasePushMessageServiceTest.java
index 6b1ab81fc..41449272c 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/mobilepushmessage/FirebasePushMessageServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/mobilepushmessage/FirebasePushMessageServiceTest.java
@@ -1,6 +1,7 @@
package de.caritas.cob.userservice.api.service.mobilepushmessage;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
@@ -15,15 +16,15 @@
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.FirebaseMessagingException;
import de.caritas.cob.userservice.api.service.LogService;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class FirebasePushMessageServiceTest {
@InjectMocks private FirebasePushMessageService firebasePushMessageService;
@@ -32,7 +33,7 @@ public class FirebasePushMessageServiceTest {
@Mock private Logger logger;
- @Before
+ @BeforeEach
public void setup() {
setField(firebasePushMessageService, "firebaseMessaging", firebaseMessaging);
setInternalState(LogService.class, "LOGGER", logger);
@@ -48,10 +49,14 @@ public void initializeFirebase_Should_notInitialiteFirebaseMessaging_When_fireba
verify(this.logger, times(1)).info("Firebase push notifications are disabled");
}
- @Test(expected = Exception.class)
+ @Test
public void initializeFirebase_Should_throwException_When_configurationCanNotBeLoaded() {
- setField(this.firebasePushMessageService, "isEnabled", true);
- this.firebasePushMessageService.initializeFirebase();
+ assertThrows(
+ Exception.class,
+ () -> {
+ setField(this.firebasePushMessageService, "isEnabled", true);
+ this.firebasePushMessageService.initializeFirebase();
+ });
}
@Test
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/session/SessionMapperTest.java b/src/test/java/de/caritas/cob/userservice/api/service/session/SessionMapperTest.java
index a7f8722d2..f408e8d5a 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/session/SessionMapperTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/session/SessionMapperTest.java
@@ -10,7 +10,7 @@
import de.caritas.cob.userservice.api.model.Session;
import java.time.LocalDateTime;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class SessionMapperTest {
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/session/SessionServiceIT.java b/src/test/java/de/caritas/cob/userservice/api/service/session/SessionServiceIT.java
index 33cfb3de2..1d46e5a0c 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/session/SessionServiceIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/session/SessionServiceIT.java
@@ -27,7 +27,6 @@
import org.assertj.core.util.Lists;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
@@ -35,10 +34,8 @@
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.transaction.annotation.Transactional;
-@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@TestPropertySource(properties = "feature.topics.enabled=true")
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/sessionlist/AvailableLastMessageUpdaterTest.java b/src/test/java/de/caritas/cob/userservice/api/service/sessionlist/AvailableLastMessageUpdaterTest.java
index 80460b536..018990f1f 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/sessionlist/AvailableLastMessageUpdaterTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/sessionlist/AvailableLastMessageUpdaterTest.java
@@ -26,14 +26,14 @@
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class AvailableLastMessageUpdaterTest {
private static final String GROUP_ID = "GroupId";
@@ -47,7 +47,7 @@ public class AvailableLastMessageUpdaterTest {
@Mock private RoomsLastMessageDTO roomsLastMessageDTO;
private SessionDTO session;
- @Before
+ @BeforeEach
public void setup() {
Map rooms = new HashMap<>();
rooms.put(GROUP_ID, roomsLastMessageDTO);
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/sessionlist/ConsultantChatEnricherTest.java b/src/test/java/de/caritas/cob/userservice/api/service/sessionlist/ConsultantChatEnricherTest.java
index a791f9bcc..6b421c3ec 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/sessionlist/ConsultantChatEnricherTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/sessionlist/ConsultantChatEnricherTest.java
@@ -14,9 +14,7 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USERS_EMPTY_ROOMS_LIST;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USERS_ROOMS_LIST;
import static java.util.Collections.singletonList;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -26,14 +24,14 @@
import de.caritas.cob.userservice.api.facade.userdata.ConsultantDataFacade;
import de.caritas.cob.userservice.api.helper.SessionListAnalyser;
import java.util.List;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class ConsultantChatEnricherTest {
@InjectMocks private ConsultantChatEnricher consultantChatEnricher;
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/sessionlist/ConsultantSessionEnricherTest.java b/src/test/java/de/caritas/cob/userservice/api/service/sessionlist/ConsultantSessionEnricherTest.java
index 9438d98ce..5e3fcd142 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/sessionlist/ConsultantSessionEnricherTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/sessionlist/ConsultantSessionEnricherTest.java
@@ -24,9 +24,7 @@
import static java.util.Collections.singletonList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -40,17 +38,17 @@
import java.util.Date;
import java.util.Map;
import org.jeasy.random.EasyRandom;
-import org.junit.After;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.util.ReflectionTestUtils;
-@RunWith(MockitoJUnitRunner.class)
-public class ConsultantSessionEnricherTest {
+@ExtendWith(MockitoExtension.class)
+class ConsultantSessionEnricherTest {
@InjectMocks private ConsultantSessionEnricher consultantSessionEnricher;
@@ -62,13 +60,13 @@ public class ConsultantSessionEnricherTest {
@Mock private SessionTopicEnrichmentService sessionTopicEnrichmentService;
- @After
- public void tearDown() {
+ @AfterEach
+ void tearDown() {
ReflectionTestUtils.setField(consultantSessionEnricher, "topicsFeatureEnabled", false);
}
@Test
- public void
+ void
updateRequiredConsultantSessionValues_Should_ReturnValidSessionListWithMessagesReadTrue_WhenThereAreNoUnreadMessages() {
RocketChatRoomInformation rocketChatRoomInformation =
RocketChatRoomInformation.builder()
@@ -95,7 +93,7 @@ public void tearDown() {
}
@Test
- public void
+ void
updateRequiredConsultantSessionValues_Should_ReturnValidSessionListWithMessagesReadFalse_WhenThereAreUnreadMessages() {
RocketChatRoomInformation rocketChatRoomInformation =
RocketChatRoomInformation.builder()
@@ -122,8 +120,7 @@ public void tearDown() {
}
@Test
- public void
- updateRequiredConsultantSessionValues_Should_EnrichWithTopicsIfTopicFeatureIsEnabled() {
+ void updateRequiredConsultantSessionValues_Should_EnrichWithTopicsIfTopicFeatureIsEnabled() {
ReflectionTestUtils.setField(consultantSessionEnricher, "topicsFeatureEnabled", true);
ReflectionTestUtils.setField(
consultantSessionEnricher, "sessionTopicEnrichmentService", sessionTopicEnrichmentService);
@@ -155,7 +152,7 @@ public void tearDown() {
}
@Test
- public void updateRequiredConsultantSessionValues_Should_SetCorrectMessageDate() {
+ void updateRequiredConsultantSessionValues_Should_SetCorrectMessageDate() {
RocketChatRoomInformation rocketChatRoomInformation =
RocketChatRoomInformation.builder()
.readMessages(MESSAGES_READ_MAP_WITH_UNREADS)
@@ -179,7 +176,7 @@ public void updateRequiredConsultantSessionValues_Should_SetCorrectMessageDate()
}
@Test
- public void
+ void
updateRequiredConsultantSessionValues_Should_ReturnFalseAsAttachmentReceivedStatus_WhenCallingConsultantIsSenderOfTheAttachment() {
RocketChatRoomInformation rocketChatRoomInformation =
RocketChatRoomInformation.builder()
@@ -205,7 +202,7 @@ public void updateRequiredConsultantSessionValues_Should_SetCorrectMessageDate()
}
@Test
- public void
+ void
updateRequiredConsultantSessionValues_Should_ReturnTrueAsAttachmentReceivedStatus_WhenCallingConsultantIsNotSenderOfTheAttachment() {
RocketChatRoomInformation rocketChatRoomInformation =
RocketChatRoomInformation.builder()
@@ -231,7 +228,7 @@ public void updateRequiredConsultantSessionValues_Should_SetCorrectMessageDate()
}
@Test
- public void
+ void
updateRequiredConsultantSessionValues_ShouldNot_SetIsFeedbackReadToFalse_WhenNoMessageWasPostedInTheFeedbackRoom() {
RocketChatRoomInformation rocketChatRoomInformation =
RocketChatRoomInformation.builder()
@@ -257,7 +254,7 @@ public void updateRequiredConsultantSessionValues_Should_SetCorrectMessageDate()
}
@Test
- public void
+ void
updateRequiredConsultantSessionValues_Should_SendListWithMonitoringFalse_When_NoMonitoringSetInConsultingTypeSettings() {
RocketChatRoomInformation rocketChatRoomInformation =
RocketChatRoomInformation.builder()
@@ -278,7 +275,7 @@ public void updateRequiredConsultantSessionValues_Should_SetCorrectMessageDate()
}
@Test
- public void
+ void
updateRequiredConsultantSessionValues_Should_SendListWithMonitoringTrue_When_MonitoringSetInConsultingTypeSettings() {
RocketChatRoomInformation rocketChatRoomInformation =
RocketChatRoomInformation.builder()
@@ -299,7 +296,7 @@ public void updateRequiredConsultantSessionValues_Should_SetCorrectMessageDate()
}
@Test
- public void
+ void
updateRequiredConsultantSessionValues_Should_ReturnCorrectFileTypeAndImagePreviewForSession() {
RocketChatRoomInformation rocketChatRoomInformation =
RocketChatRoomInformation.builder()
@@ -327,7 +324,7 @@ public void updateRequiredConsultantSessionValues_Should_SetCorrectMessageDate()
}
@Test
- public void
+ void
updateRequiredConsultantSessionValues_Should_ReturnSessionListWithMessagesReadFalse_WhenThereAreUnreadMessages() {
RocketChatRoomInformation rocketChatRoomInformation =
RocketChatRoomInformation.builder()
@@ -353,7 +350,7 @@ public void updateRequiredConsultantSessionValues_Should_SetCorrectMessageDate()
}
@Test
- public void
+ void
updateRequiredConsultantSessionValues_Should_ReturnSessionListWithFeedbackReadTrue_WhenThereAreNoUnreadFeedbackMessages() {
RocketChatRoomInformation rocketChatRoomInformation =
RocketChatRoomInformation.builder()
@@ -379,8 +376,7 @@ public void updateRequiredConsultantSessionValues_Should_SetCorrectMessageDate()
}
@Test
- public void
- updateRequiredConsultantSessionValues_Should_ReturnMessageDateAsUnixtime0_WhenNoMessages() {
+ void updateRequiredConsultantSessionValues_Should_ReturnMessageDateAsUnixtime0_WhenNoMessages() {
RocketChatRoomInformation rocketChatRoomInformation =
RocketChatRoomInformation.builder()
.readMessages(MESSAGES_READ_MAP_WITHOUT_UNREADS)
@@ -402,7 +398,7 @@ public void updateRequiredConsultantSessionValues_Should_SetCorrectMessageDate()
}
@Test
- public void
+ void
updateRequiredConsultantSessionValues_Should_ReturnSessionListWithFeedbackReadTrue_WhenFeedbackGroupIdIsNull() {
RocketChatRoomInformation rocketChatRoomInformation =
RocketChatRoomInformation.builder()
@@ -430,7 +426,7 @@ public void updateRequiredConsultantSessionValues_Should_SetCorrectMessageDate()
}
@Test
- public void
+ void
updateRequiredConsultantSessionValues_Should_ReturnSessionListWithChatMessagesReadFalse_WhenThereAreUnreadSessionMessages() {
RocketChatRoomInformation rocketChatRoomInformation =
RocketChatRoomInformation.builder()
@@ -455,7 +451,7 @@ public void updateRequiredConsultantSessionValues_Should_SetCorrectMessageDate()
}
@Test
- public void
+ void
updateRequiredConsultantSessionValues_Should_ReturnSessionListWithChatMessagesReadTrue_WhenThereAreNoUnreadSessionMessages() {
RocketChatRoomInformation rocketChatRoomInformation =
RocketChatRoomInformation.builder()
@@ -480,7 +476,7 @@ public void updateRequiredConsultantSessionValues_Should_SetCorrectMessageDate()
}
@Test
- public void
+ void
updateRequiredConsultantSessionValues_Should_ReturnMessageDateAsFromCreateDate_When_sessionIsAnonymous() {
RocketChatRoomInformation rocketChatRoomInformation =
RocketChatRoomInformation.builder()
@@ -508,7 +504,7 @@ public void updateRequiredConsultantSessionValues_Should_SetCorrectMessageDate()
}
@Test
- public void
+ void
updateRequiredConsultantSessionValues_should_use_fallback_date_if_last_message_is_unavailable() {
var fallbackDates = Map.of(RC_GROUP_ID, new Date(1655730882738L));
RocketChatRoomInformation rocketChatRoomInformation =
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/sessionlist/ConsultantSessionListServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/service/sessionlist/ConsultantSessionListServiceTest.java
index 2b6d416c0..218cb39be 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/sessionlist/ConsultantSessionListServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/sessionlist/ConsultantSessionListServiceTest.java
@@ -14,10 +14,7 @@
import static java.util.Arrays.asList;
import static java.util.Objects.nonNull;
import static org.jsoup.helper.Validate.fail;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
@@ -32,16 +29,16 @@
import de.caritas.cob.userservice.api.service.session.SessionService;
import java.util.ArrayList;
import java.util.List;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
-public class ConsultantSessionListServiceTest {
+@ExtendWith(MockitoExtension.class)
+class ConsultantSessionListServiceTest {
@InjectMocks private ConsultantSessionListService consultantSessionListService;
@Mock private SessionService sessionService;
@@ -50,21 +47,18 @@ public class ConsultantSessionListServiceTest {
@Mock private ConsultantChatEnricher consultantChatEnricher;
@Mock private RocketChatCredentials rocketChatCredentials;
- @Before
- public void setup() {
+ @BeforeEach
+ void setup() {}
+
+ @Test
+ void
+ retrieveSessionsForAuthenticatedConsultant_Should_ReturnOnlySessions_WhenQueryParameterSessionStatusIsNew() {
+
when(sessionService.getRegisteredEnquiriesForConsultant(Mockito.any()))
.thenReturn(CONSULTANT_SESSION_RESPONSE_DTO_LIST);
when(this.consultantSessionEnricher.updateRequiredConsultantSessionValues(
eq(CONSULTANT_SESSION_RESPONSE_DTO_LIST), any(), any()))
.thenReturn(CONSULTANT_SESSION_RESPONSE_DTO_LIST);
- when(this.consultantChatEnricher.updateRequiredConsultantChatValues(
- eq(List.of(CONSULTANT_SESSION_RESPONSE_DTO_WITH_ENCRYPTED_CHAT_MESSAGE)), any(), any()))
- .thenReturn(List.of(CONSULTANT_SESSION_RESPONSE_DTO_WITH_ENCRYPTED_CHAT_MESSAGE));
- }
-
- @Test
- public void
- retrieveSessionsForAuthenticatedConsultant_Should_ReturnOnlySessions_WhenQueryParameterSessionStatusIsNew() {
when(rocketChatCredentials.getRocketChatToken()).thenReturn(RC_TOKEN);
List result =
@@ -81,7 +75,12 @@ public void setup() {
}
@Test
- public void retrieveSessionsForAuthenticatedConsultant_ShouldNot_SendChatsInEnquiryList() {
+ void retrieveSessionsForAuthenticatedConsultant_ShouldNot_SendChatsInEnquiryList() {
+ when(sessionService.getRegisteredEnquiriesForConsultant(Mockito.any()))
+ .thenReturn(CONSULTANT_SESSION_RESPONSE_DTO_LIST);
+ when(this.consultantSessionEnricher.updateRequiredConsultantSessionValues(
+ eq(CONSULTANT_SESSION_RESPONSE_DTO_LIST), any(), any()))
+ .thenReturn(CONSULTANT_SESSION_RESPONSE_DTO_LIST);
when(rocketChatCredentials.getRocketChatToken()).thenReturn(RC_TOKEN);
List result =
@@ -93,7 +92,14 @@ public void retrieveSessionsForAuthenticatedConsultant_ShouldNot_SendChatsInEnqu
}
@Test
- public void retrieveSessionsForAuthenticatedConsultant_Should_MergeSessionsAndChats() {
+ void retrieveSessionsForAuthenticatedConsultant_Should_MergeSessionsAndChats() {
+
+ when(this.consultantSessionEnricher.updateRequiredConsultantSessionValues(
+ eq(CONSULTANT_SESSION_RESPONSE_DTO_LIST), any(), any()))
+ .thenReturn(CONSULTANT_SESSION_RESPONSE_DTO_LIST);
+ when(this.consultantChatEnricher.updateRequiredConsultantChatValues(
+ eq(List.of(CONSULTANT_SESSION_RESPONSE_DTO_WITH_ENCRYPTED_CHAT_MESSAGE)), any(), any()))
+ .thenReturn(List.of(CONSULTANT_SESSION_RESPONSE_DTO_WITH_ENCRYPTED_CHAT_MESSAGE));
when(chatService.getChatsForConsultant(Mockito.any()))
.thenReturn(CONSULTANT_SESSION_RESPONSE_DTO_LIST_WITH_ENCRYPTED_CHAT_MESSAGE);
when(sessionService.getActiveAndDoneSessionsForConsultant(Mockito.any()))
@@ -139,7 +145,7 @@ public void retrieveSessionsForAuthenticatedConsultant_Should_MergeSessionsAndCh
}
@Test
- public void
+ void
retrieveTeamSessionsForAuthenticatedConsultant_Should_ReturnFilteredSessionList_WhenFeedbackFilter() {
List responseDTOS =
new ArrayList<>(
@@ -166,7 +172,7 @@ public void retrieveSessionsForAuthenticatedConsultant_Should_MergeSessionsAndCh
}
@Test
- public void
+ void
retrieveSessionsForAuthenticatedConsultant_Should_returnEmptyList_When_SessionStatusIsInitial() {
SessionListQueryParameter sessionListQueryParameter =
createStandardSessionListQueryParameterObject(0);
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/sessionlist/UserSessionListServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/service/sessionlist/UserSessionListServiceTest.java
index 8457180ff..df4ae3acd 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/sessionlist/UserSessionListServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/sessionlist/UserSessionListServiceTest.java
@@ -23,10 +23,7 @@
import static java.util.Collections.emptyMap;
import static java.util.Objects.nonNull;
import static org.jsoup.helper.Validate.fail;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when;
import de.caritas.cob.userservice.api.adapters.web.dto.UserSessionResponseDTO;
@@ -38,14 +35,14 @@
import de.caritas.cob.userservice.api.service.session.SessionService;
import java.util.Collections;
import java.util.List;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class UserSessionListServiceTest {
@InjectMocks private UserSessionListService userSessionListService;
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/statistics/StatisticsServiceIT.java b/src/test/java/de/caritas/cob/userservice/api/service/statistics/StatisticsServiceIT.java
index 81215a44d..0a58c91db 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/statistics/StatisticsServiceIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/statistics/StatisticsServiceIT.java
@@ -15,8 +15,7 @@
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import org.apache.commons.io.IOUtils;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
@@ -24,9 +23,7 @@
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
-@RunWith(SpringRunner.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@SpringBootTest(classes = UserServiceApplication.class)
@AutoConfigureTestDatabase(replace = Replace.ANY)
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/statistics/StatisticsServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/service/statistics/StatisticsServiceTest.java
index 51ea2e783..d7beff7e8 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/statistics/StatisticsServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/statistics/StatisticsServiceTest.java
@@ -12,20 +12,23 @@
import de.caritas.cob.userservice.statisticsservice.generated.web.model.EventType;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
import org.slf4j.Logger;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
-@RunWith(MockitoJUnitRunner.class)
-public class StatisticsServiceTest {
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
+class StatisticsServiceTest {
private static final String FIELD_NAME_STATISTICS_ENABLED = "statisticsEnabled";
private static final String FIELD_NAME_RABBIT_EXCHANGE_NAME = "rabbitMqExchangeName";
@@ -39,8 +42,8 @@ public class StatisticsServiceTest {
@Mock private AmqpTemplate amqpTemplate;
@Mock Logger logger;
- @Before
- public void setup() {
+ @BeforeEach
+ void setup() {
assignSessionStatisticsEvent = Mockito.mock(AssignSessionStatisticsEvent.class);
when(assignSessionStatisticsEvent.getEventType()).thenReturn(eventType);
when(assignSessionStatisticsEvent.getPayload()).thenReturn(Optional.of(PAYLOAD));
@@ -49,7 +52,7 @@ public void setup() {
}
@Test
- public void fireEvent_Should_NotSendStatisticsMessage_WhenStatisticsIsDisabled() {
+ void fireEvent_Should_NotSendStatisticsMessage_WhenStatisticsIsDisabled() {
setField(statisticsService, FIELD_NAME_STATISTICS_ENABLED, false);
statisticsService.fireEvent(assignSessionStatisticsEvent);
@@ -58,7 +61,7 @@ public void fireEvent_Should_NotSendStatisticsMessage_WhenStatisticsIsDisabled()
}
@Test
- public void fireEvent_Should_SendStatisticsMessage_WhenStatisticsIsEnabled() {
+ void fireEvent_Should_SendStatisticsMessage_WhenStatisticsIsEnabled() {
setField(statisticsService, FIELD_NAME_STATISTICS_ENABLED, true);
when(assignSessionStatisticsEvent.getEventType()).thenReturn(eventType);
@@ -70,7 +73,7 @@ public void fireEvent_Should_SendStatisticsMessage_WhenStatisticsIsEnabled() {
}
@Test
- public void fireEvent_Should_LogWarning_WhenPayloadIsEmpty() {
+ void fireEvent_Should_LogWarning_WhenPayloadIsEmpty() {
setField(statisticsService, FIELD_NAME_STATISTICS_ENABLED, true);
when(assignSessionStatisticsEvent.getPayload()).thenReturn(Optional.empty());
@@ -79,7 +82,7 @@ public void fireEvent_Should_LogWarning_WhenPayloadIsEmpty() {
}
@Test
- public void fireEvent_Should_UseEventTypeAsTopicAndSendPayloadOfEvent() {
+ void fireEvent_Should_UseEventTypeAsTopicAndSendPayloadOfEvent() {
setField(statisticsService, FIELD_NAME_STATISTICS_ENABLED, true);
statisticsService.fireEvent(assignSessionStatisticsEvent);
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/statistics/event/AssignSessionStatisticsEventTest.java b/src/test/java/de/caritas/cob/userservice/api/service/statistics/event/AssignSessionStatisticsEventTest.java
index 9b205d3b8..5aaf611bc 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/statistics/event/AssignSessionStatisticsEventTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/statistics/event/AssignSessionStatisticsEventTest.java
@@ -11,17 +11,17 @@
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Optional;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class AssignSessionStatisticsEventTest {
private AssignSessionStatisticsEvent assignSessionStatisticsEvent;
- @Before
+ @BeforeEach
public void setup() throws NoSuchFieldException, IllegalAccessException {
assignSessionStatisticsEvent =
new AssignSessionStatisticsEvent(CONSULTANT_ID, UserRole.CONSULTANT, SESSION_ID);
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/statistics/event/RegistrationStatisticsEventTest.java b/src/test/java/de/caritas/cob/userservice/api/service/statistics/event/RegistrationStatisticsEventTest.java
index 9febf0a07..4a8c21ae7 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/statistics/event/RegistrationStatisticsEventTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/statistics/event/RegistrationStatisticsEventTest.java
@@ -14,17 +14,17 @@
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class RegistrationStatisticsEventTest {
private RegistrationStatisticsEvent registrationStatisticsEvent;
- @Before
+ @BeforeEach
public void setUp() {
UserDTO registeredUser =
UserDTO.builder()
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/user/UserAccountServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/service/user/UserAccountServiceTest.java
index 05e2336c9..a09a08153 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/user/UserAccountServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/user/UserAccountServiceTest.java
@@ -4,7 +4,8 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USER;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USER_ID;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
@@ -35,15 +36,15 @@
import java.util.Optional;
import org.apache.commons.lang3.RandomStringUtils;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class UserAccountServiceTest {
private static final EasyRandom EASY_RANDOM = new EasyRandom();
@@ -109,12 +110,16 @@ public void retrieveValidatedUser_Should_ReturnUser_When_UserIsPresent() {
assertThat(resultUser).isEqualTo(userMock);
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
retrieveValidatedUser_Should_Throw_InternalServerErrorException_When_UserIsNotPresent() {
- when(userService.getUser(any())).thenReturn(Optional.empty());
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(userService.getUser(any())).thenReturn(Optional.empty());
- this.accountProvider.retrieveValidatedUser();
+ this.accountProvider.retrieveValidatedUser();
+ });
}
@Test
@@ -127,12 +132,16 @@ public void retrieveValidatedConsultant_Should_ReturnConsultant_When_ConsultantI
assertThat(resultUser).isEqualTo(consultantMock);
}
- @Test(expected = InternalServerErrorException.class)
+ @Test
public void
retrieveValidatedConsultant_Should_Throw_InternalServerErrorException_When_ConsultantIsNotPresent() {
- when(consultantService.getConsultant(any())).thenReturn(Optional.empty());
+ assertThrows(
+ InternalServerErrorException.class,
+ () -> {
+ when(consultantService.getConsultant(any())).thenReturn(Optional.empty());
- this.accountProvider.retrieveValidatedConsultant();
+ this.accountProvider.retrieveValidatedConsultant();
+ });
}
@Test
@@ -147,13 +156,17 @@ public void retrieveValidatedConsultant_Should_ReturnConsultant_When_ConsultantI
assertThat(resultUser).isEqualTo(teamConsultantMock);
}
- @Test(expected = ForbiddenException.class)
+ @Test
public void
retrieveValidatedTeamConsultant_Should_Throw_ForbiddenException_When_ConsultantIsNotATeamConsultant() {
- Consultant consultantMock = mock(Consultant.class);
- when(consultantService.getConsultant(any())).thenReturn(Optional.of(consultantMock));
-
- this.accountProvider.retrieveValidatedTeamConsultant();
+ assertThrows(
+ ForbiddenException.class,
+ () -> {
+ Consultant consultantMock = mock(Consultant.class);
+ when(consultantService.getConsultant(any())).thenReturn(Optional.of(consultantMock));
+
+ this.accountProvider.retrieveValidatedTeamConsultant();
+ });
}
@Test
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/user/UserServiceIT.java b/src/test/java/de/caritas/cob/userservice/api/service/user/UserServiceIT.java
index c9faed926..88b5296e1 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/user/UserServiceIT.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/user/UserServiceIT.java
@@ -11,15 +11,12 @@
import de.caritas.cob.userservice.api.port.out.UserRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
-import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
-@RunWith(SpringRunner.class)
@SpringBootTest(classes = UserServiceApplication.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@AutoConfigureTestDatabase(replace = Replace.ANY)
diff --git a/src/test/java/de/caritas/cob/userservice/api/service/user/validation/UserAccountValidatorTest.java b/src/test/java/de/caritas/cob/userservice/api/service/user/validation/UserAccountValidatorTest.java
index ae06121d2..6733a5b2a 100644
--- a/src/test/java/de/caritas/cob/userservice/api/service/user/validation/UserAccountValidatorTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/service/user/validation/UserAccountValidatorTest.java
@@ -3,6 +3,7 @@
import static de.caritas.cob.userservice.api.testHelper.TestConstants.ERROR;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.PASSWORD;
import static de.caritas.cob.userservice.api.testHelper.TestConstants.USERNAME;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -12,24 +13,28 @@
import de.caritas.cob.userservice.api.exception.httpresponses.BadRequestException;
import de.caritas.cob.userservice.api.port.out.IdentityClient;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
-@RunWith(SpringRunner.class)
+@ExtendWith(SpringExtension.class)
public class UserAccountValidatorTest {
@InjectMocks private UserAccountValidator userAccountValidator;
@Mock private IdentityClient identityClient;
- @Test(expected = BadRequestException.class)
+ @Test
public void checkPasswordValidity_Should_ThrowBadRequestException_When_KeycloakLoginFails() {
- when(identityClient.loginUser(anyString(), anyString()))
- .thenThrow(new BadRequestException(ERROR));
-
- this.userAccountValidator.checkPasswordValidity(USERNAME, PASSWORD);
+ assertThrows(
+ BadRequestException.class,
+ () -> {
+ when(identityClient.loginUser(anyString(), anyString()))
+ .thenThrow(new BadRequestException(ERROR));
+
+ this.userAccountValidator.checkPasswordValidity(USERNAME, PASSWORD);
+ });
}
@Test
diff --git a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteAppointmentServiceAskerActionTest.java b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteAppointmentServiceAskerActionTest.java
index c8513e2fd..7ebab2bcc 100644
--- a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteAppointmentServiceAskerActionTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteAppointmentServiceAskerActionTest.java
@@ -21,15 +21,15 @@
import de.caritas.cob.userservice.api.workflow.delete.model.DeletionWorkflowError;
import java.util.ArrayList;
import java.util.List;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class DeleteAppointmentServiceAskerActionTest {
@InjectMocks private DeleteAppointmentServiceAskerAction deleteAppointmentServiceAskerAction;
@@ -38,7 +38,7 @@ public class DeleteAppointmentServiceAskerActionTest {
@Mock private Logger logger;
- @Before
+ @BeforeEach
public void setup() {
setInternalState(DeleteAppointmentServiceAskerAction.class, "log", logger);
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteAskerRoomsAndSessionsActionTest.java b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteAskerRoomsAndSessionsActionTest.java
index c2ddb6e14..6d1a6b570 100644
--- a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteAskerRoomsAndSessionsActionTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteAskerRoomsAndSessionsActionTest.java
@@ -30,15 +30,15 @@
import java.util.List;
import java.util.stream.Collectors;
import org.jeasy.random.EasyRandom;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class DeleteAskerRoomsAndSessionsActionTest {
@InjectMocks private DeleteAskerRoomsAndSessionsAction deleteAskerRoomsAndSessionsAction;
@@ -51,7 +51,7 @@ public class DeleteAskerRoomsAndSessionsActionTest {
@Mock private Logger logger;
- @Before
+ @BeforeEach
public void setup() {
setInternalState(DeleteAskerRoomsAndSessionsAction.class, "log", logger);
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteDatabaseAskerActionTest.java b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteDatabaseAskerActionTest.java
index 6d7eb4336..ed124f000 100644
--- a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteDatabaseAskerActionTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteDatabaseAskerActionTest.java
@@ -21,15 +21,15 @@
import de.caritas.cob.userservice.api.workflow.delete.model.DeletionWorkflowError;
import java.util.ArrayList;
import java.util.List;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class DeleteDatabaseAskerActionTest {
@InjectMocks private DeleteDatabaseAskerAction deleteDatabaseAskerAction;
@@ -38,7 +38,7 @@ public class DeleteDatabaseAskerActionTest {
@Mock private Logger logger;
- @Before
+ @BeforeEach
public void setup() {
setInternalState(DeleteDatabaseAskerAction.class, "log", logger);
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteDatabaseAskerAgencyActionTest.java b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteDatabaseAskerAgencyActionTest.java
index 00f93f8a5..5ed2c51e8 100644
--- a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteDatabaseAskerAgencyActionTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteDatabaseAskerAgencyActionTest.java
@@ -20,15 +20,15 @@
import de.caritas.cob.userservice.api.workflow.delete.model.DeletionWorkflowError;
import java.util.ArrayList;
import java.util.List;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class DeleteDatabaseAskerAgencyActionTest {
@InjectMocks private DeleteDatabaseAskerAgencyAction deleteDatabaseAskerAgencyAction;
@@ -37,7 +37,7 @@ public class DeleteDatabaseAskerAgencyActionTest {
@Mock private Logger logger;
- @Before
+ @BeforeEach
public void setup() {
setInternalState(DeleteDatabaseAskerAgencyAction.class, "log", logger);
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteKeycloakAskerActionTest.java b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteKeycloakAskerActionTest.java
index 7eb6dd913..84507f3e7 100644
--- a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteKeycloakAskerActionTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteKeycloakAskerActionTest.java
@@ -21,17 +21,17 @@
import de.caritas.cob.userservice.api.workflow.delete.model.DeletionWorkflowError;
import java.util.ArrayList;
import java.util.List;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.web.client.HttpClientErrorException;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class DeleteKeycloakAskerActionTest {
@InjectMocks private DeleteKeycloakAskerAction deleteKeycloakAskerAction;
@@ -40,7 +40,7 @@ public class DeleteKeycloakAskerActionTest {
@Mock private Logger logger;
- @Before
+ @BeforeEach
public void setup() {
setInternalState(DeleteKeycloakAskerAction.class, "log", logger);
setInternalState(DeleteKeycloakUserAction.class, "log", logger);
diff --git a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteRocketChatAskerActionTest.java b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteRocketChatAskerActionTest.java
index cde25bad1..b31f37447 100644
--- a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteRocketChatAskerActionTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteRocketChatAskerActionTest.java
@@ -22,15 +22,15 @@
import de.caritas.cob.userservice.api.workflow.delete.model.DeletionWorkflowError;
import java.util.ArrayList;
import java.util.List;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class DeleteRocketChatAskerActionTest {
@InjectMocks private DeleteRocketChatAskerAction deleteRocketChatAskerAction;
@@ -39,7 +39,7 @@ public class DeleteRocketChatAskerActionTest {
@Mock private Logger logger;
- @Before
+ @BeforeEach
public void setup() {
setInternalState(DeleteRocketChatAskerAction.class, "log", logger);
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteSingleRoomAndSessionActionTest.java b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteSingleRoomAndSessionActionTest.java
index 38ba85126..2a5199e88 100644
--- a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteSingleRoomAndSessionActionTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/asker/DeleteSingleRoomAndSessionActionTest.java
@@ -26,15 +26,15 @@
import java.util.ArrayList;
import java.util.List;
import org.jeasy.random.EasyRandom;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class DeleteSingleRoomAndSessionActionTest {
@InjectMocks private DeleteSingleRoomAndSessionAction deleteSingleRoomAndSessionAction;
@@ -47,7 +47,7 @@ public class DeleteSingleRoomAndSessionActionTest {
@Mock private Logger logger;
- @Before
+ @BeforeEach
public void setup() {
setInternalState(DeleteSingleRoomAndSessionAction.class, "log", logger);
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/consultant/DeleteAppointmentServiceConsultantActionTest.java b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/consultant/DeleteAppointmentServiceConsultantActionTest.java
index 898b89615..81f2a5277 100644
--- a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/consultant/DeleteAppointmentServiceConsultantActionTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/consultant/DeleteAppointmentServiceConsultantActionTest.java
@@ -21,15 +21,15 @@
import de.caritas.cob.userservice.api.workflow.delete.model.DeletionWorkflowError;
import java.util.ArrayList;
import java.util.List;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class DeleteAppointmentServiceConsultantActionTest {
@InjectMocks
@@ -39,7 +39,7 @@ public class DeleteAppointmentServiceConsultantActionTest {
@Mock private Logger logger;
- @Before
+ @BeforeEach
public void setup() {
setInternalState(DeleteAppointmentServiceConsultantAction.class, "log", logger);
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/consultant/DeleteChatActionTest.java b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/consultant/DeleteChatActionTest.java
index 4c2b42578..b659c9a18 100644
--- a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/consultant/DeleteChatActionTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/consultant/DeleteChatActionTest.java
@@ -29,15 +29,15 @@
import java.util.List;
import java.util.stream.Collectors;
import org.jeasy.random.EasyRandom;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class DeleteChatActionTest {
@InjectMocks private DeleteChatAction deleteChatAction;
@@ -48,7 +48,7 @@ public class DeleteChatActionTest {
@Mock private Logger logger;
- @Before
+ @BeforeEach
public void setup() {
setInternalState(DeleteChatAction.class, "log", logger);
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/consultant/DeleteDatabaseConsultantActionTest.java b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/consultant/DeleteDatabaseConsultantActionTest.java
index 5ea89de31..7fe597b0a 100644
--- a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/consultant/DeleteDatabaseConsultantActionTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/consultant/DeleteDatabaseConsultantActionTest.java
@@ -7,7 +7,7 @@
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
@@ -25,15 +25,15 @@
import de.caritas.cob.userservice.api.workflow.delete.model.DeletionWorkflowError;
import java.util.ArrayList;
import java.util.List;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class DeleteDatabaseConsultantActionTest {
@InjectMocks private DeleteDatabaseConsultantAction deleteDatabaseConsultantAction;
@@ -44,7 +44,7 @@ public class DeleteDatabaseConsultantActionTest {
@Mock private Logger logger;
- @Before
+ @BeforeEach
public void setup() {
setInternalState(DeleteDatabaseConsultantAction.class, "log", logger);
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/consultant/DeleteDatabaseConsultantAgencyActionTest.java b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/consultant/DeleteDatabaseConsultantAgencyActionTest.java
index d19afe6d6..335d8ecb5 100644
--- a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/consultant/DeleteDatabaseConsultantAgencyActionTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/consultant/DeleteDatabaseConsultantAgencyActionTest.java
@@ -20,15 +20,15 @@
import de.caritas.cob.userservice.api.workflow.delete.model.DeletionWorkflowError;
import java.util.ArrayList;
import java.util.List;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class DeleteDatabaseConsultantAgencyActionTest {
@InjectMocks private DeleteDatabaseConsultantAgencyAction deleteDatabaseConsultantAgencyAction;
@@ -37,7 +37,7 @@ public class DeleteDatabaseConsultantAgencyActionTest {
@Mock private Logger logger;
- @Before
+ @BeforeEach
public void setup() {
setInternalState(DeleteDatabaseConsultantAgencyAction.class, "log", logger);
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/consultant/DeleteKeycloakConsultantActionTest.java b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/consultant/DeleteKeycloakConsultantActionTest.java
index 6d1a279cc..621f5c199 100644
--- a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/consultant/DeleteKeycloakConsultantActionTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/consultant/DeleteKeycloakConsultantActionTest.java
@@ -21,17 +21,17 @@
import de.caritas.cob.userservice.api.workflow.delete.model.DeletionWorkflowError;
import java.util.ArrayList;
import java.util.List;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.web.client.HttpClientErrorException;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class DeleteKeycloakConsultantActionTest {
@InjectMocks private DeleteKeycloakConsultantAction deleteKeycloakConsultantAction;
@@ -40,7 +40,7 @@ public class DeleteKeycloakConsultantActionTest {
@Mock private Logger logger;
- @Before
+ @BeforeEach
public void setup() {
setInternalState(DeleteKeycloakConsultantAction.class, "log", logger);
setInternalState(DeleteKeycloakUserAction.class, "log", logger);
diff --git a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/consultant/DeleteRocketChatConsultantActionTest.java b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/consultant/DeleteRocketChatConsultantActionTest.java
index c2f9c5e0d..337d292a4 100644
--- a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/consultant/DeleteRocketChatConsultantActionTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/consultant/DeleteRocketChatConsultantActionTest.java
@@ -22,15 +22,15 @@
import de.caritas.cob.userservice.api.workflow.delete.model.DeletionWorkflowError;
import java.util.ArrayList;
import java.util.List;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class DeleteRocketChatConsultantActionTest {
@InjectMocks private DeleteRocketChatConsultantAction deleteRocketChatConsultantAction;
@@ -39,7 +39,7 @@ public class DeleteRocketChatConsultantActionTest {
@Mock private Logger logger;
- @Before
+ @BeforeEach
public void setup() {
setInternalState(DeleteRocketChatConsultantAction.class, "log", logger);
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/scheduler/DeleteInactiveSessionsAndUserSchedulerTest.java b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/scheduler/DeleteInactiveSessionsAndUserSchedulerTest.java
index 597c158c5..38b9e506a 100644
--- a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/scheduler/DeleteInactiveSessionsAndUserSchedulerTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/scheduler/DeleteInactiveSessionsAndUserSchedulerTest.java
@@ -6,13 +6,13 @@
import de.caritas.cob.userservice.api.tenant.TenantContextProvider;
import de.caritas.cob.userservice.api.workflow.delete.service.DeleteInactiveSessionsAndUserService;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class DeleteInactiveSessionsAndUserSchedulerTest {
private final String FIELD_NAME_SESSION_INACTIVE_DELETE_WORKFLOW_ENABLED =
diff --git a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/scheduler/DeleteUserAccountSchedulerTest.java b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/scheduler/DeleteUserAccountSchedulerTest.java
index efd128a9c..957748e0d 100644
--- a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/scheduler/DeleteUserAccountSchedulerTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/scheduler/DeleteUserAccountSchedulerTest.java
@@ -4,13 +4,13 @@
import de.caritas.cob.userservice.api.tenant.TenantContextProvider;
import de.caritas.cob.userservice.api.workflow.delete.service.DeleteUserAccountService;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class DeleteUserAccountSchedulerTest {
@InjectMocks private DeleteUserAccountScheduler deleteUserAccountScheduler;
diff --git a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/scheduler/DeleteUserAnonymousSchedulerTest.java b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/scheduler/DeleteUserAnonymousSchedulerTest.java
index 781c29109..2963e32bf 100644
--- a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/scheduler/DeleteUserAnonymousSchedulerTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/scheduler/DeleteUserAnonymousSchedulerTest.java
@@ -4,13 +4,13 @@
import de.caritas.cob.userservice.api.tenant.TenantContextProvider;
import de.caritas.cob.userservice.api.workflow.delete.service.DeleteUserAnonymousService;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class DeleteUserAnonymousSchedulerTest {
@InjectMocks private DeleteUserAnonymousScheduler deleteUserAnonymousScheduler;
diff --git a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/scheduler/DeleteUsersRegisteredOnlySchedulerTest.java b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/scheduler/DeleteUsersRegisteredOnlySchedulerTest.java
index c57b3364c..5c0ded6ee 100644
--- a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/scheduler/DeleteUsersRegisteredOnlySchedulerTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/scheduler/DeleteUsersRegisteredOnlySchedulerTest.java
@@ -6,13 +6,13 @@
import de.caritas.cob.userservice.api.tenant.TenantContextProvider;
import de.caritas.cob.userservice.api.workflow.delete.service.DeleteUsersRegisteredOnlyService;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class DeleteUsersRegisteredOnlySchedulerTest {
@InjectMocks DeleteUsersRegisteredOnlyScheduler deleteUsersRegisteredOnlyScheduler;
diff --git a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/DeleteInactiveSessionsAndUserServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/DeleteInactiveSessionsAndUserServiceTest.java
index 92b1a151e..383a2338e 100644
--- a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/DeleteInactiveSessionsAndUserServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/DeleteInactiveSessionsAndUserServiceTest.java
@@ -21,14 +21,14 @@
import java.util.Map;
import java.util.Optional;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class DeleteInactiveSessionsAndUserServiceTest {
@InjectMocks private DeleteInactiveSessionsAndUserService deleteInactiveSessionsAndUserService;
diff --git a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/DeleteSessionServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/DeleteSessionServiceTest.java
index 3a4e21c74..8c0bbd5c9 100644
--- a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/DeleteSessionServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/DeleteSessionServiceTest.java
@@ -13,13 +13,13 @@
import de.caritas.cob.userservice.api.model.Session;
import de.caritas.cob.userservice.api.workflow.delete.action.asker.DeleteSingleRoomAndSessionAction;
import de.caritas.cob.userservice.api.workflow.delete.model.SessionDeletionWorkflowDTO;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class DeleteSessionServiceTest {
@InjectMocks private DeleteSessionService deleteSessionService;
diff --git a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/DeleteUserAccountServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/DeleteUserAccountServiceTest.java
index a6e4e57ca..4bbc8e8bc 100644
--- a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/DeleteUserAccountServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/DeleteUserAccountServiceTest.java
@@ -25,13 +25,13 @@
import de.caritas.cob.userservice.api.workflow.delete.action.consultant.DeleteRocketChatConsultantAction;
import de.caritas.cob.userservice.api.workflow.delete.model.AskerDeletionWorkflowDTO;
import de.caritas.cob.userservice.api.workflow.delete.model.ConsultantDeletionWorkflowDTO;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class DeleteUserAccountServiceTest {
@InjectMocks private DeleteUserAccountService deleteUserAccountService;
diff --git a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/DeleteUsersRegisteredOnlyServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/DeleteUsersRegisteredOnlyServiceTest.java
index 25bb2c986..cf16ad20e 100644
--- a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/DeleteUsersRegisteredOnlyServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/DeleteUsersRegisteredOnlyServiceTest.java
@@ -17,14 +17,14 @@
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Collections;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class DeleteUsersRegisteredOnlyServiceTest {
@InjectMocks private DeleteUsersRegisteredOnlyService deleteUsersRegisteredOnlyService;
diff --git a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/WorkflowErrorLogServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/WorkflowErrorLogServiceTest.java
index 43274c0e5..2a6e54b3b 100644
--- a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/WorkflowErrorLogServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/WorkflowErrorLogServiceTest.java
@@ -12,21 +12,21 @@
import java.util.ArrayList;
import java.util.List;
import org.assertj.core.api.Assertions;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.LoggerFactory;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class WorkflowErrorLogServiceTest {
@InjectMocks private WorkflowErrorLogService workflowErrorLogService;
private ListAppender listAppender;
- @Before
+ @BeforeEach
public void setUp() {
Logger logger = (Logger) LoggerFactory.getLogger(WorkflowErrorLogService.class);
listAppender = new ListAppender<>();
diff --git a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/WorkflowErrorMailServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/WorkflowErrorMailServiceTest.java
index 0f6157f12..d935bfc07 100644
--- a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/WorkflowErrorMailServiceTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/WorkflowErrorMailServiceTest.java
@@ -19,16 +19,16 @@
import de.caritas.cob.userservice.mailservice.generated.web.model.ErrorMailDTO;
import de.caritas.cob.userservice.mailservice.generated.web.model.TemplateDataDTO;
import java.util.List;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.util.ReflectionTestUtils;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class WorkflowErrorMailServiceTest {
@InjectMocks private WorkflowErrorMailService workflowErrorMailService;
@@ -37,7 +37,7 @@ public class WorkflowErrorMailServiceTest {
@Mock private TenantTemplateSupplier tenantTemplateSupplier;
- @Before
+ @BeforeEach
public void setup() {
setField(workflowErrorMailService, "applicationBaseUrl", "www.host.de");
}
diff --git a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/provider/InactivePrivateGroupsProviderTest.java b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/provider/InactivePrivateGroupsProviderTest.java
index 441ef4b50..85d1a71aa 100644
--- a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/provider/InactivePrivateGroupsProviderTest.java
+++ b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/provider/InactivePrivateGroupsProviderTest.java
@@ -26,15 +26,15 @@
import java.util.List;
import org.apache.commons.collections4.IterableUtils;
import org.jeasy.random.EasyRandom;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class InactivePrivateGroupsProviderTest {
@InjectMocks private InactivePrivateGroupsProvider inactivePrivateGroupsProvider;
@@ -43,7 +43,7 @@ public class InactivePrivateGroupsProviderTest {
@Mock private ChatRepository chatRepository;
@Mock private Logger logger;
- @Before
+ @BeforeEach
public void setup() {
setInternalState(LogService.class, "LOGGER", logger);
}
diff --git a/src/test/resources/database/UserServiceDatabase.sql b/src/test/resources/database/UserServiceDatabase.sql
index 494c06496..ed6680d37 100644
--- a/src/test/resources/database/UserServiceDatabase.sql
+++ b/src/test/resources/database/UserServiceDatabase.sql
@@ -1,8 +1,13 @@
+CREATE sequence if not exists sequence_session;
+CREATE sequence if not exists sequence_session_topic;
+CREATE sequence if not exists sequence_consultant_agency;
+CREATE sequence if not exists sequence_admin_agency;
+
ALTER SEQUENCE sequence_session RESTART WITH 100000;
ALTER SEQUENCE sequence_session_topic RESTART WITH 100000;
ALTER SEQUENCE sequence_consultant_agency RESTART WITH 100000;
ALTER SEQUENCE sequence_admin_agency RESTART WITH 100000;
-INSERT INTO user (`user_id`, `id_old`, `delete_date`, `username`, `email`, `rc_user_id`,
+INSERT INTO user(`user_id`, `id_old`, `delete_date`, `username`, `email`, `rc_user_id`,
`language_formal`, `create_date`, `update_date`,`notifications_enabled`)
VALUES ('015d013d-95e7-4e91-85b5-12cdb3d317f3', 0, NULL, 'enc.OBSXEZTPOJWWC3TDMUWWC43LMVZC2NZS',
'015d013d-95e7-4e91-85b5-12cdb3d317f3@beratungcaritas.de', 'dciScSDa9Qm8vmEBB', 1,