diff --git a/.github/workflows/dockerImageSkipTests.yml b/.github/workflows/dockerImageSkipTests.yml
index a457bf8..1edb54a 100644
--- a/.github/workflows/dockerImageSkipTests.yml
+++ b/.github/workflows/dockerImageSkipTests.yml
@@ -40,7 +40,7 @@ jobs:
key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/pom.xml') }}
- name: Maven Package
run: mvn -B -Pprod clean package -DskipTests
- - uses: actions/upload-artifact@v2
+ - uses: actions/upload-artifact@v4
with:
name: targetfiles
path: target/*.jar
@@ -71,7 +71,7 @@ jobs:
steps:
- uses: actions/checkout@v2
- name: Download buildfiles artifact
- uses: actions/download-artifact@v2
+ uses: actions/download-artifact@v4
with:
name: targetfiles
- name: Get current time
@@ -179,4 +179,4 @@ jobs:
value: ${{ env.DOCKER_IMAGE_TAG }}
custom-actions: |
- text: View CI
- url: "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
\ No newline at end of file
+ url: "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
diff --git a/pom.xml b/pom.xml
index 8bab793..a7a513a 100644
--- a/pom.xml
+++ b/pom.xml
@@ -16,7 +16,7 @@
org.springframework.boot
spring-boot-starter-parent
- 3.0.13
+ 3.3.8
@@ -31,13 +31,14 @@
6.4.0
4.23.2
4.23.2
+ 6.3.4
3.0.0
- 6.0.5
+ 6.0.8
17
17
3.11
4.4
- 1.15
+ 1.17.2
3.0.1
@@ -66,17 +67,14 @@
org.springframework.security
spring-security-web
- ${spring-security.version}
org.springframework.security
spring-security-config
- ${spring-security.version}
org.springframework.security
spring-security-core
- ${spring-security.version}
org.springframework.boot
@@ -85,11 +83,6 @@
org.hibernate.validator
hibernate-validator
- 8.0.0.Final
-
-
- org.springframework.boot
- spring-boot-starter-cache
org.sonatype.plexus
@@ -143,7 +136,7 @@
org.springdoc
springdoc-openapi-starter-webmvc-ui
- 2.4.0
+ 2.6.0
@@ -163,9 +156,8 @@
${keycloak.version}
- javax.ws.rs
- javax.ws.rs-api
- 2.1.1
+ jakarta.ws.rs
+ jakarta.ws.rs-api
@@ -179,7 +171,6 @@
org.apache.commons
commons-lang3
- ${commons-lang3.version}
@@ -199,7 +190,6 @@
commons-codec
commons-codec
- ${commons-codec.version}
@@ -212,7 +202,6 @@
org.liquibase
liquibase-core
- ${liquibase-core.version}
@@ -223,22 +212,18 @@
org.apache.logging.log4j
log4j-core
- ${log4j.version}
org.apache.logging.log4j
log4j-api
- ${log4j.version}
org.apache.logging.log4j
log4j-to-slf4j
- ${log4j.version}
org.yaml
snakeyaml
- 2.0
@@ -249,7 +234,6 @@
org.springframework.security
spring-security-test
- ${spring-security-test.version}
test
@@ -275,6 +259,12 @@
concurrent-junit
1.0.2
test
+
+
+ junit
+ junit
+
+
com.github.fridujo
@@ -442,7 +432,7 @@
org.apache.maven.plugins
maven-checkstyle-plugin
- 3.3.0
+ 3.6.0
validate
@@ -466,9 +456,8 @@
org.apache.maven.plugins
maven-compiler-plugin
- 17
- 17
--enable-preview
+ ${java.version}
@@ -508,6 +497,24 @@
+
+ org.openrewrite.maven
+ rewrite-maven-plugin
+ 6.0.4
+
+ true
+
+ org.openrewrite.java.spring.boot3.UpgradeSpringBoot_3_3
+
+
+
+
+ org.openrewrite.recipe
+ rewrite-spring
+ 6.0.2
+
+
+
diff --git a/src/main/java/de/caritas/cob/messageservice/Messenger.java b/src/main/java/de/caritas/cob/messageservice/Messenger.java
index db51609..d904d35 100644
--- a/src/main/java/de/caritas/cob/messageservice/Messenger.java
+++ b/src/main/java/de/caritas/cob/messageservice/Messenger.java
@@ -259,7 +259,7 @@ public boolean patchEventMessage(String rcToken, String rcUserId, String message
}
if (!message.isA(MessageType.REASSIGN_CONSULTANT)) {
- var errorMessage = String.format("Message (%s) is not a reassignment.", messageId);
+ var errorMessage = "Message (%s) is not a reassignment.".formatted(messageId);
throw new BadRequestException(errorMessage, LogService::logBadRequest);
}
diff --git a/src/main/java/de/caritas/cob/messageservice/api/controller/MessageController.java b/src/main/java/de/caritas/cob/messageservice/api/controller/MessageController.java
index 1db6055..5355bd1 100644
--- a/src/main/java/de/caritas/cob/messageservice/api/controller/MessageController.java
+++ b/src/main/java/de/caritas/cob/messageservice/api/controller/MessageController.java
@@ -27,7 +27,7 @@
import de.caritas.cob.messageservice.api.service.MessageMapper;
import de.caritas.cob.messageservice.api.service.RocketChatService;
import de.caritas.cob.messageservice.generated.api.controller.MessagesApi;
-import io.swagger.annotations.Api;
+import io.swagger.v3.oas.annotations.tags.Tag;
import java.time.Instant;
import java.util.Optional;
import jakarta.validation.Valid;
@@ -41,8 +41,8 @@
* Controller for message requests.
*/
@RestController
+@Tag(name = "message-controller")
@RequiredArgsConstructor
-@Api(tags = "message-controller")
public class MessageController implements MessagesApi {
private final @NonNull RocketChatService rocketChatService;
@@ -245,19 +245,19 @@ public ResponseEntity saveAliasOnlyMessage(String rcGroupId,
var aliasArgs = aliasOnlyMessageDTO.getArgs();
if (type.equals(MessageType.USER_MUTED) || type.equals(MessageType.USER_UNMUTED)) {
- var message = String.format("Message type (%s) is protected.", type);
+ var message = "Message type (%s) is protected.".formatted(type);
throw new BadRequestException(message, LogService::logBadRequest);
}
if (nonNull(aliasArgs) && type != MessageType.REASSIGN_CONSULTANT) {
- var message = String.format("Alias args are not supported by type (%s).", type);
+ var message = "Alias args are not supported by type (%s).".formatted(type);
throw new BadRequestException(message, LogService::logBadRequest);
}
if (type == MessageType.REASSIGN_CONSULTANT && hasMissingMandatoryAliasArgForReassignment(
aliasArgs)) {
var errorFormat = "toConsultantId is required during reassignment creation (%s).";
- var message = String.format(errorFormat, MessageType.REASSIGN_CONSULTANT);
+ var message = errorFormat.formatted(MessageType.REASSIGN_CONSULTANT);
throw new BadRequestException(message, LogService::logBadRequest);
}
@@ -290,7 +290,7 @@ public ResponseEntity patchMessage(String rcToken, String rcUserId, String
AliasArgs aliasArgs) {
var reassignStatus = aliasArgs.getStatus();
if (reassignStatus == ReassignStatus.REQUESTED) {
- var message = String.format("Updating to status (%s) is not supported.", reassignStatus);
+ var message = "Updating to status (%s) is not supported.".formatted(reassignStatus);
throw new BadRequestException(message, LogService::logBadRequest);
}
diff --git a/src/main/java/de/caritas/cob/messageservice/api/exception/CustomCryptoException.java b/src/main/java/de/caritas/cob/messageservice/api/exception/CustomCryptoException.java
index 3ab0e36..d494c0d 100644
--- a/src/main/java/de/caritas/cob/messageservice/api/exception/CustomCryptoException.java
+++ b/src/main/java/de/caritas/cob/messageservice/api/exception/CustomCryptoException.java
@@ -1,7 +1,10 @@
package de.caritas.cob.messageservice.api.exception;
+import java.io.Serial;
+
public class CustomCryptoException extends Exception {
+ @Serial
private static final long serialVersionUID = 1232112575979020932L;
/**
diff --git a/src/main/java/de/caritas/cob/messageservice/api/exception/HelperException.java b/src/main/java/de/caritas/cob/messageservice/api/exception/HelperException.java
index f15262e..cacdb3b 100644
--- a/src/main/java/de/caritas/cob/messageservice/api/exception/HelperException.java
+++ b/src/main/java/de/caritas/cob/messageservice/api/exception/HelperException.java
@@ -1,6 +1,9 @@
package de.caritas.cob.messageservice.api.exception;
+import java.io.Serial;
+
public class HelperException extends RuntimeException {
+ @Serial
private static final long serialVersionUID = -1321906171569622899L;
/**
diff --git a/src/main/java/de/caritas/cob/messageservice/api/exception/KeycloakException.java b/src/main/java/de/caritas/cob/messageservice/api/exception/KeycloakException.java
index a6644ec..afcaad2 100644
--- a/src/main/java/de/caritas/cob/messageservice/api/exception/KeycloakException.java
+++ b/src/main/java/de/caritas/cob/messageservice/api/exception/KeycloakException.java
@@ -1,7 +1,10 @@
package de.caritas.cob.messageservice.api.exception;
+import java.io.Serial;
+
public class KeycloakException extends RuntimeException {
+ @Serial
private static final long serialVersionUID = -5083156826149548581L;
/**
diff --git a/src/main/java/de/caritas/cob/messageservice/api/exception/NoMasterKeyException.java b/src/main/java/de/caritas/cob/messageservice/api/exception/NoMasterKeyException.java
index 19c7371..8d5d30e 100644
--- a/src/main/java/de/caritas/cob/messageservice/api/exception/NoMasterKeyException.java
+++ b/src/main/java/de/caritas/cob/messageservice/api/exception/NoMasterKeyException.java
@@ -1,7 +1,10 @@
package de.caritas.cob.messageservice.api.exception;
+import java.io.Serial;
+
public class NoMasterKeyException extends RuntimeException {
+ @Serial
private static final long serialVersionUID = 362702101121444833L;
/**
diff --git a/src/main/java/de/caritas/cob/messageservice/api/exception/RocketChatBadRequestException.java b/src/main/java/de/caritas/cob/messageservice/api/exception/RocketChatBadRequestException.java
index 3803c01..023ba5a 100644
--- a/src/main/java/de/caritas/cob/messageservice/api/exception/RocketChatBadRequestException.java
+++ b/src/main/java/de/caritas/cob/messageservice/api/exception/RocketChatBadRequestException.java
@@ -1,9 +1,11 @@
package de.caritas.cob.messageservice.api.exception;
+import java.io.Serial;
import java.util.function.Consumer;
public class RocketChatBadRequestException extends CustomLoggableResponseException {
+ @Serial
private static final long serialVersionUID = 362702101121444833L;
/**
diff --git a/src/main/java/de/caritas/cob/messageservice/api/exception/RocketChatLoginException.java b/src/main/java/de/caritas/cob/messageservice/api/exception/RocketChatLoginException.java
index 1d528b6..37a7dca 100644
--- a/src/main/java/de/caritas/cob/messageservice/api/exception/RocketChatLoginException.java
+++ b/src/main/java/de/caritas/cob/messageservice/api/exception/RocketChatLoginException.java
@@ -1,7 +1,10 @@
package de.caritas.cob.messageservice.api.exception;
+import java.io.Serial;
+
public class RocketChatLoginException extends RuntimeException {
+ @Serial
private static final long serialVersionUID = 5198347832036308397L;
/**
diff --git a/src/main/java/de/caritas/cob/messageservice/api/exception/RocketChatPostMarkGroupAsReadException.java b/src/main/java/de/caritas/cob/messageservice/api/exception/RocketChatPostMarkGroupAsReadException.java
index 91d4f3f..475f188 100644
--- a/src/main/java/de/caritas/cob/messageservice/api/exception/RocketChatPostMarkGroupAsReadException.java
+++ b/src/main/java/de/caritas/cob/messageservice/api/exception/RocketChatPostMarkGroupAsReadException.java
@@ -1,7 +1,10 @@
package de.caritas.cob.messageservice.api.exception;
+import java.io.Serial;
+
public class RocketChatPostMarkGroupAsReadException extends RuntimeException {
+ @Serial
private static final long serialVersionUID = -5666387091852981692L;
/**
diff --git a/src/main/java/de/caritas/cob/messageservice/api/exception/RocketChatSendMessageException.java b/src/main/java/de/caritas/cob/messageservice/api/exception/RocketChatSendMessageException.java
index 57a9cdb..4475982 100644
--- a/src/main/java/de/caritas/cob/messageservice/api/exception/RocketChatSendMessageException.java
+++ b/src/main/java/de/caritas/cob/messageservice/api/exception/RocketChatSendMessageException.java
@@ -1,7 +1,10 @@
package de.caritas.cob.messageservice.api.exception;
+import java.io.Serial;
+
public class RocketChatSendMessageException extends RuntimeException {
+ @Serial
private static final long serialVersionUID = 1232112575979020931L;
/**
diff --git a/src/main/java/de/caritas/cob/messageservice/api/helper/UserHelper.java b/src/main/java/de/caritas/cob/messageservice/api/helper/UserHelper.java
index 6120f9a..8804b0c 100644
--- a/src/main/java/de/caritas/cob/messageservice/api/helper/UserHelper.java
+++ b/src/main/java/de/caritas/cob/messageservice/api/helper/UserHelper.java
@@ -26,7 +26,7 @@ private String base32EncodeUsername(String username) {
.replace(BASE32_PLACEHOLDER, BASE32_PLACEHOLDER_REPLACE_STRING);
} catch (Exception exception) {
// Catch generic exception because of lack of base32 documentation
- throw new HelperException(String.format("Could not encode username %s", username), exception);
+ throw new HelperException("Could not encode username %s".formatted(username), exception);
}
}
@@ -43,7 +43,7 @@ private String base32DecodeUsername(String username) {
.toUpperCase().replace(BASE32_PLACEHOLDER_REPLACE_STRING, BASE32_PLACEHOLDER)));
} catch (Exception exception) {
// Catch generic exception because of lack of base32 documentation
- throw new HelperException(String.format("Could not decode username %s", username), exception);
+ throw new HelperException("Could not decode username %s".formatted(username), exception);
}
}
diff --git a/src/main/java/de/caritas/cob/messageservice/api/model/rocket/chat/message/MessagesDTO.java b/src/main/java/de/caritas/cob/messageservice/api/model/rocket/chat/message/MessagesDTO.java
index 83f25c1..aea5975 100644
--- a/src/main/java/de/caritas/cob/messageservice/api/model/rocket/chat/message/MessagesDTO.java
+++ b/src/main/java/de/caritas/cob/messageservice/api/model/rocket/chat/message/MessagesDTO.java
@@ -9,8 +9,7 @@
import de.caritas.cob.messageservice.api.model.AttachmentDTO;
import de.caritas.cob.messageservice.api.model.FileDTO;
import de.caritas.cob.messageservice.api.model.jsondeserializer.AliasJsonDeserializer;
-import io.swagger.annotations.ApiModel;
-import io.swagger.annotations.ApiModelProperty;
+import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@@ -28,50 +27,49 @@
@Setter
@AllArgsConstructor
@NoArgsConstructor
-@ApiModel(value = "Messages")
+@Schema(name = "Messages")
public class MessagesDTO {
- @ApiModelProperty(required = true, example = "M73fE4WhYF4peYB3s", position = 0)
+ @Schema(required = true, example = "M73fE4WhYF4peYB3s")
private String _id;
- @ApiModelProperty(required = false, example = "%7B%0A%20%20%22message%22%3A%20", position = 1)
+ @Schema(required = false, example = "%7B%0A%20%20%22message%22%3A%20")
@JsonDeserialize(using = AliasJsonDeserializer.class)
private AliasMessageDTO alias;
- @ApiModelProperty(required = true, example = "fR2Rz7dmWmHdXE8uz", position = 2)
+ @Schema(required = true, example = "fR2Rz7dmWmHdXE8uz")
private String rid;
- @ApiModelProperty(required = true, example = "Lorem ipsum dolor sit amet, consetetur...",
- position = 3)
+ @Schema(required = true, example = "Lorem ipsum dolor sit amet, consetetur...")
private String msg;
- @ApiModelProperty(required = true, example = "2018-11-15T09:33:00.057Z", position = 4)
+ @Schema(required = true, example = "2018-11-15T09:33:00.057Z")
private String ts;
- @ApiModelProperty(required = true, position = 5)
+ @Schema(required = true)
private UserDTO u;
- @ApiModelProperty(required = true, position = 6)
+ @Schema(required = true)
private boolean unread;
@JsonIgnore
- @ApiModelProperty(required = true, position = 7)
+ @Schema(required = true)
private String[] mentions;
@JsonIgnore
- @ApiModelProperty(required = true, position = 8)
+ @Schema(required = true)
private String[] channels;
- @ApiModelProperty(required = true, example = "2018-11-15T09:33:00.067Z", position = 9)
+ @Schema(required = true, example = "2018-11-15T09:33:00.067Z")
private String _updatedAt;
- @ApiModelProperty(required = false, position = 10)
+ @Schema(required = false)
private AttachmentDTO[] attachments;
- @ApiModelProperty(required = false, position = 11)
+ @Schema(required = false)
private FileDTO file;
- @ApiModelProperty
+ @Schema
private String t;
@JsonIgnore
diff --git a/src/main/java/de/caritas/cob/messageservice/api/model/rocket/chat/message/UserDTO.java b/src/main/java/de/caritas/cob/messageservice/api/model/rocket/chat/message/UserDTO.java
index 9dd356e..8126f5f 100644
--- a/src/main/java/de/caritas/cob/messageservice/api/model/rocket/chat/message/UserDTO.java
+++ b/src/main/java/de/caritas/cob/messageservice/api/model/rocket/chat/message/UserDTO.java
@@ -2,8 +2,7 @@
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import de.caritas.cob.messageservice.api.model.jsondeserializer.DecodeUsernameJsonDeserializer;
-import io.swagger.annotations.ApiModel;
-import io.swagger.annotations.ApiModelProperty;
+import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@@ -20,16 +19,16 @@
@Setter
@AllArgsConstructor
@NoArgsConstructor
-@ApiModel(value = "U")
+@Schema(name = "U")
public class UserDTO {
- @ApiModelProperty(required = true, example = "vppRFqjrzTsTZ6iEn", position = 0)
+ @Schema(required = true, example = "vppRFqjrzTsTZ6iEn")
private String _id;
- @ApiModelProperty(required = true, example = "test", position = 1)
+ @Schema(required = true, example = "test")
@JsonDeserialize(using = DecodeUsernameJsonDeserializer.class)
private String username;
- @ApiModelProperty(required = true, example = "Mustermax", position = 3)
+ @Schema(required = true, example = "Mustermax")
private String name;
}
diff --git a/src/main/java/de/caritas/cob/messageservice/api/service/LiveEventNotificationService.java b/src/main/java/de/caritas/cob/messageservice/api/service/LiveEventNotificationService.java
index e27c656..d7b7a69 100644
--- a/src/main/java/de/caritas/cob/messageservice/api/service/LiveEventNotificationService.java
+++ b/src/main/java/de/caritas/cob/messageservice/api/service/LiveEventNotificationService.java
@@ -36,7 +36,7 @@ public void sendLiveEvent(String rcGroupId, String accessToken, Optional t
liveProxyControllerApi.sendLiveEvent(rcGroupId);
} catch (RestClientException e) {
LogService.logInternalServerError(
- String.format("Unable to trigger live event for rc group id %s", rcGroupId), e);
+ "Unable to trigger live event for rc group id %s".formatted(rcGroupId), e);
}
}
}
diff --git a/src/main/java/de/caritas/cob/messageservice/api/service/RocketChatService.java b/src/main/java/de/caritas/cob/messageservice/api/service/RocketChatService.java
index 04dbe22..55b8da4 100644
--- a/src/main/java/de/caritas/cob/messageservice/api/service/RocketChatService.java
+++ b/src/main/java/de/caritas/cob/messageservice/api/service/RocketChatService.java
@@ -136,7 +136,7 @@ private MessageStreamDTO obtainMessageStream(String rcToken, String rcUserId, UR
} catch (RestClientException exception) {
LogService.logRocketChatServiceError(exception);
- var msg = String.format("Could not read message stream from Rocket.Chat API (uri: %s)", uri);
+ var msg = "Could not read message stream from Rocket.Chat API (uri: %s)".formatted(uri);
throw new InternalServerErrorException(msg, LogService::logRocketChatServiceError);
}
}
@@ -155,7 +155,7 @@ private URI buildMessageStreamUri(String rcGroupId, int offset, int count, Insta
} catch (IllegalArgumentException exception) {
throw new InternalServerErrorException(
- String.format("Could not build message stream URI for rcGroupId %s", rcGroupId),
+ "Could not build message stream URI for rcGroupId %s".formatted(rcGroupId),
LogService::logRocketChatServiceError);
}
}
@@ -318,7 +318,7 @@ public void markGroupAsReadForSystemUser(String rcGroupId) {
} else {
LogService.logRocketChatServiceError(
- String.format("Could not set messages as read for system user in group %s", rcGroupId));
+ "Could not set messages as read for system user in group %s".formatted(rcGroupId));
}
}
@@ -363,8 +363,7 @@ public GetGroupInfoDto getGroupInfo(String rcToken, String rcUserId, String rcGr
} catch (HttpClientErrorException clientErrorEx) {
throw new RocketChatBadRequestException(
- String.format(
- "Rocket.Chat API call failed with status %s for parameters rcUserId: %s, rcGroupId: %s)",
+ "Rocket.Chat API call failed with status %s for parameters rcUserId: %s, rcGroupId: %s)".formatted(
clientErrorEx.getStatusCode(), rcUserId, rcGroupId),
LogService::logRocketChatBadRequestError);
}
@@ -382,7 +381,7 @@ public Message findMessage(String rcToken, String rcUserId, String messageId) {
} catch (HttpClientErrorException exception) {
if (!isRcNotFoundResponse(exception)) {
var errorFormat = "Could not read message (%s) from Rocket.Chat API";
- var errorMessage = String.format(errorFormat, messageId);
+ var errorMessage = errorFormat.formatted(messageId);
throw new InternalServerErrorException(errorMessage, LogService::logRocketChatServiceError);
}
}
diff --git a/src/main/java/de/caritas/cob/messageservice/api/service/dto/Message.java b/src/main/java/de/caritas/cob/messageservice/api/service/dto/Message.java
index ebadef7..7c18be0 100644
--- a/src/main/java/de/caritas/cob/messageservice/api/service/dto/Message.java
+++ b/src/main/java/de/caritas/cob/messageservice/api/service/dto/Message.java
@@ -10,7 +10,7 @@
import java.util.LinkedHashMap;
import java.util.Map;
import lombok.Data;
-import org.springframework.util.StringUtils;
+import org.springframework.util.ObjectUtils;
@Data
public class Message {
@@ -41,7 +41,7 @@ public Map getOtherProperties() {
@JsonIgnore
public boolean isA(MessageType messageType) {
- if (StringUtils.isEmpty(alias)) {
+ if (ObjectUtils.isEmpty(alias)) {
return false;
}
diff --git a/src/main/java/de/caritas/cob/messageservice/api/service/helper/RocketChatCredentialsHelper.java b/src/main/java/de/caritas/cob/messageservice/api/service/helper/RocketChatCredentialsHelper.java
index e53c16b..3922370 100644
--- a/src/main/java/de/caritas/cob/messageservice/api/service/helper/RocketChatCredentialsHelper.java
+++ b/src/main/java/de/caritas/cob/messageservice/api/service/helper/RocketChatCredentialsHelper.java
@@ -173,7 +173,7 @@ private void logoutUser(String rcUserId, String rcAuthToken) {
} catch (Exception ex) {
LogService.logRocketChatServiceError(
- String.format("Could not log out user id (%s) from Rocket.Chat", rcUserId), ex);
+ "Could not log out user id (%s) from Rocket.Chat".formatted(rcUserId), ex);
}
}
@@ -184,7 +184,7 @@ private void logoutUser(RocketChatCredentials user) {
private HttpHeaders getStandardHttpHeaders(String rcToken, String rcUserId) {
HttpHeaders httpHeaders = new HttpHeaders();
- httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
+ httpHeaders.setContentType(MediaType.APPLICATION_JSON);
httpHeaders.add(rocketChatHeaderAuthToken, rcToken);
httpHeaders.add(rocketChatHeaderUserId, rcUserId);
return httpHeaders;
diff --git a/src/main/java/de/caritas/cob/messageservice/api/service/helper/ServiceHelper.java b/src/main/java/de/caritas/cob/messageservice/api/service/helper/ServiceHelper.java
index 947daac..91a4745 100644
--- a/src/main/java/de/caritas/cob/messageservice/api/service/helper/ServiceHelper.java
+++ b/src/main/java/de/caritas/cob/messageservice/api/service/helper/ServiceHelper.java
@@ -57,7 +57,7 @@ private void addAuthorizationHeader(HttpHeaders headers, String accessToken) {
private HttpHeaders addCsrfHeaders(HttpHeaders httpHeaders) {
String csrfToken = UUID.randomUUID().toString();
- httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
+ httpHeaders.setContentType(MediaType.APPLICATION_JSON);
httpHeaders.add("Cookie", csrfCookieProperty + "=" + csrfToken);
httpHeaders.add(csrfHeaderProperty, csrfToken);
diff --git a/src/main/java/de/caritas/cob/messageservice/api/service/statistics/StatisticsService.java b/src/main/java/de/caritas/cob/messageservice/api/service/statistics/StatisticsService.java
index 5957aa2..884a6bb 100644
--- a/src/main/java/de/caritas/cob/messageservice/api/service/statistics/StatisticsService.java
+++ b/src/main/java/de/caritas/cob/messageservice/api/service/statistics/StatisticsService.java
@@ -46,8 +46,7 @@ public void fireEvent(StatisticsEvent statisticsEvent) {
.build()),
() ->
LogService.logStatisticsEventWarning(
- String.format(
- "Empty statistics event message payload for type %s received",
+ "Empty statistics event message payload for type %s received".formatted(
statisticsEvent.getClass().getSimpleName())));
}
}
diff --git a/src/main/java/de/caritas/cob/messageservice/config/SecurityConfig.java b/src/main/java/de/caritas/cob/messageservice/config/SecurityConfig.java
index 337cedb..933b71f 100644
--- a/src/main/java/de/caritas/cob/messageservice/config/SecurityConfig.java
+++ b/src/main/java/de/caritas/cob/messageservice/config/SecurityConfig.java
@@ -6,31 +6,19 @@
import static de.caritas.cob.messageservice.api.authorization.Authority.AuthorityValue.USER_DEFAULT;
import static de.caritas.cob.messageservice.api.authorization.Authority.AuthorityValue.USE_FEEDBACK;
-import de.caritas.cob.messageservice.api.authorization.RoleAuthorizationAuthorityMapper;
import de.caritas.cob.messageservice.config.security.AuthorisationService;
import de.caritas.cob.messageservice.config.security.JwtAuthConverter;
import de.caritas.cob.messageservice.config.security.JwtAuthConverterProperties;
import de.caritas.cob.messageservice.filter.StatelessCsrfFilter;
-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;
-import org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticatedActionsFilter;
-import org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticationProcessingFilter;
-import org.keycloak.adapters.springsecurity.filter.KeycloakPreAuthActionsFilter;
-import org.keycloak.adapters.springsecurity.filter.KeycloakSecurityContextRequestFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
-import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
-import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
-import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;
-import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@@ -38,6 +26,7 @@
/**
* Provides the Keycloak/Spring Security configuration.
*/
+@Configuration
@KeycloakConfiguration
public class SecurityConfig implements WebMvcConfigurer {
@@ -74,13 +63,12 @@ public SecurityFilterChain configure(HttpSecurity http) throws Exception {
@SuppressWarnings("java:S1075") // URIs should not be hardcoded
final var SINGLE_MESSAGE_PATH = "/messages/{messageId:[0-9A-Za-z]{17}}";
- var httpSecurity = http.csrf().disable()
+ var httpSecurity = http.csrf(csrf -> csrf.disable())
.addFilterBefore(new StatelessCsrfFilter(csrfCookieProperty, csrfHeaderProperty, csrfWhitelistHeaderProperty),
CsrfFilter.class);
- httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
- .and().authorizeRequests()
+ httpSecurity.sessionManagement(management -> management.sessionCreationPolicy(SessionCreationPolicy.STATELESS)).authorizeHttpRequests(requests -> requests
.requestMatchers(SecurityConfig.WHITE_LIST).permitAll()
.requestMatchers("/messages/key")
.hasAuthority(TECHNICAL_DEFAULT)
@@ -101,9 +89,9 @@ public SecurityFilterChain configure(HttpSecurity http) throws Exception {
.requestMatchers("/messages/aliasWithContent/new")
.hasAnyAuthority(USER_DEFAULT, CONSULTANT_DEFAULT, TECHNICAL_DEFAULT)
.anyRequest()
- .denyAll();
+ .denyAll());
- httpSecurity.oauth2ResourceServer().jwt().jwtAuthenticationConverter(jwtAuthConverter());
+ httpSecurity.oauth2ResourceServer(server -> server.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthConverter())));
return httpSecurity.build();
}
diff --git a/src/main/java/de/caritas/cob/messageservice/config/apiclient/TenantServiceApiClient.java b/src/main/java/de/caritas/cob/messageservice/config/apiclient/TenantServiceApiClient.java
index c954211..f0cb371 100644
--- a/src/main/java/de/caritas/cob/messageservice/config/apiclient/TenantServiceApiClient.java
+++ b/src/main/java/de/caritas/cob/messageservice/config/apiclient/TenantServiceApiClient.java
@@ -10,7 +10,7 @@
import java.beans.PropertyDescriptor;
import java.util.Arrays;
import java.util.Collection;
-import javax.ws.rs.InternalServerErrorException;
+import jakarta.ws.rs.InternalServerErrorException;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
@@ -63,7 +63,7 @@ private MultiValueMap obtainQueryParameters(Object queryValue) {
} catch (IntrospectionException exception) {
throw new InternalServerErrorException(
- String.format("Could not obtain method properties of %s", queryValue.toString()),
+ "Could not obtain method properties of %s".formatted(queryValue.toString()),
exception);
}
}
@@ -77,7 +77,7 @@ private void setMethodKeyValuePairs(Object queryValue, MultiValueMap obtainQueryParameters(Object queryValue) {
} catch (IntrospectionException exception) {
throw new InternalServerErrorException(
- String.format("Could not obtain method properties of %s", queryValue),
+ "Could not obtain method properties of %s".formatted(queryValue),
exception);
}
}
@@ -80,7 +80,7 @@ private void setMethodKeyValuePairs(Object queryValue, MultiValueMap:/messageservice
spring.datasource.username=
spring.datasource.password=
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
-spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MariaDB103Dialect
+spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MariaDBDialect
spring.liquibase.change-log=classpath:db/changelog/messageservice-local-master.xml
spring.liquibase.user=
spring.liquibase.password=
@@ -100,10 +100,10 @@ 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
spring.security.oauth2.resourceserver.jwt.issuer-uri: https://localhost/auth/realms/onlineberatung
spring.security.oauth2.resourceserver.jwt.jwk-set-uri: https://localhost/auth/realms/onlineberatung/protocol/openid-connect/certs
spring.jwt.auth.converter.resource-id: app
spring.jwt.auth.converter.principal-attribute: preferred_username
-springdoc.api-docs.enabled=false
\ No newline at end of file
+springdoc.api-docs.enabled=false
diff --git a/src/test/java/de/caritas/cob/messageservice/AuthenticatedUserConfigTest.java b/src/test/java/de/caritas/cob/messageservice/AuthenticatedUserConfigTest.java
index 874887e..a8803d0 100644
--- a/src/test/java/de/caritas/cob/messageservice/AuthenticatedUserConfigTest.java
+++ b/src/test/java/de/caritas/cob/messageservice/AuthenticatedUserConfigTest.java
@@ -1,21 +1,21 @@
package de.caritas.cob.messageservice;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
import de.caritas.cob.messageservice.config.AuthenticatedUserConfig;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.mock.mockito.MockBean;
-import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
-@RunWith(SpringRunner.class)
-public class AuthenticatedUserConfigTest {
+@ExtendWith(SpringExtension.class)
+class AuthenticatedUserConfigTest {
@MockBean
AuthenticatedUserConfig authenticatedUserConfig;
@Test
- public void getAuthenticatedUser_Should_ReturnNullWhenNoUserSessionActive() {
+ void getAuthenticatedUser_Should_ReturnNullWhenNoUserSessionActive() {
assertNull(authenticatedUserConfig.getAuthenticatedUser());
}
}
diff --git a/src/test/java/de/caritas/cob/messageservice/MessengerTest.java b/src/test/java/de/caritas/cob/messageservice/MessengerTest.java
index 9761d1d..8c870db 100644
--- a/src/test/java/de/caritas/cob/messageservice/MessengerTest.java
+++ b/src/test/java/de/caritas/cob/messageservice/MessengerTest.java
@@ -7,6 +7,7 @@
import static de.caritas.cob.messageservice.testhelper.TestConstants.createSuccessfulMessageResult;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.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.ArgumentMatchers.eq;
@@ -43,19 +44,19 @@
import java.util.Optional;
import org.apache.commons.collections4.SetUtils;
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.Mockito;
import org.mockito.Spy;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.util.ReflectionTestUtils;
-@RunWith(MockitoJUnitRunner.class)
-public class MessengerTest {
+@ExtendWith(MockitoExtension.class)
+class MessengerTest {
private static final String RC_TOKEN = "r94qMDk8gtgVNzqCq9zD2hELK-eXGB5VHlUVBgE8a8f";
private static final String RC_USER_ID = "pptLwARyTMzbTTRdg";
@@ -97,77 +98,81 @@ public class MessengerTest {
private MessageMapper mapper = new MessageMapper(new ObjectMapper(), null);
- @Before
- public void setup() {
+ @BeforeEach
+ void setup() {
setField(this.messenger, "rocketChatSystemUserId", RC_SYSTEM_USER_ID);
- when(authenticatedUser.getRoles())
+ Mockito.lenient().when(authenticatedUser.getRoles())
.thenReturn(SetUtils.unmodifiableSet(Role.CONSULTANT.getRoleName()));
- when(authenticatedUser.getUserId())
+ Mockito.lenient().when(authenticatedUser.getUserId())
.thenReturn(CONSULTANT_ID);
}
/**
* Tests for method: postGroupMessage
*/
- @Test(expected = InternalServerErrorException.class)
- public void postGroupMessage_Should_ReturnInternalServerErrorAndNotSendNotification_When_RocketChatPostMessageFails()
- throws CustomCryptoException {
+ @Test
+ void postGroupMessage_Should_ReturnInternalServerErrorAndNotSendNotification_When_RocketChatPostMessageFails() {
+ assertThrows(InternalServerErrorException.class, () -> {
- RocketChatSendMessageException rocketChatSendMessageException =
- new RocketChatSendMessageException(new Exception());
+ RocketChatSendMessageException rocketChatSendMessageException =
+ new RocketChatSendMessageException(new Exception());
- var groupMessage = createGroupMessage().build();
- when(rocketChatService.postGroupMessage(groupMessage)).thenThrow(
- rocketChatSendMessageException);
+ var groupMessage = createGroupMessage().build();
+ when(rocketChatService.postGroupMessage(groupMessage)).thenThrow(
+ rocketChatSendMessageException);
- messenger.postGroupMessage(groupMessage);
+ messenger.postGroupMessage(groupMessage);
- verify(emailNotificationFacade, times(0)).sendEmailAboutNewChatMessage(RC_GROUP_ID,
- Optional.empty(), null);
+ verify(emailNotificationFacade, times(0)).sendEmailAboutNewChatMessage(RC_GROUP_ID,
+ Optional.empty(), null);
+ });
}
- @Test(expected = InternalServerErrorException.class)
- public void postGroupMessage_Should_ReturnInternalServerErrorAndNotSendNotification_When_RocketChatServiceReturnsEmptyDTO()
- throws CustomCryptoException {
+ @Test
+ void postGroupMessage_Should_ReturnInternalServerErrorAndNotSendNotification_When_RocketChatServiceReturnsEmptyDTO() {
+ assertThrows(InternalServerErrorException.class, () -> {
- var groupMessage = createGroupMessage().build();
- when(rocketChatService.postGroupMessage(groupMessage)).thenReturn(null);
+ var groupMessage = createGroupMessage().build();
+ when(rocketChatService.postGroupMessage(groupMessage)).thenReturn(null);
- messenger.postGroupMessage(groupMessage);
+ messenger.postGroupMessage(groupMessage);
- verify(emailNotificationFacade, times(0)).sendEmailAboutNewChatMessage(RC_GROUP_ID,
- Optional.empty(), null);
+ verify(emailNotificationFacade, times(0)).sendEmailAboutNewChatMessage(RC_GROUP_ID,
+ Optional.empty(), null);
+ });
}
- @Test(expected = InternalServerErrorException.class)
- public void postGroupMessage_Should_ReturnInternalServerErrorAndNotSendNotification_When_RocketChatServiceReturnsUnsuccessful()
- throws CustomCryptoException {
+ @Test
+ void postGroupMessage_Should_ReturnInternalServerErrorAndNotSendNotification_When_RocketChatServiceReturnsUnsuccessful() {
+ assertThrows(InternalServerErrorException.class, () -> {
- var groupMessage = createGroupMessage().build();
- when(rocketChatService.postGroupMessage(groupMessage)).thenReturn(
- POST_MESSAGE_RESPONSE_DTO_UNSUCCESSFUL);
+ var groupMessage = createGroupMessage().build();
+ when(rocketChatService.postGroupMessage(groupMessage)).thenReturn(
+ POST_MESSAGE_RESPONSE_DTO_UNSUCCESSFUL);
- messenger.postGroupMessage(groupMessage);
+ messenger.postGroupMessage(groupMessage);
- verify(emailNotificationFacade, times(0)).sendEmailAboutNewChatMessage(RC_GROUP_ID,
- Optional.empty(), null);
+ verify(emailNotificationFacade, times(0)).sendEmailAboutNewChatMessage(RC_GROUP_ID,
+ Optional.empty(), null);
+ });
}
- @Test(expected = InternalServerErrorException.class)
- public void postGroupMessage_Should_ReturnRocketChatPostMarkGroupAsReadExceptionAndNotSendNotification_When_RocketChatMarkGroupAsReadFails()
- throws CustomCryptoException {
+ @Test
+ void postGroupMessage_Should_ReturnRocketChatPostMarkGroupAsReadExceptionAndNotSendNotification_When_RocketChatMarkGroupAsReadFails() {
+ assertThrows(InternalServerErrorException.class, () -> {
- var groupMessage = createGroupMessage().build();
- when(rocketChatService.postGroupMessage(groupMessage)).thenReturn(null);
+ var groupMessage = createGroupMessage().build();
+ when(rocketChatService.postGroupMessage(groupMessage)).thenReturn(null);
- messenger.postGroupMessage(groupMessage);
+ messenger.postGroupMessage(groupMessage);
- verify(emailNotificationFacade, times(0)).sendEmailAboutNewChatMessage(RC_GROUP_ID,
- Optional.empty(), null);
+ verify(emailNotificationFacade, times(0)).sendEmailAboutNewChatMessage(RC_GROUP_ID,
+ Optional.empty(), null);
+ });
}
@Test
- public void postGroupMessage_Should_ReturnCreatedAndSendNotification_When_MessageWasSentAndNotificationIsSetToTrue()
+ void postGroupMessage_Should_ReturnCreatedAndSendNotification_When_MessageWasSentAndNotificationIsSetToTrue()
throws CustomCryptoException {
var groupMessage = createGroupMessage().sendNotification(SEND_NOTIFICATION).build();
@@ -180,7 +185,7 @@ public void postGroupMessage_Should_ReturnCreatedAndSendNotification_When_Messag
}
@Test
- public void postGroupMessage_Should_ReturnCreatedAndNotSendNotification_When_MessageWasSentAndNotificationIsSetToFalse()
+ void postGroupMessage_Should_ReturnCreatedAndNotSendNotification_When_MessageWasSentAndNotificationIsSetToFalse()
throws CustomCryptoException {
var groupMessage = createGroupMessage().build();
@@ -195,75 +200,79 @@ public void postGroupMessage_Should_ReturnCreatedAndNotSendNotification_When_Mes
/**
* Tests for method: postFeedbackGroupMessage
*/
- @Test(expected = InternalServerErrorException.class)
- public void postFeedbackGroupMessage_Should_ReturnInternalServerErrorAndNotSendNotification_When_RocketChatPostMessageFails()
- throws CustomCryptoException {
+ @Test
+ void postFeedbackGroupMessage_Should_ReturnInternalServerErrorAndNotSendNotification_When_RocketChatPostMessageFails() {
+ assertThrows(InternalServerErrorException.class, () -> {
- RocketChatSendMessageException rocketChatSendMessageException =
- new RocketChatSendMessageException(new Exception());
+ RocketChatSendMessageException rocketChatSendMessageException =
+ new RocketChatSendMessageException(new Exception());
- when(rocketChatService.getGroupInfo(RC_TOKEN, RC_USER_ID, RC_FEEDBACK_GROUP_ID))
- .thenReturn(GET_GROUP_INFO_DTO_FEEDBACK_CHAT);
- var feedbackGroupMessage = createFeedbackGroupMessage().build();
- when(rocketChatService.postGroupMessage(feedbackGroupMessage)).thenThrow(
- rocketChatSendMessageException);
+ when(rocketChatService.getGroupInfo(RC_TOKEN, RC_USER_ID, RC_FEEDBACK_GROUP_ID))
+ .thenReturn(GET_GROUP_INFO_DTO_FEEDBACK_CHAT);
+ var feedbackGroupMessage = createFeedbackGroupMessage().build();
+ when(rocketChatService.postGroupMessage(feedbackGroupMessage)).thenThrow(
+ rocketChatSendMessageException);
- messenger.postFeedbackGroupMessage(feedbackGroupMessage);
+ messenger.postFeedbackGroupMessage(feedbackGroupMessage);
- verify(emailNotificationFacade, times(0)).sendEmailAboutNewChatMessage(RC_GROUP_ID,
- Optional.empty(), null);
+ verify(emailNotificationFacade, times(0)).sendEmailAboutNewChatMessage(RC_GROUP_ID,
+ Optional.empty(), null);
+ });
}
- @Test(expected = InternalServerErrorException.class)
- public void postFeedbackGroupMessage_Should_ReturnInternalServerErrorAndNotSendFeedbackNotification_When_RocketChatServiceReturnsEmptyDTO()
- throws CustomCryptoException {
+ @Test
+ void postFeedbackGroupMessage_Should_ReturnInternalServerErrorAndNotSendFeedbackNotification_When_RocketChatServiceReturnsEmptyDTO() {
+ assertThrows(InternalServerErrorException.class, () -> {
- when(rocketChatService.getGroupInfo(RC_TOKEN, RC_USER_ID, RC_FEEDBACK_GROUP_ID))
- .thenReturn(GET_GROUP_INFO_DTO_FEEDBACK_CHAT);
- var feedbackGroupMessage = createFeedbackGroupMessage().build();
- when(rocketChatService.postGroupMessage(feedbackGroupMessage))
- .thenReturn(null);
+ when(rocketChatService.getGroupInfo(RC_TOKEN, RC_USER_ID, RC_FEEDBACK_GROUP_ID))
+ .thenReturn(GET_GROUP_INFO_DTO_FEEDBACK_CHAT);
+ var feedbackGroupMessage = createFeedbackGroupMessage().build();
+ when(rocketChatService.postGroupMessage(feedbackGroupMessage))
+ .thenReturn(null);
- messenger.postFeedbackGroupMessage(feedbackGroupMessage);
+ messenger.postFeedbackGroupMessage(feedbackGroupMessage);
- verify(emailNotificationFacade, times(0)).sendEmailAboutNewFeedbackMessage(
- RC_FEEDBACK_GROUP_ID, any(), anyString());
+ verify(emailNotificationFacade, times(0)).sendEmailAboutNewFeedbackMessage(
+ RC_FEEDBACK_GROUP_ID, any(), anyString());
+ });
}
- @Test(expected = InternalServerErrorException.class)
- public void postFeedbackGroupMessage_Should_ReturnInternalServerErrorAndNotSendNotification_When_RocketChatServiceReturnsUnsuccessful()
- throws CustomCryptoException {
+ @Test
+ void postFeedbackGroupMessage_Should_ReturnInternalServerErrorAndNotSendNotification_When_RocketChatServiceReturnsUnsuccessful() {
+ assertThrows(InternalServerErrorException.class, () -> {
- when(rocketChatService.getGroupInfo(RC_TOKEN, RC_USER_ID, RC_FEEDBACK_GROUP_ID))
- .thenReturn(GET_GROUP_INFO_DTO_FEEDBACK_CHAT);
- var groupMessage = createGroupMessage().build();
- when(rocketChatService.postGroupMessage(groupMessage)).thenReturn(
- POST_MESSAGE_RESPONSE_DTO_UNSUCCESSFUL);
- var feedbackGroupMessage = createFeedbackGroupMessage().build();
+ when(rocketChatService.getGroupInfo(RC_TOKEN, RC_USER_ID, RC_FEEDBACK_GROUP_ID))
+ .thenReturn(GET_GROUP_INFO_DTO_FEEDBACK_CHAT);
+ var groupMessage = createGroupMessage().build();
+ when(rocketChatService.postGroupMessage(groupMessage)).thenReturn(
+ POST_MESSAGE_RESPONSE_DTO_UNSUCCESSFUL);
+ var feedbackGroupMessage = createFeedbackGroupMessage().build();
- messenger.postFeedbackGroupMessage(feedbackGroupMessage);
+ messenger.postFeedbackGroupMessage(feedbackGroupMessage);
- verify(emailNotificationFacade, times(0)).sendEmailAboutNewChatMessage(RC_FEEDBACK_GROUP_ID,
- Optional.empty(), null);
+ verify(emailNotificationFacade, times(0)).sendEmailAboutNewChatMessage(RC_FEEDBACK_GROUP_ID,
+ Optional.empty(), null);
+ });
}
- @Test(expected = InternalServerErrorException.class)
- public void postFeedbackGroupMessage_Should_ReturnRocketChatPostMarkGroupAsReadExceptionAndNotSendFeedbackNotification_When_RocketChatMarkGroupAsReadFails()
- throws CustomCryptoException {
+ @Test
+ void postFeedbackGroupMessage_Should_ReturnRocketChatPostMarkGroupAsReadExceptionAndNotSendFeedbackNotification_When_RocketChatMarkGroupAsReadFails() {
+ assertThrows(InternalServerErrorException.class, () -> {
- when(rocketChatService.getGroupInfo(RC_TOKEN, RC_USER_ID, RC_FEEDBACK_GROUP_ID))
- .thenReturn(GET_GROUP_INFO_DTO_FEEDBACK_CHAT);
- var feedbackGroupMessage = createFeedbackGroupMessage().build();
- when(rocketChatService.postGroupMessage(feedbackGroupMessage)).thenReturn(null);
+ when(rocketChatService.getGroupInfo(RC_TOKEN, RC_USER_ID, RC_FEEDBACK_GROUP_ID))
+ .thenReturn(GET_GROUP_INFO_DTO_FEEDBACK_CHAT);
+ var feedbackGroupMessage = createFeedbackGroupMessage().build();
+ when(rocketChatService.postGroupMessage(feedbackGroupMessage)).thenReturn(null);
- messenger.postFeedbackGroupMessage(feedbackGroupMessage);
+ messenger.postFeedbackGroupMessage(feedbackGroupMessage);
- verify(emailNotificationFacade, times(0)).sendEmailAboutNewFeedbackMessage(
- RC_FEEDBACK_GROUP_ID, any(), anyString());
+ verify(emailNotificationFacade, times(0)).sendEmailAboutNewFeedbackMessage(
+ RC_FEEDBACK_GROUP_ID, any(), anyString());
+ });
}
@Test
- public void postFeedbackGroupMessage_Should_ReturnCreatedAndSendFeedbackNotification_When_RocketChatServiceSucceeds()
+ void postFeedbackGroupMessage_Should_ReturnCreatedAndSendFeedbackNotification_When_RocketChatServiceSucceeds()
throws CustomCryptoException {
when(rocketChatService.getGroupInfo(RC_TOKEN, RC_USER_ID, RC_FEEDBACK_GROUP_ID))
@@ -279,20 +288,22 @@ public void postFeedbackGroupMessage_Should_ReturnCreatedAndSendFeedbackNotifica
eq(RC_FEEDBACK_GROUP_ID), any(), any());
}
- @Test(expected = BadRequestException.class)
- public void postFeedbackGroupMessage_Should_ReturnBadRequestAndNotSendFeedbackNotification_When_GroupIdIsNoFeedbackChat() {
- when(rocketChatService.getGroupInfo(RC_TOKEN, RC_USER_ID, RC_GROUP_ID))
- .thenReturn(GET_GROUP_INFO_DTO);
- var groupMessage = createGroupMessage().build();
+ @Test
+ void postFeedbackGroupMessage_Should_ReturnBadRequestAndNotSendFeedbackNotification_When_GroupIdIsNoFeedbackChat() {
+ assertThrows(BadRequestException.class, () -> {
+ when(rocketChatService.getGroupInfo(RC_TOKEN, RC_USER_ID, RC_GROUP_ID))
+ .thenReturn(GET_GROUP_INFO_DTO);
+ var groupMessage = createGroupMessage().build();
- messenger.postFeedbackGroupMessage(groupMessage);
+ messenger.postFeedbackGroupMessage(groupMessage);
- verify(emailNotificationFacade, times(0)).sendEmailAboutNewFeedbackMessage(RC_GROUP_ID, any(),
- anyString());
+ verify(emailNotificationFacade, times(0)).sendEmailAboutNewFeedbackMessage(RC_GROUP_ID, any(),
+ anyString());
+ });
}
@Test
- public void postGroupMessage_Should_sendLiveNotification_When_RocketChatServiceSucceeds()
+ void postGroupMessage_Should_sendLiveNotification_When_RocketChatServiceSucceeds()
throws CustomCryptoException {
var groupMessage = createGroupMessage().build();
@@ -306,7 +317,7 @@ public void postGroupMessage_Should_sendLiveNotification_When_RocketChatServiceS
}
@Test
- public void postFeedbackGroupMessage_Should_sendLiveNotification_When_RocketChatServiceSucceeds()
+ void postFeedbackGroupMessage_Should_sendLiveNotification_When_RocketChatServiceSucceeds()
throws CustomCryptoException {
when(rocketChatService.getGroupInfo(RC_TOKEN, RC_USER_ID, RC_FEEDBACK_GROUP_ID))
@@ -321,7 +332,7 @@ public void postFeedbackGroupMessage_Should_sendLiveNotification_When_RocketChat
}
@Test
- public void postGroupMessage_Should_notSendLiveNotification_When_userIsRocketChatSystemUser()
+ void postGroupMessage_Should_notSendLiveNotification_When_userIsRocketChatSystemUser()
throws CustomCryptoException {
var systemFeedbackMessage = createFeedbackGroupMessage().rcUserId(RC_SYSTEM_USER_ID).build();
@@ -334,7 +345,7 @@ public void postGroupMessage_Should_notSendLiveNotification_When_userIsRocketCha
}
@Test
- public void postGroupMessage_Should_deleteDraftMessage_When_RocketChatServiceSucceeds()
+ void postGroupMessage_Should_deleteDraftMessage_When_RocketChatServiceSucceeds()
throws CustomCryptoException {
var groupMessage = createGroupMessage().build();
@@ -347,7 +358,7 @@ public void postGroupMessage_Should_deleteDraftMessage_When_RocketChatServiceSuc
}
@Test
- public void postGroupMessage_Should_FireCreateMessageStatisticsEvent()
+ void postGroupMessage_Should_FireCreateMessageStatisticsEvent()
throws CustomCryptoException {
var groupMessage = createGroupMessage().build();
@@ -377,7 +388,7 @@ public void postGroupMessage_Should_FireCreateMessageStatisticsEvent()
}
@Test
- public void postFeedbackGroupMessage_Should_deleteDraftMessage_When_RocketChatServiceSucceeds()
+ void postFeedbackGroupMessage_Should_deleteDraftMessage_When_RocketChatServiceSucceeds()
throws CustomCryptoException {
when(rocketChatService.getGroupInfo(RC_TOKEN, RC_USER_ID, RC_FEEDBACK_GROUP_ID))
@@ -392,7 +403,7 @@ public void postFeedbackGroupMessage_Should_deleteDraftMessage_When_RocketChatSe
}
@Test
- public void createVideoHintMessage_Should_triggerRocketChatPost_When_paramsAreGiven() {
+ void createVideoHintMessage_Should_triggerRocketChatPost_When_paramsAreGiven() {
VideoCallMessageDTO callMessageDTO = new EasyRandom().nextObject(VideoCallMessageDTO.class);
AliasMessageDTO aliasMessageDTO = new AliasMessageDTO().videoCallMessageDTO(callMessageDTO);
when(rocketChatService.postAliasOnlyMessageAsSystemUser("rcGroupId",
@@ -405,7 +416,7 @@ public void createVideoHintMessage_Should_triggerRocketChatPost_When_paramsAreGi
}
@Test
- public void postAliasOnlyMessage_Should_triggerRocketChatPostWithCorrectMessageType_When_RcGroupIdIsGiven() {
+ void postAliasOnlyMessage_Should_triggerRocketChatPostWithCorrectMessageType_When_RcGroupIdIsGiven() {
var aliasMessageDTO = new AliasMessageDTO().messageType(MessageType.FURTHER_STEPS);
when(rocketChatService.postAliasOnlyMessageAsSystemUser(RC_GROUP_ID, aliasMessageDTO, null))
.thenReturn(createSuccessfulMessageResult(null, RC_GROUP_ID));
@@ -419,7 +430,7 @@ public void postAliasOnlyMessage_Should_triggerRocketChatPostWithCorrectMessageT
}
@Test
- public void createEvent_Should_sendNewMessageMail_When_messageTypeIsMasterkeyLost() {
+ void createEvent_Should_sendNewMessageMail_When_messageTypeIsMasterkeyLost() {
var aliasMessageDTO = new AliasMessageDTO().messageType(MessageType.MASTER_KEY_LOST);
when(rocketChatService.postAliasOnlyMessageAsSystemUser(RC_GROUP_ID, aliasMessageDTO, null))
.thenReturn(createSuccessfulMessageResult(null, RC_GROUP_ID));
diff --git a/src/test/java/de/caritas/cob/messageservice/api/authorization/AuthorityTest.java b/src/test/java/de/caritas/cob/messageservice/api/authorization/AuthorityTest.java
index b7ce41f..1e1730b 100644
--- a/src/test/java/de/caritas/cob/messageservice/api/authorization/AuthorityTest.java
+++ b/src/test/java/de/caritas/cob/messageservice/api/authorization/AuthorityTest.java
@@ -1,20 +1,20 @@
package de.caritas.cob.messageservice.api.authorization;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import de.caritas.cob.messageservice.api.authorization.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)
-public class AuthorityTest {
+@ExtendWith(MockitoExtension.class)
+class AuthorityTest {
@Test
- public void getAuthoritiesByRoleName_Should_ReturnCorrectRoles_ForKeycloakRoleConsultant() {
+ void getAuthoritiesByRoleName_Should_ReturnCorrectRoles_ForKeycloakRoleConsultant() {
List result = Authority.getAuthoritiesByUserRole(Role.CONSULTANT);
@@ -25,7 +25,7 @@ public void getAuthoritiesByRoleName_Should_ReturnCorrectRoles_ForKeycloakRoleCo
}
@Test
- public void getAuthoritiesByRoleName_Should_ReturnCorrectRoles_ForKeycloakRolePeerConsultant() {
+ void getAuthoritiesByRoleName_Should_ReturnCorrectRoles_ForKeycloakRolePeerConsultant() {
List result = Authority.getAuthoritiesByUserRole(Role.PEER_CONSULTANT);
@@ -36,7 +36,7 @@ public void getAuthoritiesByRoleName_Should_ReturnCorrectRoles_ForKeycloakRolePe
}
@Test
- public void getAuthoritiesByRoleName_Should_ReturnCorrectRoles_ForKeycloakRoleUser() {
+ void getAuthoritiesByRoleName_Should_ReturnCorrectRoles_ForKeycloakRoleUser() {
List result = Authority.getAuthoritiesByUserRole(Role.USER);
@@ -47,7 +47,7 @@ public void getAuthoritiesByRoleName_Should_ReturnCorrectRoles_ForKeycloakRoleUs
}
@Test
- public void getAuthoritiesByRoleName_Should_ReturnCorrectRoles_ForKeycloakRoleTechnical() {
+ void getAuthoritiesByRoleName_Should_ReturnCorrectRoles_ForKeycloakRoleTechnical() {
List result = Authority.getAuthoritiesByUserRole(Role.TECHNICAL);
diff --git a/src/test/java/de/caritas/cob/messageservice/api/authorization/RoleAuthorizationAuthorityMapperTest.java b/src/test/java/de/caritas/cob/messageservice/api/authorization/RoleAuthorizationAuthorityMapperTest.java
index d82cb79..8adb553 100644
--- a/src/test/java/de/caritas/cob/messageservice/api/authorization/RoleAuthorizationAuthorityMapperTest.java
+++ b/src/test/java/de/caritas/cob/messageservice/api/authorization/RoleAuthorizationAuthorityMapperTest.java
@@ -7,17 +7,17 @@
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
-public class RoleAuthorizationAuthorityMapperTest {
+class RoleAuthorizationAuthorityMapperTest {
private final RoleAuthorizationAuthorityMapper roleAuthorizationAuthorityMapper =
new RoleAuthorizationAuthorityMapper();
@Test
- public void mapAuthorities_Should_returnGrantedConsultantAuthority_When_authorityConsultant() {
+ void mapAuthorities_Should_returnGrantedConsultantAuthority_When_authorityConsultant() {
List grantedAuthorities = Stream.of("consultant")
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
@@ -32,7 +32,7 @@ public void mapAuthorities_Should_returnGrantedConsultantAuthority_When_authorit
}
@Test
- public void mapAuthorities_Should_returnGrantedTechnicalAuthority_When_authoritiesContainsTechnical() {
+ void mapAuthorities_Should_returnGrantedTechnicalAuthority_When_authoritiesContainsTechnical() {
List grantedAuthorities = Stream.of("a", "v", "technical", "c")
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
@@ -48,7 +48,7 @@ public void mapAuthorities_Should_returnGrantedTechnicalAuthority_When_authoriti
}
@Test
- public void mapAuthorities_Should_returnEmptyCollection_When_authorityIsEmpty() {
+ void mapAuthorities_Should_returnEmptyCollection_When_authorityIsEmpty() {
Collection extends GrantedAuthority> mappedAuthorities = this.roleAuthorizationAuthorityMapper
.mapAuthorities(emptyList());
@@ -56,7 +56,7 @@ public void mapAuthorities_Should_returnEmptyCollection_When_authorityIsEmpty()
}
@Test
- public void mapAuthorities_Should_returnEmptyCollection_When_authoritiesAreNotProvided() {
+ void mapAuthorities_Should_returnEmptyCollection_When_authoritiesAreNotProvided() {
List grantedAuthorities = Stream.of("a", "v", "b", "c")
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
diff --git a/src/test/java/de/caritas/cob/messageservice/api/controller/ActuatorControllerIT.java b/src/test/java/de/caritas/cob/messageservice/api/controller/ActuatorControllerIT.java
index 8d1b1d4..302f858 100644
--- a/src/test/java/de/caritas/cob/messageservice/api/controller/ActuatorControllerIT.java
+++ b/src/test/java/de/caritas/cob/messageservice/api/controller/ActuatorControllerIT.java
@@ -1,6 +1,6 @@
package de.caritas.cob.messageservice.api.controller;
-import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
+import static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;
import static org.hamcrest.Matchers.is;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
diff --git a/src/test/java/de/caritas/cob/messageservice/api/controller/MessageControllerAuthorizationTestIT.java b/src/test/java/de/caritas/cob/messageservice/api/controller/MessageControllerAuthorizationTestIT.java
index 88774f4..72c1550 100644
--- a/src/test/java/de/caritas/cob/messageservice/api/controller/MessageControllerAuthorizationTestIT.java
+++ b/src/test/java/de/caritas/cob/messageservice/api/controller/MessageControllerAuthorizationTestIT.java
@@ -27,9 +27,8 @@
import jakarta.servlet.http.Cookie;
import org.apache.commons.lang3.RandomStringUtils;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
@@ -37,14 +36,12 @@
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;
-@RunWith(SpringRunner.class)
@ActiveProfiles("testing")
@SpringBootTest
@AutoConfigureMockMvc
-public class MessageControllerAuthorizationTestIT {
+class MessageControllerAuthorizationTestIT {
protected final static String PATH_GET_MESSAGE_STREAM = "/messages";
protected final static String PATH_POST_CREATE_MESSAGE = "/messages/new";
@@ -75,15 +72,15 @@ public class MessageControllerAuthorizationTestIT {
private String messageId;
private AliasArgs aliasArgs;
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
csrfCookie = new Cookie(CSRF_COOKIE, CSRF_VALUE);
messageId = null;
aliasArgs = null;
}
@Test
- public void findMessages_Should_ReturnUnauthorizedAndCallNoMethods_WhenNoKeycloakAuthorization()
+ void findMessages_Should_ReturnUnauthorizedAndCallNoMethods_WhenNoKeycloakAuthorization()
throws Exception {
mvc.perform(get(PATH_GET_MESSAGE_STREAM).cookie(csrfCookie).header(CSRF_HEADER, CSRF_VALUE)
@@ -95,7 +92,7 @@ public void findMessages_Should_ReturnUnauthorizedAndCallNoMethods_WhenNoKeycloa
@Test
@WithMockUser(authorities = {AuthorityValue.TECHNICAL_DEFAULT})
- public void findMessages_Should_ReturnForbiddenAndCallNoMethods_WhenNoUserOrConsultantDefaultAuthority()
+ void findMessages_Should_ReturnForbiddenAndCallNoMethods_WhenNoUserOrConsultantDefaultAuthority()
throws Exception {
mvc.perform(get(PATH_GET_MESSAGE_STREAM).cookie(csrfCookie).header(CSRF_HEADER, CSRF_VALUE)
@@ -107,7 +104,7 @@ public void findMessages_Should_ReturnForbiddenAndCallNoMethods_WhenNoUserOrCons
@Test
@WithMockUser(authorities = {AuthorityValue.CONSULTANT_DEFAULT, AuthorityValue.USER_DEFAULT})
- public void findMessages_Should_ReturnForbiddenAndCallNoMethods_WhenNoCsrfTokens()
+ void findMessages_Should_ReturnForbiddenAndCallNoMethods_WhenNoCsrfTokens()
throws Exception {
mvc.perform(get(PATH_GET_MESSAGE_STREAM).contentType(MediaType.APPLICATION_JSON)
@@ -117,7 +114,7 @@ public void findMessages_Should_ReturnForbiddenAndCallNoMethods_WhenNoCsrfTokens
}
@Test
- public void createMessage_Should_ReturnUnauthorizedAndCallNoMethods_WhenNoKeycloakAuthorization()
+ void createMessage_Should_ReturnUnauthorizedAndCallNoMethods_WhenNoKeycloakAuthorization()
throws Exception {
mvc.perform(post(PATH_POST_CREATE_MESSAGE).cookie(csrfCookie).header(CSRF_HEADER, CSRF_VALUE)
@@ -130,7 +127,7 @@ public void createMessage_Should_ReturnUnauthorizedAndCallNoMethods_WhenNoKeyclo
@Test
@WithMockUser
- public void createMessage_Should_ReturnForbiddenAndCallNoMethods_WhenNoUserOrConsultantOrTechnicalDefaultAuthority()
+ void createMessage_Should_ReturnForbiddenAndCallNoMethods_WhenNoUserOrConsultantOrTechnicalDefaultAuthority()
throws Exception {
mvc.perform(post(PATH_POST_CREATE_MESSAGE).cookie(csrfCookie).header(CSRF_HEADER, CSRF_VALUE)
@@ -144,7 +141,7 @@ public void createMessage_Should_ReturnForbiddenAndCallNoMethods_WhenNoUserOrCon
@Test
@WithMockUser(authorities = {AuthorityValue.CONSULTANT_DEFAULT, AuthorityValue.USER_DEFAULT,
AuthorityValue.TECHNICAL_DEFAULT})
- public void createMessage_Should_ReturnForbiddenAndCallNoMethods_WhenNoCsrfTokens()
+ void createMessage_Should_ReturnForbiddenAndCallNoMethods_WhenNoCsrfTokens()
throws Exception {
mvc.perform(post(PATH_POST_CREATE_MESSAGE).contentType(MediaType.APPLICATION_JSON)
@@ -155,7 +152,7 @@ public void createMessage_Should_ReturnForbiddenAndCallNoMethods_WhenNoCsrfToken
}
@Test
- public void updateKey_Should_ReturnUnauthorizedAndCallNoMethods_WhenNoKeycloakAuthorization()
+ void updateKey_Should_ReturnUnauthorizedAndCallNoMethods_WhenNoKeycloakAuthorization()
throws Exception {
mvc.perform(post(PATH_POST_UPDATE_KEY).cookie(csrfCookie).header(CSRF_HEADER, CSRF_VALUE)
@@ -167,7 +164,7 @@ public void updateKey_Should_ReturnUnauthorizedAndCallNoMethods_WhenNoKeycloakAu
@Test
@WithMockUser(authorities = {AuthorityValue.CONSULTANT_DEFAULT, AuthorityValue.USER_DEFAULT})
- public void updateKey_Should_ReturnForbiddenAndCallNoMethods_WhenNoTechnicalDefaultAuthority()
+ void updateKey_Should_ReturnForbiddenAndCallNoMethods_WhenNoTechnicalDefaultAuthority()
throws Exception {
mvc.perform(post(PATH_POST_UPDATE_KEY).cookie(csrfCookie).header(CSRF_HEADER, CSRF_VALUE)
@@ -179,7 +176,7 @@ public void updateKey_Should_ReturnForbiddenAndCallNoMethods_WhenNoTechnicalDefa
@Test
@WithMockUser(authorities = {AuthorityValue.TECHNICAL_DEFAULT})
- public void updateKey_Should_ReturnForbiddenAndCallNoMethods_WhenNoCsrfTokens() throws Exception {
+ void updateKey_Should_ReturnForbiddenAndCallNoMethods_WhenNoCsrfTokens() throws Exception {
mvc.perform(post(PATH_POST_UPDATE_KEY).contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)).andExpect(status().isForbidden());
@@ -188,7 +185,7 @@ public void updateKey_Should_ReturnForbiddenAndCallNoMethods_WhenNoCsrfTokens()
}
@Test
- public void forwardMessage_Should_ReturnUnauthorizedAndCallNoMethods_WhenNoKeycloakAuthorization()
+ void forwardMessage_Should_ReturnUnauthorizedAndCallNoMethods_WhenNoKeycloakAuthorization()
throws Exception {
mvc.perform(post(PATH_POST_FORWARD_MESSAGE).cookie(csrfCookie).header(CSRF_HEADER, CSRF_VALUE)
@@ -201,7 +198,7 @@ public void forwardMessage_Should_ReturnUnauthorizedAndCallNoMethods_WhenNoKeycl
@Test
@WithMockUser
- public void forwardMessage_Should_ReturnForbiddenAndCallNoMethods_WhenNoUserFeedbackAuthority()
+ void forwardMessage_Should_ReturnForbiddenAndCallNoMethods_WhenNoUserFeedbackAuthority()
throws Exception {
mvc.perform(post(PATH_POST_FORWARD_MESSAGE).cookie(csrfCookie).header(CSRF_HEADER, CSRF_VALUE)
@@ -214,7 +211,7 @@ public void forwardMessage_Should_ReturnForbiddenAndCallNoMethods_WhenNoUserFeed
@Test
@WithMockUser(authorities = {AuthorityValue.USE_FEEDBACK})
- public void forwardMessage_Should_ReturnForbiddenAndCallNoMethods_WhenNoCsrfTokens()
+ void forwardMessage_Should_ReturnForbiddenAndCallNoMethods_WhenNoCsrfTokens()
throws Exception {
mvc.perform(post(PATH_POST_FORWARD_MESSAGE).contentType(MediaType.APPLICATION_JSON)
@@ -225,7 +222,7 @@ public void forwardMessage_Should_ReturnForbiddenAndCallNoMethods_WhenNoCsrfToke
}
@Test
- public void createFeedbackMessage_Should_ReturnUnauthorizedAndCallNoMethods_WhenNoKeycloakAuthorization()
+ void createFeedbackMessage_Should_ReturnUnauthorizedAndCallNoMethods_WhenNoKeycloakAuthorization()
throws Exception {
mvc.perform(
@@ -239,7 +236,7 @@ public void createFeedbackMessage_Should_ReturnUnauthorizedAndCallNoMethods_When
@Test
@WithMockUser
- public void createFeedbackMessage_Should_ReturnForbiddenAndCallNoMethods_WhenNoUserFeedbackAuthority()
+ void createFeedbackMessage_Should_ReturnForbiddenAndCallNoMethods_WhenNoUserFeedbackAuthority()
throws Exception {
mvc.perform(
@@ -253,7 +250,7 @@ public void createFeedbackMessage_Should_ReturnForbiddenAndCallNoMethods_WhenNoU
@Test
@WithMockUser(authorities = {AuthorityValue.USE_FEEDBACK})
- public void createFeedbackMessage_Should_ReturnForbiddenAndCallNoMethods_WhenNoCsrfTokens()
+ void createFeedbackMessage_Should_ReturnForbiddenAndCallNoMethods_WhenNoCsrfTokens()
throws Exception {
mvc.perform(post(PATH_POST_CREATE_FEEDBACK_MESSAGE).contentType(MediaType.APPLICATION_JSON)
@@ -264,7 +261,7 @@ public void createFeedbackMessage_Should_ReturnForbiddenAndCallNoMethods_WhenNoC
}
@Test
- public void createVideoHintMessage_Should_ReturnUnauthorizedAndCallNoMethods_When_NoKeycloakAuthorization()
+ void createVideoHintMessage_Should_ReturnUnauthorizedAndCallNoMethods_When_NoKeycloakAuthorization()
throws Exception {
mvc.perform(
@@ -281,7 +278,7 @@ public void createVideoHintMessage_Should_ReturnUnauthorizedAndCallNoMethods_Whe
@Test
@WithMockUser
- public void createVideoHintMessage_Should_ReturnForbiddenAndCallNoMethods_When_NoUserOrConsultantAuthority()
+ void createVideoHintMessage_Should_ReturnForbiddenAndCallNoMethods_When_NoUserOrConsultantAuthority()
throws Exception {
mvc.perform(
@@ -298,7 +295,7 @@ public void createVideoHintMessage_Should_ReturnForbiddenAndCallNoMethods_When_N
@Test
@WithMockUser(authorities = {AuthorityValue.USER_DEFAULT})
- public void createVideoHintMessage_Should_ReturnForbiddenAndCallNoMethods_When_NoCsrfTokens()
+ void createVideoHintMessage_Should_ReturnForbiddenAndCallNoMethods_When_NoCsrfTokens()
throws Exception {
mvc.perform(
@@ -313,7 +310,7 @@ public void createVideoHintMessage_Should_ReturnForbiddenAndCallNoMethods_When_N
@Test
@WithMockUser(authorities = {AuthorityValue.USER_DEFAULT})
- public void createVideoHintMessage_Should_ReturnCreatedAndCallPostGroupMessageFacade_When_UserAuthority()
+ void createVideoHintMessage_Should_ReturnCreatedAndCallPostGroupMessageFacade_When_UserAuthority()
throws Exception {
var videoCallMessageDTO = easyRandom.nextObject(VideoCallMessageDTO.class);
@@ -333,7 +330,7 @@ public void createVideoHintMessage_Should_ReturnCreatedAndCallPostGroupMessageFa
@Test
@WithMockUser(authorities = {AuthorityValue.CONSULTANT_DEFAULT})
- public void createVideoHintMessage_Should_ReturnCreatedAndCallPostGroupMessageFacade_When_ConsultantAuthority()
+ void createVideoHintMessage_Should_ReturnCreatedAndCallPostGroupMessageFacade_When_ConsultantAuthority()
throws Exception {
var videoCallMessageDTO = easyRandom.nextObject(VideoCallMessageDTO.class);
@@ -352,7 +349,7 @@ public void createVideoHintMessage_Should_ReturnCreatedAndCallPostGroupMessageFa
}
@Test
- public void saveAliasOnlyMessage_Should_ReturnUnauthorizedAndCallNoMethods_When_NoKeycloakAuthorization()
+ void saveAliasOnlyMessage_Should_ReturnUnauthorizedAndCallNoMethods_When_NoKeycloakAuthorization()
throws Exception {
var aliasOnlyMessageDTO = createAliasOnlyMessageWithoutProtectedType();
@@ -371,7 +368,7 @@ public void saveAliasOnlyMessage_Should_ReturnUnauthorizedAndCallNoMethods_When_
@Test
@WithMockUser
- public void saveAliasOnlyMessage_Should_ReturnForbiddenAndCallNoMethods_When_NoUserDefaultAuthority()
+ void saveAliasOnlyMessage_Should_ReturnForbiddenAndCallNoMethods_When_NoUserDefaultAuthority()
throws Exception {
var aliasOnlyMessageDTO = createAliasOnlyMessageWithoutProtectedType();
@@ -390,7 +387,7 @@ public void saveAliasOnlyMessage_Should_ReturnForbiddenAndCallNoMethods_When_NoU
@Test
@WithMockUser(authorities = {AuthorityValue.USER_DEFAULT})
- public void saveAliasOnlyMessage_Should_ReturnForbiddenAndCallNoMethods_When_NoCsrfTokens()
+ void saveAliasOnlyMessage_Should_ReturnForbiddenAndCallNoMethods_When_NoCsrfTokens()
throws Exception {
var aliasOnlyMessageDTO = createAliasOnlyMessageWithoutProtectedType();
@@ -407,7 +404,7 @@ public void saveAliasOnlyMessage_Should_ReturnForbiddenAndCallNoMethods_When_NoC
@Test
@WithMockUser(authorities = {AuthorityValue.USER_DEFAULT})
- public void saveAliasOnlyMessage_Should_ReturnCreatedAndCallPostGroupMessageFacade_When_UserDefaultAuthority()
+ void saveAliasOnlyMessage_Should_ReturnCreatedAndCallPostGroupMessageFacade_When_UserDefaultAuthority()
throws Exception {
var aliasOnlyMessageDTO = createAliasOnlyMessageWithoutProtectedType();
@@ -426,7 +423,7 @@ public void saveAliasOnlyMessage_Should_ReturnCreatedAndCallPostGroupMessageFaca
@Test
@WithMockUser(authorities = AuthorityValue.CONSULTANT_DEFAULT)
- public void saveAliasOnlyMessageShouldReturnCreatedWhenConsultantDefaultAuthority()
+ void saveAliasOnlyMessageShouldReturnCreatedWhenConsultantDefaultAuthority()
throws Exception {
var aliasOnlyMessageDTO = createAliasOnlyMessageWithoutProtectedType();
@@ -443,7 +440,7 @@ public void saveAliasOnlyMessageShouldReturnCreatedWhenConsultantDefaultAuthorit
@Test
@WithMockUser(authorities = {AuthorityValue.ANONYMOUS_DEFAULT})
- public void createVideoHintMessage_Should_ReturnCreatedAndCallPostGroupMessageFacade_When_AnonyousAuthority()
+ void createVideoHintMessage_Should_ReturnCreatedAndCallPostGroupMessageFacade_When_AnonyousAuthority()
throws Exception {
var videoCallMessageDTO = easyRandom.nextObject(VideoCallMessageDTO.class);
@@ -463,7 +460,7 @@ public void createVideoHintMessage_Should_ReturnCreatedAndCallPostGroupMessageFa
@Test
@WithMockUser(authorities = {AuthorityValue.ANONYMOUS_DEFAULT})
- public void sendNewMessage_Should_ReturnCreated_When_AnonyousAuthority()
+ void sendNewMessage_Should_ReturnCreated_When_AnonyousAuthority()
throws Exception {
var messageDTO = easyRandom.nextObject(MessageDTO.class);
@@ -482,7 +479,7 @@ public void sendNewMessage_Should_ReturnCreated_When_AnonyousAuthority()
@Test
@WithMockUser(authorities = {AuthorityValue.ANONYMOUS_DEFAULT})
- public void findMessages_Should_ReturnNoContent_When_AnonymousAuthority()
+ void findMessages_Should_ReturnNoContent_When_AnonymousAuthority()
throws Exception {
mvc.perform(get(PATH_GET_MESSAGE_STREAM)
.cookie(csrfCookie)
@@ -497,7 +494,7 @@ public void findMessages_Should_ReturnNoContent_When_AnonymousAuthority()
@Test
@WithMockUser(authorities = {AuthorityValue.TECHNICAL_DEFAULT})
- public void saveAliasOnlyMessage_Should_ReturnCreatedAndCallPostGroupMessageFacade_When_TechnicalDefaultAuthority()
+ void saveAliasOnlyMessage_Should_ReturnCreatedAndCallPostGroupMessageFacade_When_TechnicalDefaultAuthority()
throws Exception {
var aliasOnlyMessageDTO = givenAValidAliasOnlyMessageDTO();
@@ -515,7 +512,7 @@ public void saveAliasOnlyMessage_Should_ReturnCreatedAndCallPostGroupMessageFaca
}
@Test
- public void patchMessageShouldReturnUnauthorizedWhenNoKeycloakAuthorization() throws Exception {
+ void patchMessageShouldReturnUnauthorizedWhenNoKeycloakAuthorization() throws Exception {
givenAPatchSupportedReassignArg();
givenAValidMessageId();
@@ -537,7 +534,7 @@ public void patchMessageShouldReturnUnauthorizedWhenNoKeycloakAuthorization() th
AuthorityValue.TECHNICAL_DEFAULT,
AuthorityValue.USE_FEEDBACK
})
- public void patchMessageShouldReturnForbiddenAndCallNoMethodsWhenNoUserDefaultAuthority()
+ void patchMessageShouldReturnForbiddenAndCallNoMethodsWhenNoUserDefaultAuthority()
throws Exception {
givenAPatchSupportedReassignArg();
givenAValidMessageId();
@@ -555,7 +552,7 @@ public void patchMessageShouldReturnForbiddenAndCallNoMethodsWhenNoUserDefaultAu
@Test
@WithMockUser(authorities = AuthorityValue.USER_DEFAULT)
- public void patchMessageShouldReturnForbiddenAndCallNoMethodsWhenNoCsrfToken() throws Exception {
+ void patchMessageShouldReturnForbiddenAndCallNoMethodsWhenNoCsrfToken() throws Exception {
givenAPatchSupportedReassignArg();
givenAValidMessageId();
@@ -570,7 +567,7 @@ public void patchMessageShouldReturnForbiddenAndCallNoMethodsWhenNoCsrfToken() t
}
@Test
- public void deleteMessageShouldReturnUnauthorizedWhenNoKeycloakAuthorization() throws Exception {
+ void deleteMessageShouldReturnUnauthorizedWhenNoKeycloakAuthorization() throws Exception {
givenAValidMessageId();
mvc.perform(
@@ -587,7 +584,7 @@ public void deleteMessageShouldReturnUnauthorizedWhenNoKeycloakAuthorization() t
AuthorityValue.TECHNICAL_DEFAULT,
AuthorityValue.USE_FEEDBACK
})
- public void deleteMessageShouldReturnForbiddenAndCallNoMethodsWhenNoUserDefaultAuthority()
+ void deleteMessageShouldReturnForbiddenAndCallNoMethodsWhenNoUserDefaultAuthority()
throws Exception {
givenAValidMessageId();
@@ -602,7 +599,7 @@ public void deleteMessageShouldReturnForbiddenAndCallNoMethodsWhenNoUserDefaultA
@Test
@WithMockUser(authorities = AuthorityValue.USER_DEFAULT)
- public void deleteMessageShouldReturnForbiddenAndCallNoMethodsWhenNoCsrfToken() throws Exception {
+ void deleteMessageShouldReturnForbiddenAndCallNoMethodsWhenNoCsrfToken() throws Exception {
givenAValidMessageId();
mvc.perform(
@@ -614,7 +611,7 @@ public void deleteMessageShouldReturnForbiddenAndCallNoMethodsWhenNoCsrfToken()
}
@Test
- public void findMessageShouldReturnUnauthorizedWhenNoKeycloakAuthorization() throws Exception {
+ void findMessageShouldReturnUnauthorizedWhenNoKeycloakAuthorization() throws Exception {
givenAValidMessageId();
mvc.perform(
@@ -631,7 +628,7 @@ public void findMessageShouldReturnUnauthorizedWhenNoKeycloakAuthorization() thr
AuthorityValue.TECHNICAL_DEFAULT,
AuthorityValue.USE_FEEDBACK
})
- public void findMessageShouldReturnForbiddenAndCallNoMethodsWhenNoSupportedAuthority()
+ void findMessageShouldReturnForbiddenAndCallNoMethodsWhenNoSupportedAuthority()
throws Exception {
givenAValidMessageId();
@@ -646,7 +643,7 @@ public void findMessageShouldReturnForbiddenAndCallNoMethodsWhenNoSupportedAutho
@Test
@WithMockUser(authorities = AuthorityValue.USER_DEFAULT)
- public void findMessageShouldReturnForbiddenAndCallNoMethodsWhenNoCsrfToken() throws Exception {
+ void findMessageShouldReturnForbiddenAndCallNoMethodsWhenNoCsrfToken() throws Exception {
givenAValidMessageId();
mvc.perform(
diff --git a/src/test/java/de/caritas/cob/messageservice/api/controller/MessageControllerTestIT.java b/src/test/java/de/caritas/cob/messageservice/api/controller/MessageControllerTestIT.java
index 866880f..db2fba3 100644
--- a/src/test/java/de/caritas/cob/messageservice/api/controller/MessageControllerTestIT.java
+++ b/src/test/java/de/caritas/cob/messageservice/api/controller/MessageControllerTestIT.java
@@ -35,7 +35,6 @@
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
@@ -74,23 +73,18 @@
import java.util.Optional;
import org.assertj.core.util.Arrays;
import org.jeasy.random.EasyRandom;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
+import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
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.http.MediaType;
-import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
-@RunWith(SpringRunner.class)
@WebMvcTest(MessageController.class)
@AutoConfigureMockMvc(addFilters = false)
-public class MessageControllerTestIT {
+class MessageControllerTestIT {
private static final EasyRandom easyRandom = new EasyRandom();
@@ -157,7 +151,7 @@ RC_TIMESTAMP, new UserDTO(RC_USER_ID, "test", "name"), false, new String[0], new
*/
@Test
- public void createMessage_Should_ReturnBadRequest_WhenProvidedWithInvalidRequestBody()
+ void createMessage_Should_ReturnBadRequest_WhenProvidedWithInvalidRequestBody()
throws Exception {
mvc.perform(post(PATH_POST_CREATE_MESSAGE).header(QUERY_PARAM_RC_TOKEN, RC_TOKEN)
@@ -167,7 +161,7 @@ public void createMessage_Should_ReturnBadRequest_WhenProvidedWithInvalidRequest
}
@Test
- public void createMessage_Should_ReturnBadRequest_WhenHeaderValuesAreMissing() throws Exception {
+ void createMessage_Should_ReturnBadRequest_WhenHeaderValuesAreMissing() throws Exception {
mvc.perform(
post(PATH_POST_CREATE_MESSAGE).content(VALID_MESSAGE_REQUEST_BODY_WITHOUT_NOTIFICATION)
@@ -176,7 +170,7 @@ public void createMessage_Should_ReturnBadRequest_WhenHeaderValuesAreMissing() t
}
@Test
- public void getMessageStream_Should_ReturnBadRequest_WhenHeaderValuesAreMissing()
+ void getMessageStream_Should_ReturnBadRequest_WhenHeaderValuesAreMissing()
throws Exception {
mvc.perform(get(PATH_GET_MESSAGE_STREAM).param(QUERY_PARAM_OFFSET, RC_OFFSET)
@@ -185,7 +179,7 @@ public void getMessageStream_Should_ReturnBadRequest_WhenHeaderValuesAreMissing(
}
@Test
- public void getMessageStream_Should_ReturnBadRequest_WhenRequestParamsAreMissing()
+ void getMessageStream_Should_ReturnBadRequest_WhenRequestParamsAreMissing()
throws Exception {
mvc.perform(get(PATH_GET_MESSAGE_STREAM).header(QUERY_PARAM_RC_TOKEN, RC_TOKEN)
@@ -194,7 +188,7 @@ public void getMessageStream_Should_ReturnBadRequest_WhenRequestParamsAreMissing
}
@Test
- public void forwardMessage_Should_ReturnBadRequest_WhenProvidedWithInvalidRequestBody()
+ void forwardMessage_Should_ReturnBadRequest_WhenProvidedWithInvalidRequestBody()
throws Exception {
mvc.perform(post(PATH_POST_FORWARD_MESSAGE).header(QUERY_PARAM_RC_TOKEN, RC_TOKEN)
@@ -204,7 +198,7 @@ public void forwardMessage_Should_ReturnBadRequest_WhenProvidedWithInvalidReques
}
@Test
- public void forwardMessage_Should_ReturnBadRequest_WhenHeaderValuesAreMissing() throws Exception {
+ void forwardMessage_Should_ReturnBadRequest_WhenHeaderValuesAreMissing() throws Exception {
mvc.perform(post(PATH_POST_FORWARD_MESSAGE).content(VALID_FORWARD_MESSAGE_REQUEST_BODY)
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
@@ -212,7 +206,7 @@ public void forwardMessage_Should_ReturnBadRequest_WhenHeaderValuesAreMissing()
}
@Test
- public void createFeedbackMessage_Should_ReturnBadRequest_WhenProvidedWithInvalidRequestBody()
+ void createFeedbackMessage_Should_ReturnBadRequest_WhenProvidedWithInvalidRequestBody()
throws Exception {
mvc.perform(post(PATH_POST_CREATE_FEEDBACK_MESSAGE).header(QUERY_PARAM_RC_TOKEN, RC_TOKEN)
@@ -223,7 +217,7 @@ public void createFeedbackMessage_Should_ReturnBadRequest_WhenProvidedWithInvali
}
@Test
- public void createFeedbackMessage_Should_ReturnBadRequest_WhenHeaderValuesAreMissing()
+ void createFeedbackMessage_Should_ReturnBadRequest_WhenHeaderValuesAreMissing()
throws Exception {
mvc.perform(
@@ -238,7 +232,7 @@ public void createFeedbackMessage_Should_ReturnBadRequest_WhenHeaderValuesAreMis
*/
@Test
- public void getMessageStream_Should_ReturnOk_WhenProvidedWithValidRequestValues()
+ void getMessageStream_Should_ReturnOk_WhenProvidedWithValidRequestValues()
throws Exception {
List messages = new ArrayList<>();
@@ -260,7 +254,7 @@ public void getMessageStream_Should_ReturnOk_WhenProvidedWithValidRequestValues(
}
@Test
- public void createMessage_Should_ReturnCreated_WhenProvidedWithValidRequestValuesAndSuccessfulPostGroupMessageFacadeCall()
+ void createMessage_Should_ReturnCreated_WhenProvidedWithValidRequestValuesAndSuccessfulPostGroupMessageFacadeCall()
throws Exception {
mvc.perform(post(PATH_POST_CREATE_MESSAGE).header(QUERY_PARAM_RC_TOKEN, RC_TOKEN)
@@ -273,7 +267,7 @@ public void createMessage_Should_ReturnCreated_WhenProvidedWithValidRequestValue
}
@Test
- public void forwardMessage_Should_ReturnCreated_WhenProvidedWithValidRequestValuesAndSuccessfulPostGroupMessageFacadeCall()
+ void forwardMessage_Should_ReturnCreated_WhenProvidedWithValidRequestValuesAndSuccessfulPostGroupMessageFacadeCall()
throws Exception {
mvc.perform(post(PATH_POST_FORWARD_MESSAGE).header(QUERY_PARAM_RC_TOKEN, RC_TOKEN)
@@ -283,7 +277,7 @@ public void forwardMessage_Should_ReturnCreated_WhenProvidedWithValidRequestValu
}
@Test
- public void createFeedbackMessage_Should_ReturnCreated_WhenProvidedWithValidRequestValuesAndSuccessfulPostGroupMessageFacadeCall()
+ void createFeedbackMessage_Should_ReturnCreated_WhenProvidedWithValidRequestValuesAndSuccessfulPostGroupMessageFacadeCall()
throws Exception {
mvc.perform(post(PATH_POST_CREATE_FEEDBACK_MESSAGE).header(QUERY_PARAM_RC_TOKEN, RC_TOKEN)
@@ -300,7 +294,7 @@ public void createFeedbackMessage_Should_ReturnCreated_WhenProvidedWithValidRequ
* 204 - No Content test
*/
@Test
- public void getMessageStream_Should_ReturnNoContent_WhenProvidedWithValidRequestValuesAndMessageStreamIsEmpty()
+ void getMessageStream_Should_ReturnNoContent_WhenProvidedWithValidRequestValuesAndMessageStreamIsEmpty()
throws Exception {
when(rocketChatService.getGroupMessages(anyString(), anyString(),
@@ -319,7 +313,7 @@ public void getMessageStream_Should_ReturnNoContent_WhenProvidedWithValidRequest
* 500 - Internal Server Error test
*/
@Test
- public void createMessage_Should_ReturnInternalServerError_WhenProvidedWithValidRequestValuesAndPostGroupMessageFacadeResponseIsEmpty()
+ void createMessage_Should_ReturnInternalServerError_WhenProvidedWithValidRequestValuesAndPostGroupMessageFacadeResponseIsEmpty()
throws Exception {
doThrow(new InternalServerErrorException())
@@ -335,7 +329,7 @@ public void createMessage_Should_ReturnInternalServerError_WhenProvidedWithValid
}
@Test
- public void forwardMessage_Should_ReturnInternalServerError_WhenProvidedWithValidRequestValuesAndPostGroupMessageFacadeResponseIsEmpty()
+ void forwardMessage_Should_ReturnInternalServerError_WhenProvidedWithValidRequestValuesAndPostGroupMessageFacadeResponseIsEmpty()
throws Exception {
doThrow(new InternalServerErrorException())
@@ -351,7 +345,7 @@ public void forwardMessage_Should_ReturnInternalServerError_WhenProvidedWithVali
}
@Test
- public void createFeedbackMessage_Should_ReturnInternalServerError_WhenProvidedWithValidRequestValuesAndPostGroupMessageFacadeResponseIsEmpty()
+ void createFeedbackMessage_Should_ReturnInternalServerError_WhenProvidedWithValidRequestValuesAndPostGroupMessageFacadeResponseIsEmpty()
throws Exception {
doThrow(new InternalServerErrorException()).when(messenger)
@@ -372,7 +366,7 @@ public void createFeedbackMessage_Should_ReturnInternalServerError_WhenProvidedW
* 202 - Accepted Test
*/
@Test
- public void updateKey_Should_ReturnAccepted_WhenProvidedWithNewKey() throws Exception {
+ void updateKey_Should_ReturnAccepted_WhenProvidedWithNewKey() throws Exception {
when(encryptionService.getMasterKey()).thenReturn(MASTER_KEY_1);
@@ -385,7 +379,7 @@ public void updateKey_Should_ReturnAccepted_WhenProvidedWithNewKey() throws Exce
* 409 - Conflict test
*/
@Test
- public void updateKey_Should_ReturnConflict_WhenProvidedWithSameKey() throws Exception {
+ void updateKey_Should_ReturnConflict_WhenProvidedWithSameKey() throws Exception {
when(encryptionService.getMasterKey()).thenReturn(MASTER_KEY_1);
@@ -404,7 +398,7 @@ private String convertObjectToJson(Object object) throws JsonProcessingException
}
@Test
- public void createMessage_Should_ReturnInternalServerError_When_InternalServerErrorIsThrown()
+ void createMessage_Should_ReturnInternalServerError_When_InternalServerErrorIsThrown()
throws Exception {
doThrow(new InternalServerErrorException()).when(messenger)
@@ -418,14 +412,14 @@ public void createMessage_Should_ReturnInternalServerError_When_InternalServerEr
}
@Test
- public void saveDraftMessage_Should_returnBadRequest_When_rcGroupIdAndMessageIsMissing()
+ void saveDraftMessage_Should_returnBadRequest_When_rcGroupIdAndMessageIsMissing()
throws Exception {
mvc.perform(post(PATH_DRAFT_MESSAGE).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest());
}
@Test
- public void saveDraftMessage_Should_returnBadRequest_When_rcGroupIdIsMissing() throws Exception {
+ void saveDraftMessage_Should_returnBadRequest_When_rcGroupIdIsMissing() throws Exception {
mvc.perform(post(PATH_DRAFT_MESSAGE)
.content("message")
.contentType(MediaType.APPLICATION_JSON))
@@ -433,7 +427,7 @@ public void saveDraftMessage_Should_returnBadRequest_When_rcGroupIdIsMissing() t
}
@Test
- public void saveDraftMessage_Should_returnBadRequest_When_messageIsMissing() throws Exception {
+ void saveDraftMessage_Should_returnBadRequest_When_messageIsMissing() throws Exception {
mvc.perform(post(PATH_DRAFT_MESSAGE)
.header(QUERY_PARAM_RC_GROUP_ID, RC_GROUP_ID)
.contentType(MediaType.APPLICATION_JSON))
@@ -441,7 +435,7 @@ public void saveDraftMessage_Should_returnBadRequest_When_messageIsMissing() thr
}
@Test
- public void saveDraftMessage_Should_returnCreated_When_messageIsNew() throws Exception {
+ void saveDraftMessage_Should_returnCreated_When_messageIsNew() throws Exception {
var draftMessageDTO = new DraftMessageDTO();
draftMessageDTO.setMessage("message");
when(this.draftMessageService.saveDraftMessage(any(), any(), any())).thenReturn(
@@ -455,7 +449,7 @@ public void saveDraftMessage_Should_returnCreated_When_messageIsNew() throws Exc
}
@Test
- public void saveDraftMessage_Should_returnOk_When_messageIsOverwritten() throws Exception {
+ void saveDraftMessage_Should_returnOk_When_messageIsOverwritten() throws Exception {
when(this.draftMessageService.saveDraftMessage(any(), any(), any())).thenReturn(
OVERWRITTEN_MESSAGE);
var draftMessage = new DraftMessageDTO();
@@ -469,13 +463,13 @@ public void saveDraftMessage_Should_returnOk_When_messageIsOverwritten() throws
}
@Test
- public void findDraftMessage_Should_returnBadRequest_When_rcGroupIdIsMissing() throws Exception {
+ void findDraftMessage_Should_returnBadRequest_When_rcGroupIdIsMissing() throws Exception {
mvc.perform(get(PATH_DRAFT_MESSAGE).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest());
}
@Test
- public void findDraftMessage_Should_returnDraftMessage_When_messageExists() throws Exception {
+ void findDraftMessage_Should_returnDraftMessage_When_messageExists() throws Exception {
var draftMessageDTO = new DraftMessageDTO();
draftMessageDTO.setMessage("message");
var draftMessage = Optional.of(draftMessageDTO);
@@ -494,7 +488,7 @@ public void findDraftMessage_Should_returnDraftMessage_When_messageExists() thro
}
@Test
- public void findDraftMessage_Should_returnNoContent_When_noDraftMessageExists() throws Exception {
+ void findDraftMessage_Should_returnNoContent_When_noDraftMessageExists() throws Exception {
mvc.perform(get(PATH_DRAFT_MESSAGE)
.header(QUERY_PARAM_RC_GROUP_ID, RC_GROUP_ID)
.contentType(MediaType.APPLICATION_JSON))
@@ -502,7 +496,7 @@ public void findDraftMessage_Should_returnNoContent_When_noDraftMessageExists()
}
@Test
- public void createVideoHintMessage_Should_ReturnBadRequest_When_rcGroupIdIsMissing()
+ void createVideoHintMessage_Should_ReturnBadRequest_When_rcGroupIdIsMissing()
throws Exception {
VideoCallMessageDTO videoCallMessageDTO =
@@ -519,7 +513,7 @@ public void createVideoHintMessage_Should_ReturnBadRequest_When_rcGroupIdIsMissi
}
@Test
- public void createVideoHintMessage_Should_ReturnBadRequest_When_videoCallMessageDTOIsMissing()
+ void createVideoHintMessage_Should_ReturnBadRequest_When_videoCallMessageDTOIsMissing()
throws Exception {
mvc.perform(
@@ -533,7 +527,7 @@ public void createVideoHintMessage_Should_ReturnBadRequest_When_videoCallMessage
}
@Test
- public void createVideoHintMessage_Should_ReturnBadRequest_When_videoCallMessageDTOIsEmpty()
+ void createVideoHintMessage_Should_ReturnBadRequest_When_videoCallMessageDTOIsEmpty()
throws Exception {
mvc.perform(
@@ -548,7 +542,7 @@ public void createVideoHintMessage_Should_ReturnBadRequest_When_videoCallMessage
}
@Test
- public void createVideoHintMessage_Should_ReturnCreated_When_paramsAreValid()
+ void createVideoHintMessage_Should_ReturnCreated_When_paramsAreValid()
throws Exception {
VideoCallMessageDTO videoCallMessageDTO =
@@ -566,7 +560,7 @@ public void createVideoHintMessage_Should_ReturnCreated_When_paramsAreValid()
}
@Test
- public void saveAliasOnlyMessage_Should_ReturnBadRequest_When_rcGroupIdIsMissing()
+ void saveAliasOnlyMessage_Should_ReturnBadRequest_When_rcGroupIdIsMissing()
throws Exception {
AliasOnlyMessageDTO aliasOnlyMessageDTO =
easyRandom.nextObject(AliasOnlyMessageDTO.class);
@@ -582,7 +576,7 @@ public void saveAliasOnlyMessage_Should_ReturnBadRequest_When_rcGroupIdIsMissing
}
@Test
- public void saveAliasOnlyMessage_Should_ReturnBadRequest_When_AliasOnlyMessageDtoIsMissing()
+ void saveAliasOnlyMessage_Should_ReturnBadRequest_When_AliasOnlyMessageDtoIsMissing()
throws Exception {
mvc.perform(
post(PATH_POST_CREATE_ALIAS_ONLY_MESSAGE)
@@ -595,7 +589,7 @@ public void saveAliasOnlyMessage_Should_ReturnBadRequest_When_AliasOnlyMessageDt
}
@Test
- public void saveAliasOnlyMessage_Should_ReturnCreated_When_paramsAreValid()
+ void saveAliasOnlyMessage_Should_ReturnCreated_When_paramsAreValid()
throws Exception {
var aliasOnlyMessageDTO = easyRandom.nextObject(AliasOnlyMessageDTO.class);
aliasOnlyMessageDTO.setMessageType(MessageType.FORWARD);
diff --git a/src/test/java/de/caritas/cob/messageservice/api/helper/AuthenticatedUserHelperTest.java b/src/test/java/de/caritas/cob/messageservice/api/helper/AuthenticatedUserHelperTest.java
index 66740c8..b479b9b 100644
--- a/src/test/java/de/caritas/cob/messageservice/api/helper/AuthenticatedUserHelperTest.java
+++ b/src/test/java/de/caritas/cob/messageservice/api/helper/AuthenticatedUserHelperTest.java
@@ -5,15 +5,15 @@
import de.caritas.cob.messageservice.api.authorization.Role;
import org.apache.commons.collections4.SetUtils;
-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)
-public class AuthenticatedUserHelperTest {
+@ExtendWith(MockitoExtension.class)
+class AuthenticatedUserHelperTest {
@Test
- public void isConsultant_Should_ReturnTrue_IfAuthenticatedUserIsConsultant() {
+ void isConsultant_Should_ReturnTrue_IfAuthenticatedUserIsConsultant() {
AuthenticatedUser authenticatedUser = new AuthenticatedUser();
authenticatedUser.setRoles(SetUtils.unmodifiableSet(Role.CONSULTANT.getRoleName()));
@@ -24,7 +24,7 @@ public void isConsultant_Should_ReturnTrue_IfAuthenticatedUserIsConsultant() {
}
@Test
- public void isConsultant_Should_ReturnFalse_IfAuthenticatedUserIsNotConsultant() {
+ void isConsultant_Should_ReturnFalse_IfAuthenticatedUserIsNotConsultant() {
AuthenticatedUser authenticatedUser = new AuthenticatedUser();
authenticatedUser.setRoles(SetUtils.unmodifiableSet(Role.USER.getRoleName()));
diff --git a/src/test/java/de/caritas/cob/messageservice/api/helper/AuthenticatedUserTest.java b/src/test/java/de/caritas/cob/messageservice/api/helper/AuthenticatedUserTest.java
index 67e0818..f7b1248 100644
--- a/src/test/java/de/caritas/cob/messageservice/api/helper/AuthenticatedUserTest.java
+++ b/src/test/java/de/caritas/cob/messageservice/api/helper/AuthenticatedUserTest.java
@@ -1,36 +1,42 @@
package de.caritas.cob.messageservice.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)
-public class AuthenticatedUserTest {
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.junit.jupiter.MockitoExtension;
- @Test(expected = NullPointerException.class)
- public void AuthenticatedUser_Should_ThrowNullPointerExceptionWhenArgumentsAreNull()
- throws Exception {
- new AuthenticatedUser(null, null, null, null, null);
+@ExtendWith(MockitoExtension.class)
+class AuthenticatedUserTest {
+
+ @Test
+ void AuthenticatedUser_Should_ThrowNullPointerExceptionWhenArgumentsAreNull() {
+ assertThrows(NullPointerException.class, () -> {
+ new AuthenticatedUser(null, null, null, null, null);
+ });
}
- @Test(expected = NullPointerException.class)
- public void AuthenticatedUser_Should_ThrowNullPointerExceptionWhenUserIdIsNull()
- throws Exception {
- AuthenticatedUser authenticatedUser = new AuthenticatedUser();
- authenticatedUser.setUserId(null);
+ @Test
+ void AuthenticatedUser_Should_ThrowNullPointerExceptionWhenUserIdIsNull() {
+ assertThrows(NullPointerException.class, () -> {
+ AuthenticatedUser authenticatedUser = new AuthenticatedUser();
+ authenticatedUser.setUserId(null);
+ });
}
- @Test(expected = NullPointerException.class)
- public void AuthenticatedUser_Should_ThrowNullPointerExceptionWhenUsernameIsNull()
- throws Exception {
- AuthenticatedUser authenticatedUser = new AuthenticatedUser();
- authenticatedUser.setUsername(null);
+ @Test
+ void AuthenticatedUser_Should_ThrowNullPointerExceptionWhenUsernameIsNull() {
+ assertThrows(NullPointerException.class, () -> {
+ AuthenticatedUser authenticatedUser = new AuthenticatedUser();
+ authenticatedUser.setUsername(null);
+ });
}
- @Test(expected = NullPointerException.class)
- public void AuthenticatedUser_Should_ThrowNullPointerExceptionWhenAccessTokenIsNull()
- throws Exception {
- AuthenticatedUser authenticatedUser = new AuthenticatedUser();
- authenticatedUser.setAccessToken(null);
+ @Test
+ void AuthenticatedUser_Should_ThrowNullPointerExceptionWhenAccessTokenIsNull() {
+ assertThrows(NullPointerException.class, () -> {
+ AuthenticatedUser authenticatedUser = new AuthenticatedUser();
+ authenticatedUser.setAccessToken(null);
+ });
}
}
diff --git a/src/test/java/de/caritas/cob/messageservice/api/helper/JSONHelperTests.java b/src/test/java/de/caritas/cob/messageservice/api/helper/JSONHelperTests.java
index 8868c2b..36a33f5 100644
--- a/src/test/java/de/caritas/cob/messageservice/api/helper/JSONHelperTests.java
+++ b/src/test/java/de/caritas/cob/messageservice/api/helper/JSONHelperTests.java
@@ -17,13 +17,13 @@
import java.time.format.DateTimeFormatter;
import java.util.Optional;
import org.jeasy.random.EasyRandom;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
-public class JSONHelperTests {
+class JSONHelperTests {
@Test
- public void convertAliasMessageDTOToString_Should_returnConvertedString_When_aliasMessageDTOIsvalid() {
+ void convertAliasMessageDTOToString_Should_returnConvertedString_When_aliasMessageDTOIsvalid() {
AliasMessageDTO aliasMessageDTO = new EasyRandom().nextObject(AliasMessageDTO.class);
Optional result = JSONHelper.convertAliasMessageDTOToString(aliasMessageDTO);
@@ -32,14 +32,14 @@ public void convertAliasMessageDTOToString_Should_returnConvertedString_When_ali
}
@Test
- public void convertStringToAliasMessageDTO_Should_returnOptionalEmpty_When_jsonStringCanNotBeConverted() {
+ void convertStringToAliasMessageDTO_Should_returnOptionalEmpty_When_jsonStringCanNotBeConverted() {
Optional result = JSONHelper.convertStringToAliasMessageDTO("alias");
assertThat(result.isPresent(), is(false));
}
@Test
- public void serialize_Should_returnOptionalWithSerializedObject() {
+ void serialize_Should_returnOptionalWithSerializedObject() {
OffsetDateTime offsetDateTime = CustomOffsetDateTime.nowInUtc();
@@ -87,7 +87,7 @@ public void serialize_Should_returnOptionalWithSerializedObject() {
}
@Test
- public void serialize_Should_returnOptionalEmpty_When_jsonStringCanNotBeConverted()
+ void serialize_Should_returnOptionalEmpty_When_jsonStringCanNotBeConverted()
throws JsonProcessingException {
ObjectMapper om = Mockito.spy(new ObjectMapper());
diff --git a/src/test/java/de/caritas/cob/messageservice/api/helper/UrlEncodingDecodingUtilsTest.java b/src/test/java/de/caritas/cob/messageservice/api/helper/UrlEncodingDecodingUtilsTest.java
index c291c0f..2603552 100644
--- a/src/test/java/de/caritas/cob/messageservice/api/helper/UrlEncodingDecodingUtilsTest.java
+++ b/src/test/java/de/caritas/cob/messageservice/api/helper/UrlEncodingDecodingUtilsTest.java
@@ -1,24 +1,24 @@
package de.caritas.cob.messageservice.api.helper;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-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)
-public class UrlEncodingDecodingUtilsTest {
+@ExtendWith(MockitoExtension.class)
+class UrlEncodingDecodingUtilsTest {
private static final String DECODED_STRING = "töst#$";
private static final String ENCODED_STRING = "t%C3%B6st%23%24";
@Test
- public void urlEncodeString_Should_ReturnEncodedString() {
+ void urlEncodeString_Should_ReturnEncodedString() {
assertEquals(ENCODED_STRING, UrlEncodingDecodingUtils.urlEncodeString(DECODED_STRING));
}
@Test
- public void urlDecodeString_Should_ReturnEncodedString() {
+ void urlDecodeString_Should_ReturnEncodedString() {
assertEquals(DECODED_STRING, UrlEncodingDecodingUtils.urlDecodeString(ENCODED_STRING));
}
diff --git a/src/test/java/de/caritas/cob/messageservice/api/helper/UserHelperTest.java b/src/test/java/de/caritas/cob/messageservice/api/helper/UserHelperTest.java
index 5da7e39..4399345 100644
--- a/src/test/java/de/caritas/cob/messageservice/api/helper/UserHelperTest.java
+++ b/src/test/java/de/caritas/cob/messageservice/api/helper/UserHelperTest.java
@@ -2,40 +2,40 @@
import static de.caritas.cob.messageservice.testhelper.TestConstants.USERNAME_DECODED;
import static de.caritas.cob.messageservice.testhelper.TestConstants.USERNAME_ENCODED;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-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)
-public class UserHelperTest {
+@ExtendWith(MockitoExtension.class)
+class UserHelperTest {
private UserHelper userHelper;
- @Before
- public void setup() {
+ @BeforeEach
+ void setup() {
this.userHelper = new UserHelper();
}
@Test
- public void encodeUsername_Should_ReturnEncodedUsernameWithReplacedPaddingAndAddedPrefix_WhenDecodedUsernameIsGiven() {
+ void encodeUsername_Should_ReturnEncodedUsernameWithReplacedPaddingAndAddedPrefix_WhenDecodedUsernameIsGiven() {
assertEquals(USERNAME_ENCODED, userHelper.encodeUsername(USERNAME_DECODED));
}
@Test
- public void encodeUsername_Should_ReturnEncodedUsername_WhenEncodedUsernameIsGiven() {
+ void encodeUsername_Should_ReturnEncodedUsername_WhenEncodedUsernameIsGiven() {
assertEquals(USERNAME_ENCODED, userHelper.encodeUsername(USERNAME_ENCODED));
}
@Test
- public void decodeUsername_Should_ReturnDecodedUsername_WhenEncodedUsernameIsGiven() {
+ void decodeUsername_Should_ReturnDecodedUsername_WhenEncodedUsernameIsGiven() {
assertEquals(USERNAME_DECODED, userHelper.decodeUsername(USERNAME_ENCODED));
}
@Test
- public void decodeUsername_Should_ReturnDecodedUsername_WhenDecodedUsernameIsGiven() {
+ void decodeUsername_Should_ReturnDecodedUsername_WhenDecodedUsernameIsGiven() {
assertEquals(USERNAME_DECODED, userHelper.decodeUsername(USERNAME_DECODED));
}
diff --git a/src/test/java/de/caritas/cob/messageservice/api/helper/XssProtectionTest.java b/src/test/java/de/caritas/cob/messageservice/api/helper/XssProtectionTest.java
index 30d0d33..ac64adf 100644
--- a/src/test/java/de/caritas/cob/messageservice/api/helper/XssProtectionTest.java
+++ b/src/test/java/de/caritas/cob/messageservice/api/helper/XssProtectionTest.java
@@ -4,48 +4,50 @@
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-public class XssProtectionTest {
+class XssProtectionTest {
@Test
- public void escapeHtml_Should_escapeStandardHtml() {
+ void escapeHtml_Should_escapeStandardHtml() {
String normalized = escapeHtml("Lorem Ipsum");
assertThat(normalized, is("<strong>Lorem Ipsum</strong>"));
}
@Test
- public void escapeHtml_Should_escapeJavascriptCode() {
+ void escapeHtml_Should_escapeJavascriptCode() {
String normalized = escapeHtml("Lorem Ipsum");
assertThat(normalized, is("Lorem Ipsum<script>alert('1');</script>"));
}
@Test
- public void escapeHtml_ShouldNot_removeNewlinesFromText() {
+ void escapeHtml_ShouldNot_removeNewlinesFromText() {
String normalized = escapeHtml("Lorem Ipsum\nLorem Ipsum");
assertThat(normalized, is("Lorem Ipsum\nLorem Ipsum"));
}
@Test
- public void escapeHtml_Should_escapeHtmlFromText_And_ShouldNot_removeNewlines() {
- String normalized = escapeHtml("Lorem Ipsum\nLorem Ipsum");
+ void escapeHtml_Should_escapeHtmlFromText_And_ShouldNot_removeNewlines() {
+ String normalized = escapeHtml("""
+ Lorem Ipsum
+ Lorem Ipsum""");
assertThat(normalized, is("<b>Lorem Ipsum</b>\nLorem Ipsum<script>alert('1');</script>"));
}
@Test
- public void removeHTMLFromText_Should_returnEmptyString_When_inputIsNull() {
+ void removeHTMLFromText_Should_returnEmptyString_When_inputIsNull() {
String normalized = escapeHtml(null);
assertThat(normalized, is(""));
}
@Test
- public void removeHTMLFromText_Should_returnEmptyString_When_inputIsEmptyString() {
+ void removeHTMLFromText_Should_returnEmptyString_When_inputIsEmptyString() {
String normalized = escapeHtml("");
assertThat(normalized, is(""));
diff --git a/src/test/java/de/caritas/cob/messageservice/api/model/jsondeserializer/AliasJsonDeserializerTest.java b/src/test/java/de/caritas/cob/messageservice/api/model/jsondeserializer/AliasJsonDeserializerTest.java
index 32b8e69..782111a 100644
--- a/src/test/java/de/caritas/cob/messageservice/api/model/jsondeserializer/AliasJsonDeserializerTest.java
+++ b/src/test/java/de/caritas/cob/messageservice/api/model/jsondeserializer/AliasJsonDeserializerTest.java
@@ -12,9 +12,9 @@
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.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+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;
@@ -30,13 +30,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 final ObjectMapper objectMapper = new ObjectMapper();
private final UserHelper userHelper = new UserHelper();
@@ -45,12 +45,12 @@ public class AliasJsonDeserializerTest {
private final String encodedUsername = userHelper.encodeUsername(decodedUsername);
@Test
- public void aliasJsonDeserializer_Schould_haveNoArgsConstructor() {
+ void aliasJsonDeserializer_Schould_haveNoArgsConstructor() {
assertTrue(ClassUtils.hasConstructor(AliasJsonDeserializer.class));
}
@Test
- public void deserialize_Schould_convertAliasWithEncodedUsernameToForwardMessageDTO()
+ void deserialize_Schould_convertAliasWithEncodedUsernameToForwardMessageDTO()
throws IOException {
ForwardMessageDTO result =
deserializeOldAliasJson(MESSAGE_FORWARD_ALIAS_JSON_WITH_ENCODED_USERNAME)
@@ -61,7 +61,7 @@ public void deserialize_Schould_convertAliasWithEncodedUsernameToForwardMessageD
}
@Test
- public void deserialize_Schould_convertAliasWithDecodedUsernameToForwardMessageDTO()
+ void deserialize_Schould_convertAliasWithDecodedUsernameToForwardMessageDTO()
throws IOException {
ForwardMessageDTO result =
deserializeOldAliasJson(MESSAGE_FORWARD_ALIAS_JSON_WITH_DECODED_USERNAME)
@@ -72,21 +72,21 @@ public void deserialize_Schould_convertAliasWithDecodedUsernameToForwardMessageD
}
@Test
- public void deserialize_Schould_ReturnNull_IfAliasIsEmpty()
+ void deserialize_Schould_ReturnNull_IfAliasIsEmpty()
throws IOException {
AliasMessageDTO result = deserializeOldAliasJson(MESSAGE_ALIAS_DTO_EMPTY_ALIAS_JSON);
assertNull(result);
}
@Test
- public void deserialize_Schould_ReturnNull_IfAliasIsNull()
+ void deserialize_Schould_ReturnNull_IfAliasIsNull()
throws IOException {
AliasMessageDTO result = deserializeOldAliasJson(MESSAGE_ALIAS_DTO_NULL_ALIAS_JSON);
assertNull(result);
}
@Test
- public void deserialize_Should_returnAliasDTOWithDecodedUsername_When_usernameIsEncoded()
+ void deserialize_Should_returnAliasDTOWithDecodedUsername_When_usernameIsEncoded()
throws Exception {
String aliasMessageDTO = asJsonString(new AliasMessageDTO()
.videoCallMessageDTO(new VideoCallMessageDTO()
@@ -103,7 +103,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(new AliasMessageDTO()
.videoCallMessageDTO(new VideoCallMessageDTO()
@@ -120,7 +120,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(new AliasMessageDTO()
.forwardMessageDTO(new ForwardMessageDTO()
diff --git a/src/test/java/de/caritas/cob/messageservice/api/model/jsondeserializer/DecodeUsernameJsonDeserializerTest.java b/src/test/java/de/caritas/cob/messageservice/api/model/jsondeserializer/DecodeUsernameJsonDeserializerTest.java
index 5d877c0..4e6e2bf 100644
--- a/src/test/java/de/caritas/cob/messageservice/api/model/jsondeserializer/DecodeUsernameJsonDeserializerTest.java
+++ b/src/test/java/de/caritas/cob/messageservice/api/model/jsondeserializer/DecodeUsernameJsonDeserializerTest.java
@@ -2,8 +2,8 @@
import static de.caritas.cob.messageservice.testhelper.TestConstants.USERNAME_DECODED;
import static de.caritas.cob.messageservice.testhelper.TestConstants.USERNAME_ENCODED;
-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 com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
@@ -14,40 +14,40 @@
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;
import org.springframework.util.ClassUtils;
-@RunWith(MockitoJUnitRunner.class)
-public class DecodeUsernameJsonDeserializerTest {
+@ExtendWith(MockitoExtension.class)
+class DecodeUsernameJsonDeserializerTest {
private ObjectMapper objectMapper;
private DecodeUsernameJsonDeserializer decodeUsernameJsonDeserializer;
private UserHelper userHelper;
- @Before
- public void setup() {
+ @BeforeEach
+ void setup() {
userHelper = new UserHelper();
objectMapper = new ObjectMapper();
decodeUsernameJsonDeserializer = new DecodeUsernameJsonDeserializer(userHelper);
}
@Test
- public void decodeUsernameJsonDeserializer_Schould_haveNoArgsConstructor() {
+ void decodeUsernameJsonDeserializer_Schould_haveNoArgsConstructor() {
assertTrue(ClassUtils.hasConstructor(DecodeUsernameJsonDeserializer.class));
}
@Test
- public void deserialize_Schould_DecodeEncodedUsername() throws JsonParseException, IOException {
+ void deserialize_Schould_DecodeEncodedUsername() throws JsonParseException, IOException {
String json = "{\"username:\":\"" + USERNAME_ENCODED + "\"}";
String result = deserializeUsername(json);
assertEquals(USERNAME_DECODED, result);
}
@Test
- public void deserialize_SchouldNot_DecodeNotEncodedUsername()
+ void deserialize_SchouldNot_DecodeNotEncodedUsername()
throws JsonParseException, IOException {
String json = "{\"username:\":\"" + USERNAME_DECODED + "\"}";
String result = deserializeUsername(json);
diff --git a/src/test/java/de/caritas/cob/messageservice/api/service/DraftMessageServiceIT.java b/src/test/java/de/caritas/cob/messageservice/api/service/DraftMessageServiceIT.java
index 9aa5f88..df37015 100644
--- a/src/test/java/de/caritas/cob/messageservice/api/service/DraftMessageServiceIT.java
+++ b/src/test/java/de/caritas/cob/messageservice/api/service/DraftMessageServiceIT.java
@@ -11,22 +11,19 @@
import de.caritas.cob.messageservice.api.exception.CustomCryptoException;
import de.caritas.cob.messageservice.api.helper.AuthenticatedUser;
import java.util.concurrent.atomic.AtomicInteger;
-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.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 = MessageServiceApplication.class)
@AutoConfigureTestDatabase(replace = Replace.ANY)
@TestPropertySource(properties = "spring.profiles.active=testing")
-public class DraftMessageServiceIT {
+class DraftMessageServiceIT {
@Autowired
private DraftMessageService draftMessageService;
@@ -37,8 +34,8 @@ public class DraftMessageServiceIT {
@MockBean
private EncryptionService encryptionService;
- @Before
- public void setup() throws CustomCryptoException {
+ @BeforeEach
+ void setup() throws CustomCryptoException {
doAnswer(encryptArgs -> encryptArgs.getArguments()[0]).when(encryptionService)
.encrypt(anyString(), anyString());
doAnswer(decryptArgs -> String.valueOf(decryptArgs.getArguments()[0])).when(encryptionService)
@@ -47,7 +44,7 @@ public void setup() throws CustomCryptoException {
}
@Test
- public void saveAndDeleteDraftMessage_Should_produceNoError_When_executionIsInParallel()
+ void saveAndDeleteDraftMessage_Should_produceNoError_When_executionIsInParallel()
throws InterruptedException {
AtomicInteger errorCount = new AtomicInteger(0);
int threadCount = 10;
@@ -66,7 +63,7 @@ public void saveAndDeleteDraftMessage_Should_produceNoError_When_executionIsInPa
}
@Test
- public void should_store_and_load_draft_messages() {
+ void should_store_and_load_draft_messages() {
var rcGroupId = "gvkUGHASLĂ–D";
draftMessageService.saveDraftMessage("message", rcGroupId, "e2e");
diff --git a/src/test/java/de/caritas/cob/messageservice/api/service/DraftMessageServiceTest.java b/src/test/java/de/caritas/cob/messageservice/api/service/DraftMessageServiceTest.java
index fdb4337..ed5a963 100644
--- a/src/test/java/de/caritas/cob/messageservice/api/service/DraftMessageServiceTest.java
+++ b/src/test/java/de/caritas/cob/messageservice/api/service/DraftMessageServiceTest.java
@@ -4,6 +4,7 @@
import static de.caritas.cob.messageservice.api.model.draftmessage.SavedDraftType.OVERWRITTEN_MESSAGE;
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;
@@ -18,16 +19,16 @@
import de.caritas.cob.messageservice.api.model.draftmessage.entity.DraftMessage;
import de.caritas.cob.messageservice.api.repository.DraftMessageRepository;
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.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
-public class DraftMessageServiceTest {
+@ExtendWith(MockitoExtension.class)
+class DraftMessageServiceTest {
@InjectMocks
private DraftMessageService draftMessageService;
@@ -46,7 +47,7 @@ public class DraftMessageServiceTest {
ArgumentCaptor captor;
@Test
- public void saveDraftMessage_Should_returnNewMessageType_When_noMessageForUserAndRcGroupExists()
+ void saveDraftMessage_Should_returnNewMessageType_When_noMessageForUserAndRcGroupExists()
throws CustomCryptoException {
SavedDraftType savedDraftType = this.draftMessageService.saveDraftMessage("message",
@@ -58,7 +59,7 @@ public void saveDraftMessage_Should_returnNewMessageType_When_noMessageForUserAn
}
@Test
- public void saveDraftMessage_Should_returnOverwrittenMessageType_When_messageForUserAndRcGroupExists()
+ void saveDraftMessage_Should_returnOverwrittenMessageType_When_messageForUserAndRcGroupExists()
throws CustomCryptoException {
when(this.draftMessageRepository.findByUserIdAndRcGroupId(any(), any()))
.thenReturn(Optional.of(new DraftMessage()));
@@ -74,7 +75,7 @@ public void saveDraftMessage_Should_returnOverwrittenMessageType_When_messageFor
}
@Test
- public void saveDraftMessage_should_not_encrypt_message_if_already_e2e_encrypted()
+ void saveDraftMessage_should_not_encrypt_message_if_already_e2e_encrypted()
throws CustomCryptoException {
draftMessageService.saveDraftMessage("message", "rcGroupId", "e2e");
@@ -84,14 +85,14 @@ public void saveDraftMessage_should_not_encrypt_message_if_already_e2e_encrypted
}
@Test
- public void deleteDraftMessageIfExist_Should_notCallDelete_When_noMessageForUserAndGroupExists() {
+ void deleteDraftMessageIfExist_Should_notCallDelete_When_noMessageForUserAndGroupExists() {
this.draftMessageService.deleteDraftMessageIfExist("rcGroupId");
verify(this.draftMessageRepository, times(0)).delete(any());
}
@Test
- public void deleteDraftMessageIfExist_Should_callDelete_When_messageForUserAndGroupExists() {
+ void deleteDraftMessageIfExist_Should_callDelete_When_messageForUserAndGroupExists() {
when(this.draftMessageRepository.findByUserIdAndRcGroupId(any(), any()))
.thenReturn(Optional.of(new DraftMessage()));
@@ -100,17 +101,18 @@ public void deleteDraftMessageIfExist_Should_callDelete_When_messageForUserAndGr
verify(this.draftMessageRepository, times(1)).delete(any());
}
- @Test(expected = InternalServerErrorException.class)
- public void saveDraftMessage_Should_throwInternalServerError_When_encryptionServiceThrowsCustomCryptoException()
- throws CustomCryptoException {
- when(this.encryptionService.encrypt(any(), any()))
- .thenThrow(new CustomCryptoException(new Exception()));
+ @Test
+ void saveDraftMessage_Should_throwInternalServerError_When_encryptionServiceThrowsCustomCryptoException() {
+ assertThrows(InternalServerErrorException.class, () -> {
+ when(this.encryptionService.encrypt(any(), any()))
+ .thenThrow(new CustomCryptoException(new Exception()));
- this.draftMessageService.saveDraftMessage("message", "rcGroupId", "text");
+ this.draftMessageService.saveDraftMessage("message", "rcGroupId", "text");
+ });
}
@Test
- public void findAndDecryptDraftMessage_Should_returnNull_When_noDraftMessageIsPresent() {
+ void findAndDecryptDraftMessage_Should_returnNull_When_noDraftMessageIsPresent() {
var draftMessage = this.draftMessageService.findAndDecryptDraftMessage("rcGroupId");
assertThat(draftMessage.isEmpty(), is(true));
@@ -118,7 +120,7 @@ public void findAndDecryptDraftMessage_Should_returnNull_When_noDraftMessageIsPr
}
@Test
- public void findAndDecryptDraftMessage_Should_returnNull_When_rcGroupIdIsNull() {
+ void findAndDecryptDraftMessage_Should_returnNull_When_rcGroupIdIsNull() {
var draftMessage = this.draftMessageService.findAndDecryptDraftMessage(null);
assertThat(draftMessage.isEmpty(), is(true));
@@ -126,7 +128,7 @@ public void findAndDecryptDraftMessage_Should_returnNull_When_rcGroupIdIsNull()
}
@Test
- public void findAndDecryptDraftMessage_Should_returnDecryptedMessage_When_draftMessageIsPresent()
+ void findAndDecryptDraftMessage_Should_returnDecryptedMessage_When_draftMessageIsPresent()
throws CustomCryptoException {
var draftMessage = DraftMessage.builder().message("encrypted").build();
when(this.draftMessageRepository.findByUserIdAndRcGroupId(any(), any()))
@@ -140,15 +142,16 @@ public void findAndDecryptDraftMessage_Should_returnDecryptedMessage_When_draftM
verify(this.encryptionService, times(1)).decrypt("encrypted", "rcGroupId");
}
- @Test(expected = InternalServerErrorException.class)
- public void findAndDecryptDraftMessage_Should_throwInternalServerError_When_encryptionServiceThrowsCustomCryptoException()
- throws CustomCryptoException {
- when(this.draftMessageRepository.findByUserIdAndRcGroupId(any(), any()))
- .thenReturn(Optional.of(new DraftMessage()));
- when(this.encryptionService.decrypt(any(), any())).thenThrow(
- new CustomCryptoException(new Exception()));
-
- this.draftMessageService.findAndDecryptDraftMessage("rcGroupId");
+ @Test
+ void findAndDecryptDraftMessage_Should_throwInternalServerError_When_encryptionServiceThrowsCustomCryptoException() {
+ assertThrows(InternalServerErrorException.class, () -> {
+ when(this.draftMessageRepository.findByUserIdAndRcGroupId(any(), any()))
+ .thenReturn(Optional.of(new DraftMessage()));
+ when(this.encryptionService.decrypt(any(), any())).thenThrow(
+ new CustomCryptoException(new Exception()));
+
+ this.draftMessageService.findAndDecryptDraftMessage("rcGroupId");
+ });
}
}
diff --git a/src/test/java/de/caritas/cob/messageservice/api/service/EncryptionServiceTest.java b/src/test/java/de/caritas/cob/messageservice/api/service/EncryptionServiceTest.java
index ba0e742..9874c0d 100644
--- a/src/test/java/de/caritas/cob/messageservice/api/service/EncryptionServiceTest.java
+++ b/src/test/java/de/caritas/cob/messageservice/api/service/EncryptionServiceTest.java
@@ -1,21 +1,22 @@
package de.caritas.cob.messageservice.api.service;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+import org.junit.jupiter.api.Assertions;
+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 de.caritas.cob.messageservice.api.exception.CustomCryptoException;
import org.springframework.test.util.ReflectionTestUtils;
-@RunWith(MockitoJUnitRunner.class)
-public class EncryptionServiceTest {
+@ExtendWith(MockitoExtension.class)
+class EncryptionServiceTest {
private final String KEY_MASTER = "MasterKeyTestKey";
private final String KEY_APPLICATION = "ApplicationTestKey";
@@ -32,8 +33,8 @@ public class EncryptionServiceTest {
@Mock
private LogService logService;
- @Before
- public void setup() throws NoSuchFieldException {
+ @BeforeEach
+ void setup() throws NoSuchFieldException {
ReflectionTestUtils.setField(encryptionService, "fragment_applicationKey", KEY_APPLICATION);
@@ -41,52 +42,54 @@ public void setup() throws NoSuchFieldException {
}
@Test
- public void check_setup() {
- assertEquals("MasterKey was not properly set", KEY_MASTER, encryptionService.getMasterKey());
- assertEquals("ApplicationKey was not properly set", KEY_APPLICATION,
- encryptionService.getApplicationKey());
+ void check_setup() {
+ assertEquals(KEY_MASTER, encryptionService.getMasterKey(), "MasterKey was not properly set");
+ assertEquals(KEY_APPLICATION,
+ encryptionService.getApplicationKey(),
+ "ApplicationKey was not properly set");
}
@Test
- public void updateMasterKey_Should_UpdateMasterKeyFragment() {
+ 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 encrypt_Should_ReturnEncryptedText_WhenProvidedWithValidParameters()
+ void encrypt_Should_ReturnEncryptedText_WhenProvidedWithValidParameters()
throws CustomCryptoException {
String encryptMessage = encryptionService.encrypt(MESSAGE_PLAIN, KEY_SESSION);
- assertEquals("Did not get the expected encryption result.", MESSAGE_ENCRYPTED, encryptMessage);
+ assertEquals(MESSAGE_ENCRYPTED, encryptMessage, "Did not get the expected encryption result.");
}
@Test
- public void encrypt_Should_ReturnWrongEncryptedText_WhenProvidedWithInvalidParameters()
+ void encrypt_Should_ReturnWrongEncryptedText_WhenProvidedWithInvalidParameters()
throws CustomCryptoException {
String encryptMessage = encryptionService.encrypt(MESSAGE_PLAIN, KEY_SESSION_WRONG);
- Assert.assertNotEquals("Did not get the expected encryption result.", MESSAGE_ENCRYPTED,
- encryptMessage);
+ Assertions.assertNotEquals(MESSAGE_ENCRYPTED,
+ encryptMessage,
+ "Did not get the expected encryption result.");
}
@Test
- public void decrypt_Should_ReturnDecryptedText_WhenProvidedWithValidParameters()
+ void decrypt_Should_ReturnDecryptedText_WhenProvidedWithValidParameters()
throws CustomCryptoException {
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
- public void decrypt_Should_ReturnWrongDecryptedText_WhenProvidedWithInvalidParameters() {
+ void decrypt_Should_ReturnWrongDecryptedText_WhenProvidedWithInvalidParameters() {
try {
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");
}
}
@Test
- public void decrypt_Should_ReturnNull_WhenMessageIsNull() throws CustomCryptoException {
+ void decrypt_Should_ReturnNull_WhenMessageIsNull() throws CustomCryptoException {
assertNull(encryptionService.decrypt(null, KEY_MASTER));
}
diff --git a/src/test/java/de/caritas/cob/messageservice/api/service/LiveEventNotificationServiceTest.java b/src/test/java/de/caritas/cob/messageservice/api/service/LiveEventNotificationServiceTest.java
index 2cafc50..a4ff9d2 100644
--- a/src/test/java/de/caritas/cob/messageservice/api/service/LiveEventNotificationServiceTest.java
+++ b/src/test/java/de/caritas/cob/messageservice/api/service/LiveEventNotificationServiceTest.java
@@ -14,17 +14,17 @@
import de.caritas.cob.messageservice.userservice.generated.ApiClient;
import de.caritas.cob.messageservice.userservice.generated.web.LiveproxyControllerApi;
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.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestClientException;
-@RunWith(MockitoJUnitRunner.class)
-public class LiveEventNotificationServiceTest {
+@ExtendWith(MockitoExtension.class)
+class LiveEventNotificationServiceTest {
@InjectMocks private LiveEventNotificationService liveEventNotificationService;
@@ -32,13 +32,13 @@ public class LiveEventNotificationServiceTest {
@Mock private ServiceHelper serviceHelper;
@Mock private ApiControllerFactory clientFactory;
- @Before
- public void setup() {
+ @BeforeEach
+ void setup() {
when(clientFactory.liveproxyControllerApi()).thenReturn(liveproxyControllerApi);
}
@Test
- public void sendLiveEvent_Should_notTriggerLiveEvent_When_rcGroupIdIsNull() {
+ void sendLiveEvent_Should_notTriggerLiveEvent_When_rcGroupIdIsNull() {
this.liveEventNotificationService.sendLiveEvent(null, null, Optional.empty());
verifyNoMoreInteractions(this.liveproxyControllerApi);
@@ -46,7 +46,7 @@ public void sendLiveEvent_Should_notTriggerLiveEvent_When_rcGroupIdIsNull() {
}
@Test
- public void sendLiveEvent_Should_notTriggerLiveEvent_When_rcGroupIdIsEmpty() {
+ void sendLiveEvent_Should_notTriggerLiveEvent_When_rcGroupIdIsEmpty() {
this.liveEventNotificationService.sendLiveEvent(null, null, Optional.empty());
verifyNoMoreInteractions(this.liveproxyControllerApi);
@@ -54,7 +54,7 @@ public void sendLiveEvent_Should_notTriggerLiveEvent_When_rcGroupIdIsEmpty() {
}
@Test
- public void sendLiveEvent_Should_triggerLiveEventWithHeaders_When_rcGroupIdIsValid() {
+ void sendLiveEvent_Should_triggerLiveEventWithHeaders_When_rcGroupIdIsValid() {
ApiClient apiClient = mock(ApiClient.class);
when(this.liveproxyControllerApi.getApiClient()).thenReturn(apiClient);
HttpHeaders headers = new HttpHeaders();
@@ -71,7 +71,7 @@ public void sendLiveEvent_Should_triggerLiveEventWithHeaders_When_rcGroupIdIsVal
}
@Test
- public void sendLiveEvent_Should_logError_When_apiClientThrowsRestClientException() {
+ void sendLiveEvent_Should_logError_When_apiClientThrowsRestClientException() {
doThrow(new RestClientException(""))
.when(this.liveproxyControllerApi)
.sendLiveEvent(anyString());
diff --git a/src/test/java/de/caritas/cob/messageservice/api/service/RocketChatServiceTest.java b/src/test/java/de/caritas/cob/messageservice/api/service/RocketChatServiceTest.java
index bd849e6..e211c0d 100644
--- a/src/test/java/de/caritas/cob/messageservice/api/service/RocketChatServiceTest.java
+++ b/src/test/java/de/caritas/cob/messageservice/api/service/RocketChatServiceTest.java
@@ -12,7 +12,8 @@
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
@@ -43,13 +44,13 @@
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.ArgumentMatchers;
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.HttpEntity;
import org.springframework.http.HttpMethod;
@@ -60,8 +61,8 @@
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
-@RunWith(MockitoJUnitRunner.class)
-public class RocketChatServiceTest {
+@ExtendWith(MockitoExtension.class)
+class RocketChatServiceTest {
private static final int RC_OFFSET = 0;
private static final int RC_COUNT = 0;
@@ -95,8 +96,8 @@ public class RocketChatServiceTest {
@Mock
private Logger logger;
- @Before
- public void setup() throws NoSuchFieldException, SecurityException {
+ @BeforeEach
+ void setup() throws NoSuchFieldException, SecurityException {
ReflectionTestUtils.setField(rocketChatService, "rcHeaderAuthToken", RC_TOKEN);
ReflectionTestUtils.setField(rocketChatService, "rcHeaderUserId", RC_USER_ID);
ReflectionTestUtils.setField(rocketChatService, "rcQueryParamRoomId", RC_GROUP_ID);
@@ -110,48 +111,51 @@ public void setup() throws NoSuchFieldException, SecurityException {
}
- @Test(expected = InternalServerErrorException.class)
- public void getGroupMessages_Should_ThrowInternalServerErrorException_When_BuildMessageStreamUriFails()
- throws NoSuchFieldException {
+ @Test
+ void getGroupMessages_Should_ThrowInternalServerErrorException_When_BuildMessageStreamUriFails() {
+ assertThrows(InternalServerErrorException.class, () -> {
- ReflectionTestUtils.setField(rocketChatService, "rcGetGroupMessageUrl", (Object[]) null);
- rocketChatService.getGroupMessages(RC_TOKEN, RC_USER_ID, RC_GROUP_ID, 0, 0, Instant.now());
+ ReflectionTestUtils.setField(rocketChatService, "rcGetGroupMessageUrl", (Object[]) null);
+ rocketChatService.getGroupMessages(RC_TOKEN, RC_USER_ID, RC_GROUP_ID, 0, 0, Instant.now());
+ });
}
- @Test(expected = InternalServerErrorException.class)
- public void getGroupMessages_Should_ThrowInternalServerErrorException_When_RocketChatRequestFails()
- throws NoSuchFieldException {
- ReflectionTestUtils.setField(rocketChatService, "rcGetGroupMessageUrl", "http://localhost/api/v1/groups.messages");
+ @Test
+ void getGroupMessages_Should_ThrowInternalServerErrorException_When_RocketChatRequestFails() {
+ assertThrows(InternalServerErrorException.class, () -> {
+ ReflectionTestUtils.setField(rocketChatService, "rcGetGroupMessageUrl", "http://localhost/api/v1/groups.messages");
- HttpClientErrorException ex = new HttpClientErrorException(HttpStatus.BAD_REQUEST);
- when(restTemplate.exchange(any(), any(HttpMethod.class), any(),
- ArgumentMatchers.>any())).thenThrow(ex);
+ HttpClientErrorException ex = new HttpClientErrorException(HttpStatus.BAD_REQUEST);
+ when(restTemplate.exchange(any(), any(HttpMethod.class), any(),
+ ArgumentMatchers.>any())).thenThrow(ex);
- rocketChatService.getGroupMessages(RC_TOKEN, RC_USER_ID, RC_GROUP_ID, 0, 0, Instant.now());
+ rocketChatService.getGroupMessages(RC_TOKEN, RC_USER_ID, RC_GROUP_ID, 0, 0, Instant.now());
+ });
}
- @Test(expected = InternalServerErrorException.class)
- public void getGroupMessages_Should_ThrowInternalServerErrorException_When_DecryptionOfMessageFails()
- throws NoSuchFieldException, CustomCryptoException {
- ReflectionTestUtils.setField(rocketChatService, "rcGetGroupMessageUrl", "http://localhost/api/v1/groups.messages");
-
- EasyRandom easyRandom = new EasyRandom();
- MessageStreamDTO messageStreamDTO = easyRandom.nextObject(MessageStreamDTO.class);
- messageStreamDTO.setMessages(easyRandom.objects(MessagesDTO.class, 5)
- .collect(Collectors.toList()));
- ResponseEntity response = new ResponseEntity<>(messageStreamDTO,
- HttpStatus.OK);
- CustomCryptoException exception = new CustomCryptoException(new Exception());
-
- when(restTemplate.exchange(any(), any(HttpMethod.class), any(),
- ArgumentMatchers.>any())).thenReturn(response);
- when(encryptionService.decrypt(anyString(), anyString())).thenThrow(exception);
-
- rocketChatService.getGroupMessages(RC_TOKEN, RC_USER_ID, RC_GROUP_ID, 0, 0, Instant.now());
+ @Test
+ void getGroupMessages_Should_ThrowInternalServerErrorException_When_DecryptionOfMessageFails() {
+ assertThrows(InternalServerErrorException.class, () -> {
+ ReflectionTestUtils.setField(rocketChatService, "rcGetGroupMessageUrl", "http://localhost/api/v1/groups.messages");
+
+ EasyRandom easyRandom = new EasyRandom();
+ MessageStreamDTO messageStreamDTO = easyRandom.nextObject(MessageStreamDTO.class);
+ messageStreamDTO.setMessages(easyRandom.objects(MessagesDTO.class, 5)
+ .collect(Collectors.toList()));
+ ResponseEntity response = new ResponseEntity<>(messageStreamDTO,
+ HttpStatus.OK);
+ CustomCryptoException exception = new CustomCryptoException(new Exception());
+
+ when(restTemplate.exchange(any(), any(HttpMethod.class), any(),
+ ArgumentMatchers.>any())).thenReturn(response);
+ when(encryptionService.decrypt(anyString(), anyString())).thenThrow(exception);
+
+ rocketChatService.getGroupMessages(RC_TOKEN, RC_USER_ID, RC_GROUP_ID, 0, 0, Instant.now());
+ });
}
@Test
- public void getGroupMessages_Should_ReturnMessageStreamDTO_When_ProvidedWithValidParameters()
+ void getGroupMessages_Should_ReturnMessageStreamDTO_When_ProvidedWithValidParameters()
throws NoSuchFieldException {
ReflectionTestUtils.setField(rocketChatService, "rcGetGroupMessageUrl", "http://localhost/api/v1/groups.messages");
@@ -168,7 +172,7 @@ public void getGroupMessages_Should_ReturnMessageStreamDTO_When_ProvidedWithVali
}
@Test
- public void getGroupMessages_Should_DecryptAllMessages() throws CustomCryptoException {
+ void getGroupMessages_Should_DecryptAllMessages() throws CustomCryptoException {
ReflectionTestUtils.setField(rocketChatService, "rcGetGroupMessageUrl", "http://localhost/api/v1/groups.messages");
EasyRandom easyRandom = new EasyRandom();
@@ -186,7 +190,7 @@ public void getGroupMessages_Should_DecryptAllMessages() throws CustomCryptoExce
}
@Test
- public void getGroupMessages_Should_SetForwardAsMessageType_ForForwardedMessages()
+ void getGroupMessages_Should_SetForwardAsMessageType_ForForwardedMessages()
throws NoSuchFieldException {
ReflectionTestUtils.setField(rocketChatService, "rcGetGroupMessageUrl", "http://localhost/api/v1/groups.messages");
EasyRandom easyRandom = new EasyRandom();
@@ -216,7 +220,7 @@ public void getGroupMessages_Should_SetForwardAsMessageType_ForForwardedMessages
}
@Test
- public void getGroupMessages_Should_SetVideocallAsMessageType_ForVideocallMessages()
+ void getGroupMessages_Should_SetVideocallAsMessageType_ForVideocallMessages()
throws NoSuchFieldException {
ReflectionTestUtils.setField(rocketChatService, "rcGetGroupMessageUrl", "http://localhost/api/v1/groups.messages");
@@ -247,7 +251,7 @@ public void getGroupMessages_Should_SetVideocallAsMessageType_ForVideocallMessag
}
@Test
- public void getGroupMessages_Should_SetFurtherStepsAsMessageType_ForFurtherStepsMessages()
+ void getGroupMessages_Should_SetFurtherStepsAsMessageType_ForFurtherStepsMessages()
throws NoSuchFieldException {
ReflectionTestUtils.setField(rocketChatService, "rcGetGroupMessageUrl", "http://localhost/api/v1/groups.messages");
EasyRandom easyRandom = new EasyRandom();
@@ -279,7 +283,7 @@ public void getGroupMessages_Should_SetFurtherStepsAsMessageType_ForFurtherSteps
}
@Test
- public void postGroupMessage_Should_ReturnRocketChatPostMessageException_When_HttpRequestFails()
+ void postGroupMessage_Should_ReturnRocketChatPostMessageException_When_HttpRequestFails()
throws CustomCryptoException {
RocketChatSendMessageException ex = new RocketChatSendMessageException(new Exception("reason"));
@@ -297,24 +301,26 @@ public void postGroupMessage_Should_ReturnRocketChatPostMessageException_When_Ht
rocketChatService.postGroupMessage(createGroupMessage());
fail("Expected exception: InternalServerErrorException");
} catch (InternalServerErrorException internalServerErrorException) {
- assertTrue("Expected InternalServerErrorException thrown", true);
+ assertTrue(true, "Expected InternalServerErrorException thrown");
}
}
- @Test(expected = RocketChatBadRequestException.class)
- public void getGroupInfo_Should_ReturnRocketChatBadRequestException_When_HttpRequestFails() {
+ @Test
+ void getGroupInfo_Should_ReturnRocketChatBadRequestException_When_HttpRequestFails() {
+ assertThrows(RocketChatBadRequestException.class, () -> {
- HttpClientErrorException ex = new HttpClientErrorException(HttpStatus.BAD_REQUEST);
+ HttpClientErrorException ex = new HttpClientErrorException(HttpStatus.BAD_REQUEST);
- when(restTemplate.exchange(
- any(), any(HttpMethod.class), any(), ArgumentMatchers.>any()))
- .thenThrow(ex);
+ when(restTemplate.exchange(
+ any(), any(HttpMethod.class), any(), ArgumentMatchers.>any()))
+ .thenThrow(ex);
- rocketChatService.getGroupInfo(RC_TOKEN, RC_USER_ID, RC_GROUP_ID);
+ rocketChatService.getGroupInfo(RC_TOKEN, RC_USER_ID, RC_GROUP_ID);
+ });
}
@Test
- public void postGroupMessage_Should_ReturnPostMessageResponseDTO_When_ProvidedWithValidParameters()
+ void postGroupMessage_Should_ReturnPostMessageResponseDTO_When_ProvidedWithValidParameters()
throws CustomCryptoException {
SendMessageResponseDTO response = new SendMessageResponseDTO(new SendMessageResultDTO(), true,
@@ -332,7 +338,7 @@ public void postGroupMessage_Should_ReturnPostMessageResponseDTO_When_ProvidedWi
}
@Test
- public void postGroupMessage_should_not_encrypt_text_of_e2e_encrypted_messages()
+ void postGroupMessage_should_not_encrypt_text_of_e2e_encrypted_messages()
throws CustomCryptoException {
var e2eEncryptedMessage = ChatMessage.builder().rcToken(RC_TOKEN).rcUserId(RC_USER_ID)
.rcGroupId(RC_GROUP_ID).text("e2eEncryptedMessage")
@@ -347,7 +353,7 @@ public void postGroupMessage_should_not_encrypt_text_of_e2e_encrypted_messages()
* Method: markGroupAsReadForSystemUser
*/
@Test
- public void markGroupAsReadForSystemUser_Should_LogError_When_MarkGroupAsReadFails()
+ void markGroupAsReadForSystemUser_Should_LogError_When_MarkGroupAsReadFails()
throws SecurityException, RocketChatUserNotInitializedException {
when(rcCredentialsHelper.getSystemUser()).thenReturn(RCC_SYSTEM_USER);
@@ -360,12 +366,12 @@ public void markGroupAsReadForSystemUser_Should_LogError_When_MarkGroupAsReadFai
rocketChatService.markGroupAsReadForSystemUser(RC_GROUP_ID);
fail("Expected exception: InternalServerErrorException");
} catch (InternalServerErrorException internalServerErrorException) {
- assertTrue("Expected InternalServerErrorException thrown", true);
+ assertTrue(true, "Expected InternalServerErrorException thrown");
}
}
@Test
- public void markGroupAsReadForSystemUser_Should_MarkGroupAsRead_When_ProvidedWithValidGroupId()
+ void markGroupAsReadForSystemUser_Should_MarkGroupAsRead_When_ProvidedWithValidGroupId()
throws SecurityException, RocketChatUserNotInitializedException {
when(rcCredentialsHelper.getSystemUser()).thenReturn(RCC_SYSTEM_USER);
@@ -380,7 +386,7 @@ public void markGroupAsReadForSystemUser_Should_MarkGroupAsRead_When_ProvidedWit
}
@Test
- public void markGroupAsReadForSystemUser_Should_NotInteractWithRestTemplate_When_ProvidedWithInvalidRocketChatSystemUserCredentials()
+ void markGroupAsReadForSystemUser_Should_NotInteractWithRestTemplate_When_ProvidedWithInvalidRocketChatSystemUserCredentials()
throws SecurityException, RocketChatUserNotInitializedException {
when(rcCredentialsHelper.getSystemUser()).thenReturn(INVALID_RCC_SYSTEM_USER);
@@ -390,18 +396,19 @@ public void markGroupAsReadForSystemUser_Should_NotInteractWithRestTemplate_When
verifyNoInteractions(restTemplate);
}
- @Test(expected = InternalServerErrorException.class)
- public void markGroupAsReadForSystemUser_Should_ThrowInternalServerError_When_ProvidedWithOutChatSystemUserCredentials()
- throws SecurityException, RocketChatUserNotInitializedException {
+ @Test
+ void markGroupAsReadForSystemUser_Should_ThrowInternalServerError_When_ProvidedWithOutChatSystemUserCredentials() {
+ assertThrows(InternalServerErrorException.class, () -> {
- when(rcCredentialsHelper.getSystemUser())
- .thenThrow(new RocketChatUserNotInitializedException(""));
+ when(rcCredentialsHelper.getSystemUser())
+ .thenThrow(new RocketChatUserNotInitializedException(""));
- rocketChatService.markGroupAsReadForSystemUser(RC_GROUP_ID);
+ rocketChatService.markGroupAsReadForSystemUser(RC_GROUP_ID);
+ });
}
@Test
- public void postAliasOnlyMessageAsSystemUser_Should_postGroupMessage() throws Exception {
+ void postAliasOnlyMessageAsSystemUser_Should_postGroupMessage() throws Exception {
RocketChatCredentials rocketChatCredentials =
new EasyRandom().nextObject(RocketChatCredentials.class);
when(this.rcCredentialsHelper.getSystemUser()).thenReturn(rocketChatCredentials);
@@ -413,17 +420,18 @@ public void postAliasOnlyMessageAsSystemUser_Should_postGroupMessage() throws Ex
verify(this.restTemplate, times(1)).postForObject(anyString(), any(HttpEntity.class), any());
}
- @Test(expected = InternalServerErrorException.class)
- public void postAliasOnlyMessageAsSystemUser_Should_throwInternalServerErrorException_When_CustomCryptoExceptionIsThrown()
- throws CustomCryptoException, RocketChatUserNotInitializedException {
- EasyRandom easyRandom = new EasyRandom();
- RocketChatCredentials rocketChatCredentials = easyRandom
- .nextObject(RocketChatCredentials.class);
- AliasMessageDTO aliasMessageDTO = easyRandom.nextObject(AliasMessageDTO.class);
- when(this.rcCredentialsHelper.getSystemUser()).thenReturn(rocketChatCredentials);
- when(encryptionService.encrypt(anyString(), anyString()))
- .thenThrow(new CustomCryptoException(new Exception()));
-
- this.rocketChatService.postAliasOnlyMessageAsSystemUser(RC_GROUP_ID, aliasMessageDTO);
+ @Test
+ void postAliasOnlyMessageAsSystemUser_Should_throwInternalServerErrorException_When_CustomCryptoExceptionIsThrown() {
+ assertThrows(InternalServerErrorException.class, () -> {
+ EasyRandom easyRandom = new EasyRandom();
+ RocketChatCredentials rocketChatCredentials = easyRandom
+ .nextObject(RocketChatCredentials.class);
+ AliasMessageDTO aliasMessageDTO = easyRandom.nextObject(AliasMessageDTO.class);
+ when(this.rcCredentialsHelper.getSystemUser()).thenReturn(rocketChatCredentials);
+ when(encryptionService.encrypt(anyString(), anyString()))
+ .thenThrow(new CustomCryptoException(new Exception()));
+
+ this.rocketChatService.postAliasOnlyMessageAsSystemUser(RC_GROUP_ID, aliasMessageDTO);
+ });
}
}
diff --git a/src/test/java/de/caritas/cob/messageservice/api/service/helper/RocketChatCredentialsHelperTest.java b/src/test/java/de/caritas/cob/messageservice/api/service/helper/RocketChatCredentialsHelperTest.java
index 61e398a..c451faf 100644
--- a/src/test/java/de/caritas/cob/messageservice/api/service/helper/RocketChatCredentialsHelperTest.java
+++ b/src/test/java/de/caritas/cob/messageservice/api/service/helper/RocketChatCredentialsHelperTest.java
@@ -1,21 +1,21 @@
package de.caritas.cob.messageservice.api.service.helper;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+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;
import java.time.LocalDateTime;
-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;
@@ -31,8 +31,8 @@
import de.caritas.cob.messageservice.api.model.rocket.chat.login.LoginResponseDTO;
import de.caritas.cob.messageservice.api.model.rocket.chat.logout.LogoutResponseDTO;
-@RunWith(MockitoJUnitRunner.class)
-public class RocketChatCredentialsHelperTest {
+@ExtendWith(MockitoExtension.class)
+class RocketChatCredentialsHelperTest {
/**
* FIELD Names
@@ -114,8 +114,8 @@ public class RocketChatCredentialsHelperTest {
@Mock
private RestTemplate restTemplate;
- @Before
- public void setup() throws NoSuchFieldException {
+ @BeforeEach
+ void setup() throws NoSuchFieldException {
ReflectionTestUtils.setField(rcCredentialHelper, FIELD_NAME_SYSTEM_USERNAME, SYSTEM_USER_USERNAME);
ReflectionTestUtils.setField(rcCredentialHelper, FIELD_NAME_SYSTEM_PASSWORD, SYSTEM_USER_PW);
ReflectionTestUtils.setField(rcCredentialHelper, FIELD_NAME_ROCKET_CHAT_API_POST_USER_LOGIN, RC_URL_CHAT_USER_LOGIN);
@@ -131,7 +131,7 @@ public void setup() throws NoSuchFieldException {
**/
@Test
- public void updateCredentials_Should_LoginAUsers_WhenNoUsersAreLoggedIn()
+ void updateCredentials_Should_LoginAUsers_WhenNoUsersAreLoggedIn()
throws RocketChatUserNotInitializedException {
// Prepare Header for Requests
HttpHeaders headers = new HttpHeaders();
@@ -159,7 +159,7 @@ public void updateCredentials_Should_LoginAUsers_WhenNoUsersAreLoggedIn()
}
@Test
- public void updateCredentials_Should_LoginBUsers_WhenAUsersAreLoggedIn()
+ void updateCredentials_Should_LoginBUsers_WhenAUsersAreLoggedIn()
throws NoSuchFieldException, RocketChatUserNotInitializedException {
// Prepare Header for Requests
HttpHeaders headers = new HttpHeaders();
@@ -197,7 +197,7 @@ public void updateCredentials_Should_LoginBUsers_WhenAUsersAreLoggedIn()
}
@Test
- public void updateCredentials_Should_LogoutAndReLoginBUsers_WhenAllUsersArePresent()
+ void updateCredentials_Should_LogoutAndReLoginBUsers_WhenAllUsersArePresent()
throws NoSuchFieldException, RocketChatUserNotInitializedException {
HttpHeaders headers = new HttpHeaders();
@@ -216,7 +216,7 @@ public void updateCredentials_Should_LogoutAndReLoginBUsers_WhenAllUsersArePrese
// prepare logout intercept for system user
HttpHeaders headersLogoutSys = new HttpHeaders();
- headersLogoutSys.setContentType(MediaType.APPLICATION_JSON_UTF8);
+ headersLogoutSys.setContentType(MediaType.APPLICATION_JSON);
headersLogoutSys.add(FIELD_VALUE_ROCKET_CHAT_HEADER_AUTH_TOKEN, SYSTEM_USER_A_TOKEN);
headersLogoutSys.add(FIELD_VALUE_ROCKET_CHAT_HEADER_USER_ID, SYSTEM_USER_A_ID);
HttpEntity requestSysLogout = new HttpEntity(headersLogoutSys);
@@ -258,17 +258,17 @@ public void updateCredentials_Should_LogoutAndReLoginBUsers_WhenAllUsersArePrese
**/
@Test
- public void getSystemUser_Should_ThrowRocketChatUserNotInitializedException_WhenNoUserIsInitialized() {
+ void getSystemUser_Should_ThrowRocketChatUserNotInitializedException_WhenNoUserIsInitialized() {
try {
rcCredentialHelper.getSystemUser();
fail("Expected exception: RocketChatUserNotInitializedException");
} catch (RocketChatUserNotInitializedException ex) {
- assertTrue("Excepted RocketChatUserNotInitializedException thrown", true);
+ assertTrue(true, "Excepted RocketChatUserNotInitializedException thrown");
}
}
@Test
- public void getSystemUser_Should_ReturnUserA_WhenOnlyUserAIsInitialized()
+ void getSystemUser_Should_ReturnUserA_WhenOnlyUserAIsInitialized()
throws NoSuchFieldException, RocketChatUserNotInitializedException {
RocketChatCredentials sysUserA = new RocketChatCredentials(SYSTEM_USER_A_ID,
@@ -282,7 +282,7 @@ public void getSystemUser_Should_ReturnUserA_WhenOnlyUserAIsInitialized()
}
@Test
- public void getSystemUser_Should_ReturnUserB_WhenOnlyUserBIsInitialized()
+ void getSystemUser_Should_ReturnUserB_WhenOnlyUserBIsInitialized()
throws NoSuchFieldException, RocketChatUserNotInitializedException {
RocketChatCredentials sysUserB = new RocketChatCredentials(SYSTEM_USER_B_ID,
@@ -296,7 +296,7 @@ public void getSystemUser_Should_ReturnUserB_WhenOnlyUserBIsInitialized()
}
@Test
- public void getSystemUser_Should_ReturnUserA_WhenUserAIsNewer()
+ void getSystemUser_Should_ReturnUserA_WhenUserAIsNewer()
throws NoSuchFieldException, RocketChatUserNotInitializedException {
// Prepare User A
@@ -319,7 +319,7 @@ public void getSystemUser_Should_ReturnUserA_WhenUserAIsNewer()
}
@Test
- public void getSystemUser_Should_ReturnUserB_WhenUserBIsNewer()
+ void getSystemUser_Should_ReturnUserB_WhenUserBIsNewer()
throws NoSuchFieldException, RocketChatUserNotInitializedException {
// Prepare User A - 5 minutes older than User B
diff --git a/src/test/java/de/caritas/cob/messageservice/api/service/helper/ServiceHelperTest.java b/src/test/java/de/caritas/cob/messageservice/api/service/helper/ServiceHelperTest.java
index 1169463..d1cc7a1 100644
--- a/src/test/java/de/caritas/cob/messageservice/api/service/helper/ServiceHelperTest.java
+++ b/src/test/java/de/caritas/cob/messageservice/api/service/helper/ServiceHelperTest.java
@@ -1,8 +1,8 @@
package de.caritas.cob.messageservice.api.service.helper;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import de.caritas.cob.messageservice.api.helper.AuthenticatedUser;
import de.caritas.cob.messageservice.api.service.TenantHeaderSupplier;
@@ -10,13 +10,13 @@
import java.util.Optional;
import jakarta.servlet.http.HttpServletRequest;
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.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
@@ -24,8 +24,8 @@
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
-@RunWith(MockitoJUnitRunner.class)
-public class ServiceHelperTest {
+@ExtendWith(MockitoExtension.class)
+class ServiceHelperTest {
private final String FIELD_NAME_CSRF_TOKEN_HEADER_PROPERTY = "csrfHeaderProperty";
private final String FIELD_NAME_CSRF_TOKEN_COOKIE_PROPERTY = "csrfCookieProperty";
@@ -49,8 +49,8 @@ public class ServiceHelperTest {
@Mock
private Enumeration headers;
- @Before
- public void setup() throws NoSuchFieldException, SecurityException {
+ @BeforeEach
+ void setup() throws NoSuchFieldException, SecurityException {
givenRequestContextIsSet();
ReflectionTestUtils.setField(serviceHelper, FIELD_NAME_CSRF_TOKEN_HEADER_PROPERTY, CSRF_TOKEN_HEADER_VALUE);
ReflectionTestUtils.setField(serviceHelper, FIELD_NAME_CSRF_TOKEN_COOKIE_PROPERTY, CSRF_TOKEN_COOKIE_VALUE);
@@ -65,16 +65,16 @@ private void givenRequestContextIsSet() {
*/
@Test
- public void getKeycloakAndCsrfHttpHeaders_Should_Return_HeaderWithCorrectContentType() {
+ void getKeycloakAndCsrfHttpHeaders_Should_Return_HeaderWithCorrectContentType() {
HttpHeaders result = serviceHelper.getKeycloakAndCsrfAndOriginHttpHeaders(
RandomStringUtils.randomAlphanumeric(16), Optional.empty());
- assertEquals(MediaType.APPLICATION_JSON_UTF8, result.getContentType());
+ assertEquals(MediaType.APPLICATION_JSON, result.getContentType());
}
@Test
- public void getKeycloakAndCsrfHttpHeaders_Should_Return_HeaderWithCookiePropertyNameFromProperties() {
+ void getKeycloakAndCsrfHttpHeaders_Should_Return_HeaderWithCookiePropertyNameFromProperties() {
HttpHeaders result = serviceHelper.getKeycloakAndCsrfAndOriginHttpHeaders(
RandomStringUtils.randomAlphanumeric(16), Optional.empty());
@@ -83,7 +83,7 @@ public void getKeycloakAndCsrfHttpHeaders_Should_Return_HeaderWithCookieProperty
}
@Test
- public void getKeycloakAndCsrfHttpHeaders_Should_Return_HeaderWithPropertyNameFromProperties() {
+ void getKeycloakAndCsrfHttpHeaders_Should_Return_HeaderWithPropertyNameFromProperties() {
HttpHeaders result = serviceHelper.getKeycloakAndCsrfAndOriginHttpHeaders(
RandomStringUtils.randomAlphanumeric(16), Optional.empty());
@@ -92,7 +92,7 @@ public void getKeycloakAndCsrfHttpHeaders_Should_Return_HeaderWithPropertyNameFr
}
@Test
- public void getKeycloakAndCsrfHttpHeaders_Should_Return_HeaderWithBearerAuthorization() {
+ void getKeycloakAndCsrfHttpHeaders_Should_Return_HeaderWithBearerAuthorization() {
HttpHeaders result = serviceHelper.getKeycloakAndCsrfAndOriginHttpHeaders(
RandomStringUtils.randomAlphanumeric(16), Optional.empty());
diff --git a/src/test/java/de/caritas/cob/messageservice/api/service/statistics/StatisticsServiceIT.java b/src/test/java/de/caritas/cob/messageservice/api/service/statistics/StatisticsServiceIT.java
index 36a6f3e..69c983c 100644
--- a/src/test/java/de/caritas/cob/messageservice/api/service/statistics/StatisticsServiceIT.java
+++ b/src/test/java/de/caritas/cob/messageservice/api/service/statistics/StatisticsServiceIT.java
@@ -19,8 +19,7 @@
import java.time.OffsetDateTime;
import java.util.Objects;
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;
@@ -28,14 +27,12 @@
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.util.ReflectionTestUtils;
-@RunWith(SpringRunner.class)
@TestPropertySource(properties = "spring.profiles.active=testing")
@SpringBootTest(classes = MessageServiceApplication.class)
@AutoConfigureTestDatabase(replace = Replace.ANY)
-public class StatisticsServiceIT {
+class StatisticsServiceIT {
private static final long MAX_TIMEOUT_MILLIS = 5000;
@@ -43,7 +40,7 @@ public class StatisticsServiceIT {
@Autowired AmqpTemplate amqpTemplate;
@Test
- public void fireEvent_Should_Send_ExpectedCreateMessageStatisticsEventMessageToQueue()
+ void fireEvent_Should_Send_ExpectedCreateMessageStatisticsEventMessageToQueue()
throws IOException {
CreateMessageStatisticsEvent createMessageStatisticsEvent =
diff --git a/src/test/java/de/caritas/cob/messageservice/api/service/statistics/StatisticsServiceTest.java b/src/test/java/de/caritas/cob/messageservice/api/service/statistics/StatisticsServiceTest.java
index f253bb1..59793c0 100644
--- a/src/test/java/de/caritas/cob/messageservice/api/service/statistics/StatisticsServiceTest.java
+++ b/src/test/java/de/caritas/cob/messageservice/api/service/statistics/StatisticsServiceTest.java
@@ -13,21 +13,21 @@
import de.caritas.cob.messageservice.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.slf4j.Logger;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.messaging.Message;
-@RunWith(MockitoJUnitRunner.class)
-public class StatisticsServiceTest {
+@ExtendWith(MockitoExtension.class)
+class StatisticsServiceTest {
private static final String FIELD_NAME_STATISTICS_ENABLED = "statisticsEnabled";
private static final String FIELD_NAME_RABBIT_EXCHANGE_NAME = "rabbitMqExchangeName";
@@ -39,16 +39,16 @@ public class StatisticsServiceTest {
@InjectMocks private StatisticsService statisticsService;
@Mock private AmqpTemplate amqpTemplate;
- @Before
- public void setup() {
+ @BeforeEach
+ void setup() {
createMessageStatisticsEvent = Mockito.mock(CreateMessageStatisticsEvent.class);
- when(createMessageStatisticsEvent.getEventType()).thenReturn(eventType);
- when(createMessageStatisticsEvent.getPayload()).thenReturn(Optional.of(PAYLOAD));
+ Mockito.lenient().when(createMessageStatisticsEvent.getEventType()).thenReturn(eventType);
+ Mockito.lenient().when(createMessageStatisticsEvent.getPayload()).thenReturn(Optional.of(PAYLOAD));
setField(statisticsService, FIELD_NAME_RABBIT_EXCHANGE_NAME, RABBIT_EXCHANGE_NAME);
}
@Test
- public void fireEvent_Should_NotSendStatisticsMessage_WhenStatisticsIsDisabled() {
+ void fireEvent_Should_NotSendStatisticsMessage_WhenStatisticsIsDisabled() {
setField(statisticsService, FIELD_NAME_STATISTICS_ENABLED, false);
statisticsService.fireEvent(createMessageStatisticsEvent);
@@ -57,7 +57,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(createMessageStatisticsEvent.getEventType()).thenReturn(eventType);
@@ -73,7 +73,7 @@ public void fireEvent_Should_SendStatisticsMessage_WhenStatisticsIsEnabled() {
}
@Test
- public void fireEvent_Should_NotSendMessageToQueue_WhenPayloadIsEmpty() {
+ void fireEvent_Should_NotSendMessageToQueue_WhenPayloadIsEmpty() {
setField(statisticsService, FIELD_NAME_STATISTICS_ENABLED, true);
when(createMessageStatisticsEvent.getPayload()).thenReturn(Optional.empty());
@@ -82,7 +82,7 @@ public void fireEvent_Should_NotSendMessageToQueue_WhenPayloadIsEmpty() {
}
@Test
- public void fireEvent_Should_UseEventTypeAsTopicAndSendPayloadOfEvent() {
+ void fireEvent_Should_UseEventTypeAsTopicAndSendPayloadOfEvent() {
setField(statisticsService, FIELD_NAME_STATISTICS_ENABLED, true);
statisticsService.fireEvent(createMessageStatisticsEvent);
diff --git a/src/test/java/de/caritas/cob/messageservice/api/service/statistics/event/CreateMessageStatisticsEventTest.java b/src/test/java/de/caritas/cob/messageservice/api/service/statistics/event/CreateMessageStatisticsEventTest.java
index 2739799..2567f7e 100644
--- a/src/test/java/de/caritas/cob/messageservice/api/service/statistics/event/CreateMessageStatisticsEventTest.java
+++ b/src/test/java/de/caritas/cob/messageservice/api/service/statistics/event/CreateMessageStatisticsEventTest.java
@@ -11,18 +11,18 @@
import de.caritas.cob.messageservice.statisticsservice.generated.web.model.EventType;
import de.caritas.cob.messageservice.statisticsservice.generated.web.model.UserRole;
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 CreateMessageStatisticsEventTest {
private static final long TENANT_ID = 1L;
private CreateMessageStatisticsEvent createMessageStatisticsEvent;
- @Before
+ @BeforeEach
public void setup() throws NoSuchFieldException, IllegalAccessException {
createMessageStatisticsEvent =
new CreateMessageStatisticsEvent(CONSULTANT_ID, UserRole.CONSULTANT, RC_GROUP_ID, false, ADVICESEEKER_ID,
diff --git a/src/test/java/de/caritas/cob/messageservice/api/tenant/TechnicalUserTenantResolverTest.java b/src/test/java/de/caritas/cob/messageservice/api/tenant/TechnicalUserTenantResolverTest.java
index 7cc794f..5bbefa4 100644
--- a/src/test/java/de/caritas/cob/messageservice/api/tenant/TechnicalUserTenantResolverTest.java
+++ b/src/test/java/de/caritas/cob/messageservice/api/tenant/TechnicalUserTenantResolverTest.java
@@ -85,7 +85,7 @@ private Jwt buildJwtWithRealmRole(String realmRole) {
headers.put("alg", "HS256"); // Signature algorithm
headers.put("typ", "JWT"); // Token type
return new Jwt(
- "token", Instant.now(), Instant.now(), headers, givenClaimMapContainingRole(realmRole));
+ "token", Instant.now(), Instant.now().plusSeconds(1), headers, givenClaimMapContainingRole(realmRole));
}
private HashMap givenClaimMapContainingRole(String realmRole) {
@@ -95,4 +95,4 @@ private HashMap givenClaimMapContainingRole(String realmRole) {
claimMap.put("realm_access", realmAccess);
return claimMap;
}
-}
\ No newline at end of file
+}
diff --git a/src/test/java/de/caritas/cob/messageservice/filter/StatelessCsrfFilterTest.java b/src/test/java/de/caritas/cob/messageservice/filter/StatelessCsrfFilterTest.java
index ef9e8b0..a8e7f1d 100644
--- a/src/test/java/de/caritas/cob/messageservice/filter/StatelessCsrfFilterTest.java
+++ b/src/test/java/de/caritas/cob/messageservice/filter/StatelessCsrfFilterTest.java
@@ -13,15 +13,15 @@
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.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.springframework.security.web.access.AccessDeniedHandler;
-@RunWith(MockitoJUnitRunner.class)
-public class StatelessCsrfFilterTest {
+@ExtendWith(MockitoExtension.class)
+class StatelessCsrfFilterTest {
private static final String CSRF_HEADER = "csrfHeader";
private static final String CSRF_COOKIE = "csrfCookie";
@@ -42,13 +42,13 @@ public class StatelessCsrfFilterTest {
@Mock
private AccessDeniedHandler accessDeniedHandler;
- @Before
- public void setup() {
+ @BeforeEach
+ void setup() {
setField(csrfFilter, "accessDeniedHandler", accessDeniedHandler);
}
@Test
- public void doFilterInternal_Should_executeFilterChain_When_requestMethodIsAllowed()
+ void doFilterInternal_Should_executeFilterChain_When_requestMethodIsAllowed()
throws IOException, ServletException {
when(request.getRequestURI()).thenReturn("uri");
when(request.getMethod()).thenReturn("OPTIONS");
@@ -59,7 +59,7 @@ public void doFilterInternal_Should_executeFilterChain_When_requestMethodIsAllow
}
@Test
- public void doFilterInternal_Should_executeFilterChain_When_requestHasCsrfWhitelistHeader()
+ void doFilterInternal_Should_executeFilterChain_When_requestHasCsrfWhitelistHeader()
throws IOException, ServletException {
when(request.getRequestURI()).thenReturn("uri");
when(request.getHeader(CSRF_WHITELIST_COOKIE)).thenReturn("whitelisted");
@@ -70,11 +70,12 @@ public void doFilterInternal_Should_executeFilterChain_When_requestHasCsrfWhitel
}
@Test
- public void doFilterInternal_Should_executeFilterChain_When_requestCsrfHeaderAndCookieAreEqual()
+ void doFilterInternal_Should_executeFilterChain_When_requestCsrfHeaderAndCookieAreEqual()
throws IOException, ServletException {
when(request.getRequestURI()).thenReturn("uri");
when(request.getMethod()).thenReturn("POST");
when(request.getHeader(CSRF_HEADER)).thenReturn("csrfTokenValue");
+ when(request.getHeader(CSRF_WHITELIST_COOKIE)).thenReturn(null);
Cookie[] cookies = {new Cookie(CSRF_COOKIE, "csrfTokenValue")};
when(request.getCookies()).thenReturn(cookies);
@@ -84,7 +85,7 @@ public void doFilterInternal_Should_executeFilterChain_When_requestCsrfHeaderAnd
}
@Test
- public void doFilterInternal_Should_callAccessDeniedHandler_When_csrfHeaderIsNull()
+ void doFilterInternal_Should_callAccessDeniedHandler_When_csrfHeaderIsNull()
throws IOException, ServletException {
when(request.getRequestURI()).thenReturn("uri");
when(request.getMethod()).thenReturn("POST");
@@ -98,11 +99,12 @@ public void doFilterInternal_Should_callAccessDeniedHandler_When_csrfHeaderIsNul
}
@Test
- public void doFilterInternal_Should_callAccessDeniedHandler_When_cookiesAreNull()
+ void doFilterInternal_Should_callAccessDeniedHandler_When_cookiesAreNull()
throws IOException, ServletException {
when(request.getRequestURI()).thenReturn("uri");
when(request.getMethod()).thenReturn("POST");
when(request.getHeader(CSRF_HEADER)).thenReturn("csrfHeaderTokenValue");
+ when(request.getHeader(CSRF_WHITELIST_COOKIE)).thenReturn(null);
this.csrfFilter.doFilterInternal(request, response, filterChain);
@@ -111,11 +113,12 @@ public void doFilterInternal_Should_callAccessDeniedHandler_When_cookiesAreNull(
}
@Test
- public void doFilterInternal_Should_callAccessDeniedHandler_When_csrfHeaderIsNotEqualToCookieToken()
+ void doFilterInternal_Should_callAccessDeniedHandler_When_csrfHeaderIsNotEqualToCookieToken()
throws IOException, ServletException {
when(request.getRequestURI()).thenReturn("uri");
when(request.getMethod()).thenReturn("POST");
when(request.getHeader(CSRF_HEADER)).thenReturn("csrfHeaderTokenValue");
+ when(request.getHeader(CSRF_WHITELIST_COOKIE)).thenReturn(null);
Cookie[] cookies = {new Cookie(CSRF_COOKIE, "csrfCookieTokenValue")};
when(request.getCookies()).thenReturn(cookies);