diff --git a/.github/workflows/admin-api-documentation.yml b/.github/workflows/admin-api-documentation.yml index bb109a4d..62943348 100644 --- a/.github/workflows/admin-api-documentation.yml +++ b/.github/workflows/admin-api-documentation.yml @@ -19,7 +19,7 @@ jobs: - name: Setup JVM uses: actions/setup-java@v1 with: - java-version: 11.0.10 + java-version: 17 java-package: jdk architecture: x64 diff --git a/pom.xml b/pom.xml index 0b11b68f..5b2409d1 100644 --- a/pom.xml +++ b/pom.xml @@ -16,7 +16,7 @@ org.springframework.boot spring-boot-starter-parent - 3.0.6 + 3.3.6 @@ -89,17 +89,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} @@ -124,17 +121,6 @@ plexus-utils 3.3.0 - - - io.swagger.core.v3 - swagger-annotations - 2.2.15 - - - io.springfox - springfox-boot-starter - ${springfox.boot.starter.version} - io.swagger.parser.v3 swagger-parser @@ -171,9 +157,8 @@ ${keycloak.version} - javax.ws.rs - javax.ws.rs-api - ${javax.ws.rs-api.version} + jakarta.ws.rs + jakarta.ws.rs-api @@ -183,11 +168,11 @@ true + org.apache.commons commons-lang3 - ${commons-lang3.version} @@ -212,7 +197,6 @@ org.liquibase liquibase-core - ${liquibase-core.version} @@ -242,17 +226,14 @@ 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} @@ -266,12 +247,6 @@ org.yaml snakeyaml - 2.0 - - - io.swagger.core.v3 - swagger-annotations - 2.2.15 @@ -282,7 +257,6 @@ com.h2database h2 test - ${h2.version} org.springframework.boot @@ -294,12 +268,6 @@ spring-security-test test - - junit - junit - 4.12 - test - com.c4-soft.springaddons @@ -318,6 +286,7 @@ + org.springframework.boot spring-boot-maven-plugin @@ -554,7 +523,6 @@ org.liquibase liquibase-maven-plugin - ${liquibase-maven-plugin.version} src/main/resources/liquibase.properties @@ -563,7 +531,7 @@ org.apache.maven.plugins maven-checkstyle-plugin - 3.3.0 + 3.6.0 validate @@ -587,9 +555,8 @@ org.apache.maven.plugins maven-compiler-plugin - 17 - 17 --enable-preview + ${java.version} @@ -629,6 +596,24 @@ + + org.openrewrite.maven + rewrite-maven-plugin + 5.46.1 + + true + + org.openrewrite.java.spring.boot3.UpgradeSpringBoot_3_3 + + + + + org.openrewrite.recipe + rewrite-spring + 5.24.1 + + + diff --git a/src/main/java/de/caritas/cob/agencyservice/api/admin/controller/AgencyAdminController.java b/src/main/java/de/caritas/cob/agencyservice/api/admin/controller/AgencyAdminController.java index db71124b..70e27627 100644 --- a/src/main/java/de/caritas/cob/agencyservice/api/admin/controller/AgencyAdminController.java +++ b/src/main/java/de/caritas/cob/agencyservice/api/admin/controller/AgencyAdminController.java @@ -16,7 +16,7 @@ import de.caritas.cob.agencyservice.api.model.Sort; import de.caritas.cob.agencyservice.api.model.UpdateAgencyDTO; import de.caritas.cob.agencyservice.generated.api.admin.controller.AgencyadminApi; -import io.swagger.annotations.Api; +import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; import jakarta.validation.constraints.NotNull; @@ -33,7 +33,7 @@ * Controller to handle all agency admin requests. */ @RestController -@Api(tags = "admin-agency-controller") +@Tag(name = "admin-agency-controller") @RequiredArgsConstructor public class AgencyAdminController implements AgencyadminApi { @@ -92,8 +92,6 @@ public ResponseEntity searchAgencies( @Override @PreAuthorize("hasAuthority('AUTHORIZATION_AGENCY_ADMIN')") public ResponseEntity createAgency(@Valid AgencyDTO agencyDTO) { - - agencyValidator.validate(agencyDTO); var agencyAdminFullResponseDTO = agencyAdminService .createAgency(agencyDTO); diff --git a/src/main/java/de/caritas/cob/agencyservice/api/controller/AgencyController.java b/src/main/java/de/caritas/cob/agencyservice/api/controller/AgencyController.java index bb50d200..fc77df5c 100644 --- a/src/main/java/de/caritas/cob/agencyservice/api/controller/AgencyController.java +++ b/src/main/java/de/caritas/cob/agencyservice/api/controller/AgencyController.java @@ -6,7 +6,7 @@ import de.caritas.cob.agencyservice.api.model.FullAgencyResponseDTO; import de.caritas.cob.agencyservice.api.service.AgencyService; import de.caritas.cob.agencyservice.generated.api.controller.AgenciesApi; -import io.swagger.annotations.Api; +import io.swagger.v3.oas.annotations.tags.Tag; import java.util.List; import java.util.Optional; import lombok.NonNull; @@ -22,7 +22,7 @@ * Controller for agency API requests */ @RestController -@Api(tags = "agency-controller") +@Tag(name = "agency-controller") @RequiredArgsConstructor public class AgencyController implements AgenciesApi { @@ -40,10 +40,10 @@ public class AgencyController implements AgenciesApi { @Override public ResponseEntity> getAgencies( @RequestParam Integer consultingType, @RequestParam(required = false) String postcode, - @RequestParam(value = "topicId", required = false) Integer topicId, - @RequestParam(value = "age", required = false) Integer age, - @RequestParam(value = "gender", required = false) String gender, - @RequestParam(value = "counsellingRelation", required = false) String counsellingRelation + @RequestParam(required = false) Integer topicId, + @RequestParam(required = false) Integer age, + @RequestParam(required = false) String gender, + @RequestParam(required = false) String counsellingRelation ) { var agencies = agencyService.getAgencies(Optional.ofNullable(postcode), consultingType, @@ -62,7 +62,7 @@ public ResponseEntity> getAgencies( */ @Override public ResponseEntity> getAgenciesByIds( - @PathVariable("agencyIds") List agencyIds) { + @PathVariable List agencyIds) { var agencies = agencyService.getAgencies(agencyIds); diff --git a/src/main/java/de/caritas/cob/agencyservice/api/controller/CustomSwaggerUIController.java b/src/main/java/de/caritas/cob/agencyservice/api/controller/CustomSwaggerUIController.java deleted file mode 100644 index e89a9613..00000000 --- a/src/main/java/de/caritas/cob/agencyservice/api/controller/CustomSwaggerUIController.java +++ /dev/null @@ -1,18 +0,0 @@ -package de.caritas.cob.agencyservice.api.controller; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import springfox.documentation.annotations.ApiIgnore; - -@Controller -@ApiIgnore -public class CustomSwaggerUIController { - @Value("${springfox.docuPath}") - private String docuPath; - - @RequestMapping(value = "${springfox.docuPath}") - public String index() { - return "redirect:" + docuPath + "/swagger-ui.html"; - } -} diff --git a/src/main/java/de/caritas/cob/agencyservice/api/exception/KeycloakException.java b/src/main/java/de/caritas/cob/agencyservice/api/exception/KeycloakException.java index da6b3358..20c2d37d 100644 --- a/src/main/java/de/caritas/cob/agencyservice/api/exception/KeycloakException.java +++ b/src/main/java/de/caritas/cob/agencyservice/api/exception/KeycloakException.java @@ -1,7 +1,10 @@ package de.caritas.cob.agencyservice.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/agencyservice/api/exception/MissingConsultingTypeException.java b/src/main/java/de/caritas/cob/agencyservice/api/exception/MissingConsultingTypeException.java index dc289c17..9576d6cc 100644 --- a/src/main/java/de/caritas/cob/agencyservice/api/exception/MissingConsultingTypeException.java +++ b/src/main/java/de/caritas/cob/agencyservice/api/exception/MissingConsultingTypeException.java @@ -1,7 +1,10 @@ package de.caritas.cob.agencyservice.api.exception; +import java.io.Serial; + public class MissingConsultingTypeException extends Exception { + @Serial private static final long serialVersionUID = -6127271234647444277L; /** diff --git a/src/main/java/de/caritas/cob/agencyservice/api/exception/httpresponses/BadRequestException.java b/src/main/java/de/caritas/cob/agencyservice/api/exception/httpresponses/BadRequestException.java index 66d2ca47..627d5807 100644 --- a/src/main/java/de/caritas/cob/agencyservice/api/exception/httpresponses/BadRequestException.java +++ b/src/main/java/de/caritas/cob/agencyservice/api/exception/httpresponses/BadRequestException.java @@ -1,9 +1,11 @@ package de.caritas.cob.agencyservice.api.exception.httpresponses; import de.caritas.cob.agencyservice.api.service.LogService; +import java.io.Serial; public class BadRequestException extends CustomHttpStatusException { + @Serial private static final long serialVersionUID = -8047408802295905803L; /** diff --git a/src/main/java/de/caritas/cob/agencyservice/api/exception/httpresponses/CustomHttpStatusException.java b/src/main/java/de/caritas/cob/agencyservice/api/exception/httpresponses/CustomHttpStatusException.java index 3dee1c53..aaea3229 100644 --- a/src/main/java/de/caritas/cob/agencyservice/api/exception/httpresponses/CustomHttpStatusException.java +++ b/src/main/java/de/caritas/cob/agencyservice/api/exception/httpresponses/CustomHttpStatusException.java @@ -2,6 +2,7 @@ import static java.util.Objects.nonNull; +import java.io.Serial; import java.util.function.Consumer; /** @@ -9,6 +10,7 @@ */ public abstract class CustomHttpStatusException extends RuntimeException { + @Serial private static final long serialVersionUID = -3545035432045919306L; private final Consumer loggingMethod; diff --git a/src/main/java/de/caritas/cob/agencyservice/api/exception/httpresponses/InternalServerErrorException.java b/src/main/java/de/caritas/cob/agencyservice/api/exception/httpresponses/InternalServerErrorException.java index c431dcd7..31f82bc6 100644 --- a/src/main/java/de/caritas/cob/agencyservice/api/exception/httpresponses/InternalServerErrorException.java +++ b/src/main/java/de/caritas/cob/agencyservice/api/exception/httpresponses/InternalServerErrorException.java @@ -1,6 +1,7 @@ package de.caritas.cob.agencyservice.api.exception.httpresponses; import de.caritas.cob.agencyservice.api.service.LogService; +import java.io.Serial; import java.util.function.Consumer; /** @@ -8,6 +9,7 @@ */ public class InternalServerErrorException extends CustomHttpStatusException { + @Serial private static final long serialVersionUID = 6051508644381775936L; /** diff --git a/src/main/java/de/caritas/cob/agencyservice/api/manager/consultingtype/ConsultingTypeManager.java b/src/main/java/de/caritas/cob/agencyservice/api/manager/consultingtype/ConsultingTypeManager.java index 8ba60546..fdf4def9 100644 --- a/src/main/java/de/caritas/cob/agencyservice/api/manager/consultingtype/ConsultingTypeManager.java +++ b/src/main/java/de/caritas/cob/agencyservice/api/manager/consultingtype/ConsultingTypeManager.java @@ -28,7 +28,7 @@ public ExtendedConsultingTypeResponseDTO getConsultingTypeSettings(int consultin return consultingTypeService.getExtendedConsultingTypeResponseDTO(consultingTypeId); } catch (RestClientException ex) { throw new MissingConsultingTypeException( - String.format("No settings for consulting type %s found.", consultingTypeId)); + "No settings for consulting type %s found.".formatted(consultingTypeId)); } } diff --git a/src/main/java/de/caritas/cob/agencyservice/api/repository/agency/Agency.java b/src/main/java/de/caritas/cob/agencyservice/api/repository/agency/Agency.java index 5de6e9e5..ce19bece 100644 --- a/src/main/java/de/caritas/cob/agencyservice/api/repository/agency/Agency.java +++ b/src/main/java/de/caritas/cob/agencyservice/api/repository/agency/Agency.java @@ -43,9 +43,6 @@ @Getter @Setter @Builder -@FilterDef( - name = "tenantFilter", - parameters = {@ParamDef(name = "tenantId", type = Long.class)}) @Filter(name = "tenantFilter", condition = "tenant_id = :tenantId") public class Agency implements TenantAware { diff --git a/src/main/java/de/caritas/cob/agencyservice/api/repository/agencypostcoderange/AgencyPostcodeRange.java b/src/main/java/de/caritas/cob/agencyservice/api/repository/agencypostcoderange/AgencyPostcodeRange.java index 42d0a13d..9efb3092 100644 --- a/src/main/java/de/caritas/cob/agencyservice/api/repository/agencypostcoderange/AgencyPostcodeRange.java +++ b/src/main/java/de/caritas/cob/agencyservice/api/repository/agencypostcoderange/AgencyPostcodeRange.java @@ -38,7 +38,6 @@ @Getter @Setter @Builder -@FilterDef(name = "tenantFilter", parameters = {@ParamDef(name = "tenantId", type = Long.class)}) @Filter(name = "tenantFilter", condition = "tenant_id = :tenantId") public class AgencyPostcodeRange implements TenantAware { diff --git a/src/main/java/de/caritas/cob/agencyservice/api/repository/package-info.java b/src/main/java/de/caritas/cob/agencyservice/api/repository/package-info.java new file mode 100644 index 00000000..5e8caf01 --- /dev/null +++ b/src/main/java/de/caritas/cob/agencyservice/api/repository/package-info.java @@ -0,0 +1,11 @@ +@FilterDefs({ + @FilterDef( + name = "tenantFilter", + parameters = {@ParamDef(name = "tenantId", type = Long.class)} + ) +}) +package de.caritas.cob.agencyservice.api.repository; + +import org.hibernate.annotations.FilterDef; +import org.hibernate.annotations.FilterDefs; +import org.hibernate.annotations.ParamDef; \ No newline at end of file diff --git a/src/main/java/de/caritas/cob/agencyservice/api/service/AgencyService.java b/src/main/java/de/caritas/cob/agencyservice/api/service/AgencyService.java index 1d453a67..ca9a1455 100644 --- a/src/main/java/de/caritas/cob/agencyservice/api/service/AgencyService.java +++ b/src/main/java/de/caritas/cob/agencyservice/api/service/AgencyService.java @@ -34,6 +34,7 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.dao.DataAccessException; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; /** * Service for agencies. @@ -75,6 +76,7 @@ public class AgencyService { * @param agencyIds the ids of requested agencies * @return a list containing regarding agencies */ + @Transactional public List getAgencies(List agencyIds) { return getAgencyRepositoryForSearch().findByIdIn(agencyIds).stream() .map(this::convertToAgencyResponseDTO) @@ -98,7 +100,7 @@ public List getAgencies(int consultingTypeId) { } catch (MissingConsultingTypeException ex) { throw new BadRequestException( - String.format("Consulting type with id %s does not exist", consultingTypeId)); + "Consulting type with id %s does not exist".formatted(consultingTypeId)); } } @@ -190,7 +192,7 @@ private List findAgencies(AgencySearch agencySearch) { } private void assertTopicIdIsProvided(Optional topicId) { - if (!topicId.isPresent()) { + if (topicId.isEmpty()) { throw new BadRequestException("Topic id not provided in the search"); } } @@ -261,10 +263,10 @@ private AgencyRepository getAgencyRepositoryForSearch() { } private void assertAgeAndGenderAreProvided(Optional age, Optional gender) { - if (!age.isPresent()) { + if (age.isEmpty()) { throw new BadRequestException("Age not provided in the search"); } - if (!gender.isPresent()) { + if (gender.isEmpty()) { throw new BadRequestException("Age not provided in the search"); } } @@ -311,10 +313,14 @@ private AgencyResponseDTO convertToAgencyResponseDTO(Agency agency) { .tenantId(agency.getTenantId()) .consultingType(agency.getConsultingTypeId()) .agencySpecificPrivacy(renderedAgencySpecificPrivacy) - .topicIds(agency.getAgencyTopics().stream().map(AgencyTopic::getTopicId).toList()) + .topicIds(getAgencyTopics(agency).stream().map(AgencyTopic::getTopicId).toList()) .agencyLogo(agency.getAgencyLogo()); } + private static List getAgencyTopics(Agency agency) { + return agency.getAgencyTopics() == null ? Lists.newArrayList() : agency.getAgencyTopics(); + } + protected String getRenderedAgencySpecificPrivacy(Agency agency) { RestrictedTenantDTO tenantDataHoldingFeatureToggles = getTenantDataRelevantForFeatureToggles( agency); @@ -342,7 +348,7 @@ private FullAgencyResponseDTO convertToFullAgencyResponseDTO(Agency agency) { .external(agency.isExternal()) .demographics(getDemographics(agency)) .tenantId(agency.getTenantId()) - .topicIds(agency.getAgencyTopics().stream().map(AgencyTopic::getTopicId).toList()) + .topicIds(getAgencyTopics(agency).stream().map(AgencyTopic::getTopicId).toList()) .agencyLogo(agency.getAgencyLogo()); } diff --git a/src/main/java/de/caritas/cob/agencyservice/api/service/CentralDataProtectionTemplateService.java b/src/main/java/de/caritas/cob/agencyservice/api/service/CentralDataProtectionTemplateService.java index f685b7ee..b5dc7095 100644 --- a/src/main/java/de/caritas/cob/agencyservice/api/service/CentralDataProtectionTemplateService.java +++ b/src/main/java/de/caritas/cob/agencyservice/api/service/CentralDataProtectionTemplateService.java @@ -10,7 +10,7 @@ import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; -import javax.annotation.Nullable; +import jakarta.annotation.Nullable; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; diff --git a/src/main/java/de/caritas/cob/agencyservice/api/service/LogService.java b/src/main/java/de/caritas/cob/agencyservice/api/service/LogService.java index 4c0fa323..2c5dcf4e 100644 --- a/src/main/java/de/caritas/cob/agencyservice/api/service/LogService.java +++ b/src/main/java/de/caritas/cob/agencyservice/api/service/LogService.java @@ -2,7 +2,7 @@ import static org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace; -import javax.ws.rs.BadRequestException; +import jakarta.ws.rs.BadRequestException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; diff --git a/src/main/java/de/caritas/cob/agencyservice/api/service/TenantHibernateInterceptor.java b/src/main/java/de/caritas/cob/agencyservice/api/service/TenantHibernateInterceptor.java index 9e1bce47..9835be1f 100644 --- a/src/main/java/de/caritas/cob/agencyservice/api/service/TenantHibernateInterceptor.java +++ b/src/main/java/de/caritas/cob/agencyservice/api/service/TenantHibernateInterceptor.java @@ -8,17 +8,18 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.hibernate.EmptyInterceptor; +import org.hibernate.Interceptor; @RequiredArgsConstructor @Slf4j -public class TenantHibernateInterceptor extends EmptyInterceptor { +public class TenantHibernateInterceptor implements Interceptor { private final Long TECHNICAL_TENANT_ID = 0L; private static Boolean multiTenancyEnabled; @Override - public void preFlush(Iterator entities) { + public void preFlush(Iterator entities) { if (multiTenancyEnabled == null) { multiTenancyEnabled = resolveMultiTenancy(); @@ -28,17 +29,16 @@ public void preFlush(Iterator entities) { Object entity; while (entities.hasNext()) { entity = entities.next(); - if (entity instanceof TenantAware) { - var tenantAware = (TenantAware) entity; + if (entity instanceof TenantAware tenantAware) { if (tenantAware.getTenantId() == null && !Long.valueOf(TECHNICAL_TENANT_ID) .equals(TenantContext.getCurrentTenant())) { - ((TenantAware) entity).setTenantId(TenantContext.getCurrentTenant()); + tenantAware.setTenantId(TenantContext.getCurrentTenant()); } } } } - super.preFlush(entities); + Interceptor.super.preFlush(entities); } private boolean resolveMultiTenancy() { diff --git a/src/main/java/de/caritas/cob/agencyservice/config/AppConfig.java b/src/main/java/de/caritas/cob/agencyservice/config/AppConfig.java index a9dc20ed..95b520da 100644 --- a/src/main/java/de/caritas/cob/agencyservice/config/AppConfig.java +++ b/src/main/java/de/caritas/cob/agencyservice/config/AppConfig.java @@ -19,7 +19,7 @@ public class AppConfig { * Activate the messages.properties for validation messages */ @Bean - public LocalValidatorFactoryBean validator(MessageSource messageSource) { + LocalValidatorFactoryBean validator(MessageSource messageSource) { LocalValidatorFactoryBean validatorFactoryBean = new LocalValidatorFactoryBean(); validatorFactoryBean.setValidationMessageSource(messageSource); return validatorFactoryBean; diff --git a/src/main/java/de/caritas/cob/agencyservice/config/AuthenticatedUserConfig.java b/src/main/java/de/caritas/cob/agencyservice/config/AuthenticatedUserConfig.java index 75ab77dd..94e5ff04 100644 --- a/src/main/java/de/caritas/cob/agencyservice/config/AuthenticatedUserConfig.java +++ b/src/main/java/de/caritas/cob/agencyservice/config/AuthenticatedUserConfig.java @@ -34,7 +34,7 @@ public class AuthenticatedUserConfig { */ @Bean @Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS) - public AuthenticatedUser getAuthenticatedUser() { + AuthenticatedUser getAuthenticatedUser() { JwtAuthenticationToken authenticationToken = (JwtAuthenticationToken) getRequest().getUserPrincipal(); diff --git a/src/main/java/de/caritas/cob/agencyservice/config/CacheManagerConfig.java b/src/main/java/de/caritas/cob/agencyservice/config/CacheManagerConfig.java index 61a3178c..8dc0ec76 100644 --- a/src/main/java/de/caritas/cob/agencyservice/config/CacheManagerConfig.java +++ b/src/main/java/de/caritas/cob/agencyservice/config/CacheManagerConfig.java @@ -67,7 +67,7 @@ public class CacheManagerConfig { private long applicationSettingsTimeToLiveSeconds; @Bean(destroyMethod = "shutdown") - public net.sf.ehcache.CacheManager ehCacheManager() { + net.sf.ehcache.CacheManager ehCacheManager() { var config = new net.sf.ehcache.config.Configuration(); config.addCache(buildConsultingTypeCacheConfiguration()); config.addCache(buildTenantCacheConfiguration()); diff --git a/src/main/java/de/caritas/cob/agencyservice/config/FreeMarkerConfig.java b/src/main/java/de/caritas/cob/agencyservice/config/FreeMarkerConfig.java index 1f44c545..0a07c24f 100644 --- a/src/main/java/de/caritas/cob/agencyservice/config/FreeMarkerConfig.java +++ b/src/main/java/de/caritas/cob/agencyservice/config/FreeMarkerConfig.java @@ -13,7 +13,7 @@ public class FreeMarkerConfig { @Bean - public freemarker.template.Configuration freemarkerConfiguration() + freemarker.template.Configuration freemarkerConfiguration() throws TemplateException, IOException { Configuration configuration = new FreeMarkerConfigurationFactoryBean().createConfiguration(); configuration.setTemplateExceptionHandler( diff --git a/src/main/java/de/caritas/cob/agencyservice/config/SecurityConfig.java b/src/main/java/de/caritas/cob/agencyservice/config/SecurityConfig.java index c5b0e17e..cfb9294e 100644 --- a/src/main/java/de/caritas/cob/agencyservice/config/SecurityConfig.java +++ b/src/main/java/de/caritas/cob/agencyservice/config/SecurityConfig.java @@ -12,14 +12,16 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.http.HttpMethod; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.oauth2.server.resource.web.authentication.BearerTokenAuthenticationFilter; import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.access.expression.WebExpressionAuthorizationManager; import org.springframework.security.web.csrf.CsrfFilter; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @@ -27,9 +29,9 @@ /** * Provides the Keycloak/Spring Security configuration. */ +@Configuration @KeycloakConfiguration -@EnableGlobalMethodSecurity( - prePostEnabled = true) +@EnableMethodSecurity @EnableWebSecurity @RequiredArgsConstructor public class SecurityConfig implements WebMvcConfigurer { @@ -66,9 +68,9 @@ public class SecurityConfig implements WebMvcConfigurer { * Keycloak roles for specific REST API paths */ @Bean - public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - var httpSecurity = http.csrf().disable() + var httpSecurity = http.csrf(csrf -> csrf.disable()) .addFilterBefore(new StatelessCsrfFilter(csrfCookieProperty, csrfHeaderProperty), CsrfFilter.class); @@ -77,22 +79,21 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .addFilterAfter(httpTenantFilter, BearerTokenAuthenticationFilter.class); } - httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) - .and().authorizeRequests() + httpSecurity.sessionManagement(management -> management.sessionCreationPolicy(SessionCreationPolicy.STATELESS)).authorizeHttpRequests(requests -> requests .requestMatchers("/agencies/**").permitAll() .requestMatchers(WHITE_LIST).permitAll() .requestMatchers("/agencies").permitAll() .requestMatchers(HttpMethod.GET, "/agencyadmin/agencies") .hasAuthority(AuthorityValue.SEARCH_AGENCIES) .requestMatchers("/agencyadmin/agencies/tenant/*") - .access("hasAuthority('" + AuthorityValue.AGENCY_ADMIN - + "') and hasAuthority('" + AuthorityValue.TENANT_ADMIN + "')") + .access(new WebExpressionAuthorizationManager("hasAuthority('" + AuthorityValue.AGENCY_ADMIN + + "') and hasAuthority('" + AuthorityValue.TENANT_ADMIN + "')")) .requestMatchers("/agencyadmin", "/agencyadmin/", "/agencyadmin/**") .hasAnyAuthority(AuthorityValue.AGENCY_ADMIN, AuthorityValue.RESTRICTED_AGENCY_ADMIN) - .anyRequest().denyAll(); + .anyRequest().denyAll()); - httpSecurity.oauth2ResourceServer().jwt().jwtAuthenticationConverter(jwtAuthConverter()); + httpSecurity.oauth2ResourceServer(server -> server.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthConverter()))); return httpSecurity.build(); } @@ -106,7 +107,7 @@ public void configurePathMatch(PathMatchConfigurer configurer) { } @Bean - public JwtAuthConverter jwtAuthConverter() { + JwtAuthConverter jwtAuthConverter() { return new JwtAuthConverter(jwtAuthConverterProperties, authorisationService); } diff --git a/src/main/java/de/caritas/cob/agencyservice/config/SpringFoxConfig.java b/src/main/java/de/caritas/cob/agencyservice/config/SpringFoxConfig.java deleted file mode 100644 index d4da48fc..00000000 --- a/src/main/java/de/caritas/cob/agencyservice/config/SpringFoxConfig.java +++ /dev/null @@ -1,121 +0,0 @@ -package de.caritas.cob.agencyservice.config; - -import static java.util.Collections.singletonList; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.hateoas.client.LinkDiscoverer; -import org.springframework.hateoas.client.LinkDiscoverers; -import org.springframework.hateoas.mediatype.collectionjson.CollectionJsonLinkDiscoverer; -import org.springframework.plugin.core.SimplePluginRegistry; -import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; -import springfox.documentation.builders.PathSelectors; -import springfox.documentation.builders.RequestHandlerSelectors; -import springfox.documentation.service.ApiInfo; -import springfox.documentation.service.ApiKey; -import springfox.documentation.service.AuthorizationScope; -import springfox.documentation.service.Contact; -import springfox.documentation.service.SecurityReference; -import springfox.documentation.service.SecurityScheme; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spi.service.contexts.SecurityContext; -import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -/** - * Provides the SpringFox (API documentation generation) configuration. - * - */ -@Configuration -@Import(BeanValidatorPluginsConfiguration.class) -public class SpringFoxConfig { - - @Value("${springfox.docuTitle}") - private String docuTitle; - @Value("${springfox.docuDescription}") - private String docuDescription; - @Value("${springfox.docuVersion}") - private String docuVersion; - @Value("${springfox.docuTermsUrl}") - private String docuTermsUrl; - @Value("${springfox.docuContactName}") - private String docuContactName; - @Value("${springfox.docuContactUrl}") - private String docuContactUrl; - @Value("${springfox.docuContactEmail}") - private String docuContactEmail; - @Value("${springfox.docuLicense}") - private String docuLicense; - @Value("${springfox.docuLicenseUrl}") - private String docuLicenseUrl; - - @Bean - public Docket apiDocket() { - return new Docket(DocumentationType.SWAGGER_2).select() - .apis(RequestHandlerSelectors.basePackage("de.caritas.cob.agencyservice.api")).build() - .consumes(getContentTypes()).produces(getContentTypes()).apiInfo(getApiInfo()) - .useDefaultResponseMessages(false).protocols(protocols()).securitySchemes(securitySchemes()) - .securityContexts(securityContexts()); - } - - private List securityContexts() { - return singletonList(SecurityContext.builder() - .forPaths(PathSelectors.any()).securityReferences(securityReferences()).build()); - } - - private List securityReferences() { - return singletonList( - SecurityReference.builder().reference("token").scopes(new AuthorizationScope[0]).build()); - } - - private List securitySchemes() { - return singletonList(new ApiKey("Bearer", "Authorization", "header")); - } - - /** - * Returns the API protocols (for documentation). - * - * @return the supported protocols - */ - private Set protocols() { - Set protocols = new HashSet<>(); - protocols.add("https"); - return protocols; - } - - /** - * Returns all content types which should be consumed/produced. - * - * @return the supported content types - */ - private Set getContentTypes() { - Set contentTypes = new HashSet<>(); - contentTypes.add("application/json"); - return contentTypes; - } - - /** - * Returns the API information (defined in application.properties). - * - * @return api information - */ - private ApiInfo getApiInfo() { - return new ApiInfo(docuTitle, docuDescription, docuVersion, docuTermsUrl, - new Contact(docuContactName, docuContactUrl, docuContactEmail), docuLicense, docuLicenseUrl, - Collections.emptyList()); - } - - @Bean - public LinkDiscoverers discoverers() { - List plugins = new ArrayList<>(); - plugins.add(new CollectionJsonLinkDiscoverer()); - return new LinkDiscoverers(SimplePluginRegistry.create(plugins)); - } -} diff --git a/src/main/java/de/caritas/cob/agencyservice/config/apiclient/ApplicationSettingsApiClient.java b/src/main/java/de/caritas/cob/agencyservice/config/apiclient/ApplicationSettingsApiClient.java index a5fbfaee..97cd18a7 100644 --- a/src/main/java/de/caritas/cob/agencyservice/config/apiclient/ApplicationSettingsApiClient.java +++ b/src/main/java/de/caritas/cob/agencyservice/config/apiclient/ApplicationSettingsApiClient.java @@ -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.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.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.toString()), + "Could not obtain method properties of %s".formatted(queryValue.toString()), exception); } } @@ -77,7 +77,7 @@ private void setMethodKeyValuePairs(Object queryValue, MultiValueMap ThreadLocalRandom.current().nextInt(1, 100)) + + // Set range for dates + .dateRange(LocalDate.of(2000, 1, 1), LocalDate.of(2023, 12, 31)); + + return new EasyRandom(parameters); + } } diff --git a/src/test/java/de/caritas/cob/agencyservice/api/admin/hallink/AgencyLinksBuilderTest.java b/src/test/java/de/caritas/cob/agencyservice/api/admin/hallink/AgencyLinksBuilderTest.java index d1f7e04b..3c3bf8ab 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/admin/hallink/AgencyLinksBuilderTest.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/admin/hallink/AgencyLinksBuilderTest.java @@ -28,19 +28,19 @@ void buildAgencyLinks_Should_returnAgencyLinks_When_AgencyIsSet() { assertThat(agencyLinks.getSelf(), notNullValue()); assertThat(agencyLinks.getSelf().getMethod(), is(MethodEnum.GET)); assertThat(agencyLinks.getSelf().getHref(), - is(String.format("/agencyadmin/agencies/%s", agency.getId()))); + is("/agencyadmin/agencies/%s".formatted(agency.getId()))); assertThat(agencyLinks.getDelete(), notNullValue()); assertThat(agencyLinks.getDelete().getMethod(), is(MethodEnum.DELETE)); assertThat(agencyLinks.getDelete().getHref(), - is(String.format("/agencyadmin/agencies/%s", agency.getId()))); + is("/agencyadmin/agencies/%s".formatted(agency.getId()))); assertThat(agencyLinks.getUpdate(), notNullValue()); assertThat(agencyLinks.getUpdate().getMethod(), is(MethodEnum.PUT)); assertThat(agencyLinks.getUpdate().getHref(), - is(String.format("/agencyadmin/agencies/%s", agency.getId()))); + is("/agencyadmin/agencies/%s".formatted(agency.getId()))); assertThat(agencyLinks.getPostcodeRanges(), notNullValue()); assertThat(agencyLinks.getPostcodeRanges().getMethod(), is(MethodEnum.GET)); assertThat(agencyLinks.getPostcodeRanges().getHref(), - is(String.format("/agencyadmin/postcoderanges/%s", agency.getId()))); + is("/agencyadmin/postcoderanges/%s".formatted(agency.getId()))); } @Test diff --git a/src/test/java/de/caritas/cob/agencyservice/api/admin/service/AgencyAdminServiceIT.java b/src/test/java/de/caritas/cob/agencyservice/api/admin/service/AgencyAdminServiceIT.java index 309a5612..0d8e6b4a 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/admin/service/AgencyAdminServiceIT.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/admin/service/AgencyAdminServiceIT.java @@ -1,18 +1,15 @@ package de.caritas.cob.agencyservice.api.admin.service; import de.caritas.cob.agencyservice.AgencyServiceApplication; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; -@RunWith(SpringRunner.class) @SpringBootTest(classes = AgencyServiceApplication.class) @TestPropertySource(properties = "spring.profiles.active=testing") @AutoConfigureTestDatabase(replace = Replace.ANY) diff --git a/src/test/java/de/caritas/cob/agencyservice/api/admin/service/AgencyAdminServiceITBase.java b/src/test/java/de/caritas/cob/agencyservice/api/admin/service/AgencyAdminServiceITBase.java index 215ed301..82bfbf89 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/admin/service/AgencyAdminServiceITBase.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/admin/service/AgencyAdminServiceITBase.java @@ -4,8 +4,8 @@ import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; -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.google.common.collect.Lists; import de.caritas.cob.agencyservice.api.model.AgencyAdminFullResponseDTO; @@ -61,26 +61,22 @@ public void saveAgency_Should_ProvideValidAgencyLinks() { assertThat( agencyAdminFullResponseDTO.getLinks().getDelete().getHref(), endsWith( - String.format( - "/agencyadmin/agencies/%s", agencyAdminFullResponseDTO.getEmbedded().getId()))); + "/agencyadmin/agencies/%s".formatted(agencyAdminFullResponseDTO.getEmbedded().getId()))); assertThat(agencyAdminFullResponseDTO.getLinks().getSelf(), notNullValue()); assertThat( agencyAdminFullResponseDTO.getLinks().getSelf().getHref(), endsWith( - String.format( - "/agencyadmin/agencies/%s", agencyAdminFullResponseDTO.getEmbedded().getId()))); + "/agencyadmin/agencies/%s".formatted(agencyAdminFullResponseDTO.getEmbedded().getId()))); assertThat(agencyAdminFullResponseDTO.getLinks().getUpdate(), notNullValue()); assertThat( agencyAdminFullResponseDTO.getLinks().getUpdate().getHref(), endsWith( - String.format( - "/agencyadmin/agencies/%s", agencyAdminFullResponseDTO.getEmbedded().getId()))); + "/agencyadmin/agencies/%s".formatted(agencyAdminFullResponseDTO.getEmbedded().getId()))); assertThat(agencyAdminFullResponseDTO.getLinks().getPostcodeRanges(), notNullValue()); assertThat( agencyAdminFullResponseDTO.getLinks().getPostcodeRanges().getHref(), endsWith( - String.format( - "/agencyadmin/postcoderanges/%s", agencyAdminFullResponseDTO.getEmbedded().getId()))); + "/agencyadmin/postcoderanges/%s".formatted(agencyAdminFullResponseDTO.getEmbedded().getId()))); } protected AgencyDTO createAgencyDTO() { @@ -142,26 +138,22 @@ public void updateAgency_Should_ProvideValidAgencyLinks() { assertThat( agencyAdminFullResponseDTO.getLinks().getDelete().getHref(), endsWith( - String.format( - "/agencyadmin/agencies/%s", agencyAdminFullResponseDTO.getEmbedded().getId()))); + "/agencyadmin/agencies/%s".formatted(agencyAdminFullResponseDTO.getEmbedded().getId()))); assertThat(agencyAdminFullResponseDTO.getLinks().getSelf(), notNullValue()); assertThat( agencyAdminFullResponseDTO.getLinks().getSelf().getHref(), endsWith( - String.format( - "/agencyadmin/agencies/%s", agencyAdminFullResponseDTO.getEmbedded().getId()))); + "/agencyadmin/agencies/%s".formatted(agencyAdminFullResponseDTO.getEmbedded().getId()))); assertThat(agencyAdminFullResponseDTO.getLinks().getUpdate(), notNullValue()); assertThat( agencyAdminFullResponseDTO.getLinks().getUpdate().getHref(), endsWith( - String.format( - "/agencyadmin/agencies/%s", agencyAdminFullResponseDTO.getEmbedded().getId()))); + "/agencyadmin/agencies/%s".formatted(agencyAdminFullResponseDTO.getEmbedded().getId()))); assertThat(agencyAdminFullResponseDTO.getLinks().getPostcodeRanges(), notNullValue()); assertThat( agencyAdminFullResponseDTO.getLinks().getPostcodeRanges().getHref(), endsWith( - String.format( - "/agencyadmin/postcoderanges/%s", agencyAdminFullResponseDTO.getEmbedded().getId()))); + "/agencyadmin/postcoderanges/%s".formatted(agencyAdminFullResponseDTO.getEmbedded().getId()))); } public void getAgency_Should_returnExpectedAgency_When_agencyWithIdExists() { diff --git a/src/test/java/de/caritas/cob/agencyservice/api/admin/service/AgencyAdminServiceTenantAwareIT.java b/src/test/java/de/caritas/cob/agencyservice/api/admin/service/AgencyAdminServiceTenantAwareIT.java index 0b314c6e..7b5f0250 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/admin/service/AgencyAdminServiceTenantAwareIT.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/admin/service/AgencyAdminServiceTenantAwareIT.java @@ -1,8 +1,7 @@ package de.caritas.cob.agencyservice.api.admin.service; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.when; import com.google.common.collect.Lists; @@ -17,11 +16,9 @@ import de.caritas.cob.agencyservice.topicservice.generated.web.model.TopicDTO; import java.lang.reflect.Field; import java.util.Optional; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace; import org.springframework.boot.test.context.SpringBootTest; @@ -31,10 +28,8 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.jdbc.Sql.ExecutionPhase; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; -@RunWith(SpringRunner.class) @SpringBootTest(classes = AgencyServiceApplication.class) @TestPropertySource(properties = "spring.profiles.active=testing") @AutoConfigureTestDatabase(replace = Replace.ANY) @@ -52,7 +47,7 @@ public class AgencyAdminServiceTenantAwareIT extends AgencyAdminServiceITBase { @MockBean private TopicService topicService; - @Before + @BeforeEach public void beforeEach() throws NoSuchFieldException, IllegalAccessException { givenTopicServiceReturnsListOfTopics(); TenantContext.setCurrentTenant(1L); @@ -69,7 +64,7 @@ private void givenTopicServiceReturnsListOfTopics() { new TopicDTO().id(2L).name(THIRD_TOPIC))); } - @After + @AfterEach public void afterEach() { TenantContext.clear(); } diff --git a/src/test/java/de/caritas/cob/agencyservice/api/admin/service/UserAdminServiceTest.java b/src/test/java/de/caritas/cob/agencyservice/api/admin/service/UserAdminServiceTest.java index 97ec319b..d2c2ddb3 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/admin/service/UserAdminServiceTest.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/admin/service/UserAdminServiceTest.java @@ -22,17 +22,17 @@ import de.caritas.cob.agencyservice.useradminservice.generated.web.model.Sort.OrderEnum; import java.util.List; import org.jeasy.random.EasyRandom; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.HttpHeaders; import org.springframework.test.util.ReflectionTestUtils; -@RunWith(MockitoJUnitRunner.class) -public class UserAdminServiceTest { +@ExtendWith(MockitoExtension.class) +class UserAdminServiceTest { @InjectMocks private UserAdminService userAdminService; @@ -54,18 +54,16 @@ public class UserAdminServiceTest { private final HttpHeaders httpHeaders = new EasyRandom().nextObject(HttpHeaders.class); - @Before - public void setup() { - when(this.adminUserControllerApi.getApiClient()).thenReturn(this.apiClient); + @BeforeEach + void setup() { when(this.securityHeaderSupplier.getKeycloakAndCsrfHttpHeaders()) .thenReturn(this.httpHeaders); - when(userAdminServiceApiControllerFactory.createControllerApi()).thenReturn(adminUserControllerApi); } @Test - public void adaptRelatedConsultantsForChange_Should_callServicesCorrectly() { + void adaptRelatedConsultantsForChange_Should_callServicesCorrectly() { Long agencyId = 1L; - + when(userAdminServiceApiControllerFactory.createControllerApi()).thenReturn(adminUserControllerApi); this.userAdminService.adaptRelatedConsultantsForChange(agencyId, TEAM_AGENCY.getValue()); verify(this.adminUserControllerApi, times(1)).changeAgencyType(agencyId, @@ -74,10 +72,11 @@ public void adaptRelatedConsultantsForChange_Should_callServicesCorrectly() { } @Test - public void getConsultantsOfAgency_Should_callServicesCorrectly() { + void getConsultantsOfAgency_Should_callServicesCorrectly() { Long agencyId = 1L; int currentPage = 1; int perPage = 1; + when(userAdminServiceApiControllerFactory.createControllerApi()).thenReturn(adminUserControllerApi); when(this.adminUserControllerApi.getConsultants(any(), any(), any(), any())) .thenReturn(new EasyRandom().nextObject(ConsultantSearchResultDTO.class)); this.userAdminService.getConsultantsOfAgency(agencyId, currentPage, perPage); @@ -89,7 +88,7 @@ public void getConsultantsOfAgency_Should_callServicesCorrectly() { } @Test - public void addTenantHeader_WhenMultitenacy_Enabled() { + void addTenantHeader_WhenMultitenacy_Enabled() { TenantContext.setCurrentTenant(1L); ApiClient apiClient = new ApiClient(); TenantHeaderSupplier tenantHeaderSupplier = new TenantHeaderSupplier(); diff --git a/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agency/AgencyAdminFullResponseDTOBuilderTest.java b/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agency/AgencyAdminFullResponseDTOBuilderTest.java index e0e76eac..af6fd266 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agency/AgencyAdminFullResponseDTOBuilderTest.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agency/AgencyAdminFullResponseDTOBuilderTest.java @@ -116,16 +116,16 @@ void fromAgency_Should_Return_ValidHalLinks() { assertEquals(TENANT_ID, result.getEmbedded().getTenantId()); assertThat(agencyLinks.getSelf()).isNotNull(); assertThat(agencyLinks.getSelf().getMethod()).isEqualTo(MethodEnum.GET); - assertThat(agencyLinks.getSelf().getHref()).isEqualTo(String.format("/agencyadmin/agencies/%s", agency.getId())); + assertThat(agencyLinks.getSelf().getHref()).isEqualTo("/agencyadmin/agencies/%s".formatted(agency.getId())); assertThat(agencyLinks.getDelete()).isNotNull(); assertThat(agencyLinks.getDelete().getMethod()).isEqualTo(MethodEnum.DELETE); - assertThat(agencyLinks.getDelete().getHref()).isEqualTo(String.format("/agencyadmin/agencies/%s", agency.getId())); + assertThat(agencyLinks.getDelete().getHref()).isEqualTo("/agencyadmin/agencies/%s".formatted(agency.getId())); assertThat(agencyLinks.getUpdate()).isNotNull(); assertThat(agencyLinks.getUpdate().getMethod()).isEqualTo(MethodEnum.PUT); - assertThat(agencyLinks.getUpdate().getHref()).isEqualTo(String.format("/agencyadmin/agencies/%s", agency.getId())); + assertThat(agencyLinks.getUpdate().getHref()).isEqualTo("/agencyadmin/agencies/%s".formatted(agency.getId())); assertThat(agencyLinks.getPostcodeRanges()).isNotNull(); assertThat(agencyLinks.getPostcodeRanges().getMethod()).isEqualTo(MethodEnum.GET); - assertThat(agencyLinks.getPostcodeRanges().getHref()).isEqualTo(String.format("/agencyadmin/postcoderanges/%s", this.agency.getId())); + assertThat(agencyLinks.getPostcodeRanges().getHref()).isEqualTo("/agencyadmin/postcoderanges/%s".formatted(this.agency.getId())); } } diff --git a/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agency/AgencyAdminSearchServiceIT.java b/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agency/AgencyAdminSearchServiceIT.java index 7eb068cf..726d5377 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agency/AgencyAdminSearchServiceIT.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agency/AgencyAdminSearchServiceIT.java @@ -14,7 +14,6 @@ import de.caritas.cob.agencyservice.useradminservice.generated.web.model.AgencyAdminFullResponseDTO; import de.caritas.cob.agencyservice.useradminservice.generated.web.model.AgencyAdminResponseDTO; import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace; @@ -22,13 +21,11 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpHeaders; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; -@RunWith(SpringRunner.class) @SpringBootTest(classes = AgencyServiceApplication.class) @TestPropertySource(properties = "spring.profiles.active=testing") @AutoConfigureTestDatabase(replace = Replace.ANY) diff --git a/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agency/AgencyAdminSearchServiceIntegrationTests.java b/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agency/AgencyAdminSearchServiceIntegrationTests.java index 489d12e9..fef90cf2 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agency/AgencyAdminSearchServiceIntegrationTests.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agency/AgencyAdminSearchServiceIntegrationTests.java @@ -21,10 +21,9 @@ import java.util.List; import java.util.Set; import java.util.stream.Collectors; -import org.junit.Test; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; @@ -34,16 +33,14 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; -@RunWith(SpringRunner.class) @SpringBootTest(classes = AgencyServiceApplication.class) @TestPropertySource(properties = "spring.profiles.active=testing") @AutoConfigureTestDatabase(replace = Replace.ANY) @DirtiesContext(classMode = ClassMode.BEFORE_CLASS) @Transactional -public class AgencyAdminSearchServiceIntegrationTests { +class AgencyAdminSearchServiceIntegrationTests { @Autowired private AgencyAdminSearchService agencyAdminSearchService; @@ -52,12 +49,12 @@ public class AgencyAdminSearchServiceIntegrationTests { AuthenticatedUser authenticatedUser; @BeforeEach - public void setUp() { + void setUp() { Mockito.when(authenticatedUser.hasRestrictedAgencyPriviliges()).thenReturn(false); } @Test - public void searchAgencies_Should_returnOneResult_When_perPageIsSetToOne() { + void searchAgencies_Should_returnOneResult_When_perPageIsSetToOne() { List agencies = this.agencyAdminSearchService .searchAgencies("", 0, 1, null) .getEmbedded(); @@ -66,7 +63,7 @@ public void searchAgencies_Should_returnOneResult_When_perPageIsSetToOne() { } @Test - public void searchAgencies_Should_returnOneResult_When_perPageIsSetToOneAndPageIsSetToOne() { + void searchAgencies_Should_returnOneResult_When_perPageIsSetToOneAndPageIsSetToOne() { List agencies = this.agencyAdminSearchService .searchAgencies("", 1, 1, null) .getEmbedded(); @@ -75,7 +72,7 @@ public void searchAgencies_Should_returnOneResult_When_perPageIsSetToOneAndPageI } @Test - public void searchAgencies_Should_returnEmptyList_When_paginationParamsAreZero() { + void searchAgencies_Should_returnEmptyList_When_paginationParamsAreZero() { List agencies = this.agencyAdminSearchService .searchAgencies(null, 0, 0, null) .getEmbedded(); @@ -84,7 +81,7 @@ public void searchAgencies_Should_returnEmptyList_When_paginationParamsAreZero() } @Test - public void searchAgencies_Should_returnEmptyList_When_paginationParamsAreNegative() { + void searchAgencies_Should_returnEmptyList_When_paginationParamsAreNegative() { List agencies = this.agencyAdminSearchService .searchAgencies(null, -100, -1000, null) .getEmbedded(); @@ -93,7 +90,7 @@ public void searchAgencies_Should_returnEmptyList_When_paginationParamsAreNegati } @Test - public void searchAgencies_Should_returnAllEntities_When_keywordIsNull() { + void searchAgencies_Should_returnAllEntities_When_keywordIsNull() { List agencies = this.agencyAdminSearchService .searchAgencies(null, 0, 1133, null) .getEmbedded(); @@ -102,7 +99,7 @@ public void searchAgencies_Should_returnAllEntities_When_keywordIsNull() { } @Test - public void searchAgencies_Should_returnEntitiesSorted_When_SortParameterGiven() { + void searchAgencies_Should_returnEntitiesSorted_When_SortParameterGiven() { Sort sort = new Sort(); sort.setField(FieldEnum.NAME); sort.setOrder(OrderEnum.ASC); @@ -124,14 +121,12 @@ public void searchAgencies_Should_returnEntitiesSorted_When_SortParameterGiven() .collect(Collectors.toList()); // cannot force collation for H2, but for MariaDB it will use proper utf8_unicode_ci due to usage of lower function which by default uses utf8_unicode_ci - agenciesSorted.forEach(el -> { - Assertions.assertEquals('Ö', el.charAt(0)); - }); + agenciesSorted.forEach(el -> Assertions.assertEquals('Ö', el.charAt(0))); } @Test - public void searchAgencies_Should_returnAllEntities_When_keywordIsEmpty() { + void searchAgencies_Should_returnAllEntities_When_keywordIsEmpty() { List agencies = this.agencyAdminSearchService .searchAgencies("", 0, 1133, null) .getEmbedded(); @@ -140,7 +135,7 @@ public void searchAgencies_Should_returnAllEntities_When_keywordIsEmpty() { } @Test - public void searchAgencies_Should_returnPaginatedEntities_When_paginationParamsAreSplitted() { + void searchAgencies_Should_returnPaginatedEntities_When_paginationParamsAreSplitted() { List firstPage = this.agencyAdminSearchService .searchAgencies("", 1, 1000, null) .getEmbedded(); @@ -153,7 +148,7 @@ public void searchAgencies_Should_returnPaginatedEntities_When_paginationParamsA } @Test - public void searchAgencies_Should_returnMatchingAgencies_When_nameContainsDashIndexedValues() { + void searchAgencies_Should_returnMatchingAgencies_When_nameContainsDashIndexedValues() { List agencies = this.agencyAdminSearchService .searchAgencies("Oberschwaben", 0, 2, null) .getEmbedded(); @@ -163,7 +158,7 @@ public void searchAgencies_Should_returnMatchingAgencies_When_nameContainsDashIn } @Test - public void searchAgencies_Should_returnMatchingAgencies_When_nameContainsUmlautReplacements() { + void searchAgencies_Should_returnMatchingAgencies_When_nameContainsUmlautReplacements() { agencyAdminSearchService .searchAgencies("Uberlingen", 0, 4, null) .getEmbedded() @@ -173,7 +168,7 @@ public void searchAgencies_Should_returnMatchingAgencies_When_nameContainsUmlaut } @Test - public void searchAgencies_Should_returnMatchingAgencies_When_nameContainsUmlauts() { + void searchAgencies_Should_returnMatchingAgencies_When_nameContainsUmlauts() { agencyAdminSearchService .searchAgencies("Überlingen", 0, 2, null) .getEmbedded() @@ -183,7 +178,7 @@ public void searchAgencies_Should_returnMatchingAgencies_When_nameContainsUmlaut } @Test - public void searchAgencies_Should_returnMatchingAgencies_When_keywordIsValidPlz() { + void searchAgencies_Should_returnMatchingAgencies_When_keywordIsValidPlz() { List agencies = this.agencyAdminSearchService .searchAgencies("88662", 0, 5, null) .getEmbedded(); @@ -192,7 +187,7 @@ public void searchAgencies_Should_returnMatchingAgencies_When_keywordIsValidPlz( } @Test - public void searchAgencies_Should_returnMatchingAgencies_When_keywordIsContainedInDifferentFields() { + void searchAgencies_Should_returnMatchingAgencies_When_keywordIsContainedInDifferentFields() { List agencies = this.agencyAdminSearchService .searchAgencies("1", 0, 500, null) .getEmbedded(); @@ -206,7 +201,7 @@ public void searchAgencies_Should_returnMatchingAgencies_When_keywordIsContained } @Test - public void searchAgencies_Should_returnValidResult_When_keywordContainsOnlySpecialCharacters() { + void searchAgencies_Should_returnValidResult_When_keywordContainsOnlySpecialCharacters() { var agencies = agencyAdminSearchService .searchAgencies("§$%=#'`><", 0, 5, null) .getEmbedded(); @@ -215,7 +210,7 @@ public void searchAgencies_Should_returnValidResult_When_keywordContainsOnlySpec } @Test - public void searchAgencies_Should_returnValidResult_When_keywordHasSpecialCharacters() { + void searchAgencies_Should_returnValidResult_When_keywordHasSpecialCharacters() { var specialChars = "halle§$%=#'`><"; var agencies = agencyAdminSearchService @@ -226,7 +221,7 @@ public void searchAgencies_Should_returnValidResult_When_keywordHasSpecialCharac } @Test - public void searchAgencies_Should_returnValidResult_When_keywordHasLuceneQuerySyntax() { + void searchAgencies_Should_returnValidResult_When_keywordHasLuceneQuerySyntax() { var specialChars = "halle+-&|!(){}[]^\"~*?:\\/"; var agencies = agencyAdminSearchService @@ -237,7 +232,7 @@ public void searchAgencies_Should_returnValidResult_When_keywordHasLuceneQuerySy } @Test - public void buildAgencyAdminSearchResult_Should_returnExpectedMappedResponseDTO_When_searchForSpecialAgency() { + void buildAgencyAdminSearchResult_Should_returnExpectedMappedResponseDTO_When_searchForSpecialAgency() { String keyword = "Schwangerschaftsberatungsstelle Sch"; AgencyAdminFullResponseDTO firstSearchResult = this.agencyAdminSearchService @@ -260,7 +255,7 @@ public void buildAgencyAdminSearchResult_Should_returnExpectedMappedResponseDTO_ } @Test - public void buildAgencyAdminSearchResult_Should_haveExpectedLinks_When_search() { + void buildAgencyAdminSearchResult_Should_haveExpectedLinks_When_search() { AgencyAdminSearchResultDTO agencyAdminSearchResultDTO = this.agencyAdminSearchService .searchAgencies("a", 1, 20, null); @@ -278,7 +273,7 @@ public void buildAgencyAdminSearchResult_Should_haveExpectedLinks_When_search() } @Test - public void buildAgencyAdminSearchResult_Should_returnExpectedLinksForAgencies() { + void buildAgencyAdminSearchResult_Should_returnExpectedLinksForAgencies() { AgencyAdminSearchResultDTO searchResult = this.agencyAdminSearchService .searchAgencies("", 0, 2, null); @@ -288,19 +283,19 @@ public void buildAgencyAdminSearchResult_Should_returnExpectedLinksForAgencies() assertThat(agencyLinks.getSelf(), notNullValue()); assertThat(agencyLinks.getSelf().getMethod(), is(MethodEnum.GET)); assertThat(agencyLinks.getSelf().getHref(), - endsWith(String.format("/agencyadmin/agencies/%s", result.getEmbedded().getId()))); + endsWith("/agencyadmin/agencies/%s".formatted(result.getEmbedded().getId()))); assertThat(agencyLinks.getDelete(), notNullValue()); assertThat(agencyLinks.getDelete().getMethod(), is(MethodEnum.DELETE)); assertThat(agencyLinks.getDelete().getHref(), - endsWith(String.format("/agencyadmin/agencies/%s", result.getEmbedded().getId()))); + endsWith("/agencyadmin/agencies/%s".formatted(result.getEmbedded().getId()))); assertThat(agencyLinks.getUpdate(), notNullValue()); assertThat(agencyLinks.getUpdate().getMethod(), is(MethodEnum.PUT)); assertThat(agencyLinks.getUpdate().getHref(), - endsWith(String.format("/agencyadmin/agencies/%s", result.getEmbedded().getId()))); + endsWith("/agencyadmin/agencies/%s".formatted(result.getEmbedded().getId()))); assertThat(agencyLinks.getPostcodeRanges(), notNullValue()); assertThat(agencyLinks.getPostcodeRanges().getMethod(), is(MethodEnum.GET)); assertThat(agencyLinks.getPostcodeRanges().getHref(), - endsWith(String.format("/agencyadmin/postcoderanges/%s", result.getEmbedded().getId()))); + endsWith("/agencyadmin/postcoderanges/%s".formatted(result.getEmbedded().getId()))); } } } diff --git a/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agency/AgencyAdminSearchTenantSupportServiceTest.java b/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agency/AgencyAdminSearchTenantSupportServiceTest.java index e6b477eb..9e4b0181 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agency/AgencyAdminSearchTenantSupportServiceTest.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agency/AgencyAdminSearchTenantSupportServiceTest.java @@ -10,7 +10,6 @@ import de.caritas.cob.agencyservice.config.apiclient.UserAdminServiceApiControllerFactory; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; import org.mockito.Mock; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; @@ -18,13 +17,11 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpHeaders; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; import de.caritas.cob.agencyservice.useradminservice.generated.web.model.AdminAgencyResponseDTO; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; -@RunWith(SpringRunner.class) @SpringBootTest(classes = AgencyServiceApplication.class) @TestPropertySource(properties = "spring.profiles.active=testing") @TestPropertySource(properties = "multitenancy.enabled=true") diff --git a/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agency/AgencyTopicEnrichmentServiceTest.java b/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agency/AgencyTopicEnrichmentServiceTest.java index 3a84b672..0118c575 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agency/AgencyTopicEnrichmentServiceTest.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agency/AgencyTopicEnrichmentServiceTest.java @@ -13,7 +13,6 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import de.caritas.cob.agencyservice.topicservice.generated.web.model.TopicDTO; -import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) diff --git a/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agencypostcoderange/AgencyPostcodeRangeAdminServiceIT.java b/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agencypostcoderange/AgencyPostcodeRangeAdminServiceIT.java index 9fedffe0..72bdc441 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agencypostcoderange/AgencyPostcodeRangeAdminServiceIT.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agencypostcoderange/AgencyPostcodeRangeAdminServiceIT.java @@ -1,19 +1,18 @@ package de.caritas.cob.agencyservice.api.admin.service.agencypostcoderange; +import static org.junit.jupiter.api.Assertions.assertThrows; + import de.caritas.cob.agencyservice.AgencyServiceApplication; import de.caritas.cob.agencyservice.api.exception.httpresponses.NotFoundException; import de.caritas.cob.agencyservice.api.repository.agencypostcoderange.AgencyPostcodeRangeRepository; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; -@RunWith(SpringRunner.class) @SpringBootTest(classes = AgencyServiceApplication.class) @TestPropertySource(properties = "spring.profiles.active=testing") @AutoConfigureTestDatabase(replace = Replace.ANY) @@ -41,9 +40,9 @@ public void deleteAgencyPostcodeRange_Should_deletePostcodeRange_When_agencyIdEx super.deleteAgencyPostcodeRange_Should_deletePostcodeRange_When_agencyIdExists(); } - @Test(expected = NotFoundException.class) + @Test public void deleteAgencyPostcodeRange_Should_throwNotFound_When_agencyIdNotExists() { - super.deleteAgencyPostcodeRange_Should_throwNotFound_When_agencyIdNotExists(); + assertThrows(NotFoundException.class, () -> super.deleteAgencyPostcodeRange_Should_throwNotFound_When_agencyIdNotExists()); } } diff --git a/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agencypostcoderange/AgencyPostcodeRangeAdminServiceTenantAwareIT.java b/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agencypostcoderange/AgencyPostcodeRangeAdminServiceTenantAwareIT.java index bcbd83a0..fd8014a6 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agencypostcoderange/AgencyPostcodeRangeAdminServiceTenantAwareIT.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agencypostcoderange/AgencyPostcodeRangeAdminServiceTenantAwareIT.java @@ -7,11 +7,10 @@ import de.caritas.cob.agencyservice.api.exception.httpresponses.NotFoundException; import de.caritas.cob.agencyservice.api.repository.agencypostcoderange.AgencyPostcodeRangeRepository; import de.caritas.cob.agencyservice.api.tenant.TenantContext; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +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; @@ -21,10 +20,8 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.jdbc.Sql.ExecutionPhase; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; -@RunWith(SpringRunner.class) @SpringBootTest(classes = AgencyServiceApplication.class) @TestPropertySource(properties = "spring.profiles.active=testing") @AutoConfigureTestDatabase(replace = Replace.ANY) @@ -36,12 +33,12 @@ public class AgencyPostcodeRangeAdminServiceTenantAwareIT extends AgencyPostcode final static long AGENCY_WITH_TENANT_ID_2 = 1734L; - @Before + @BeforeEach public void beforeEach() { TenantContext.setCurrentTenant(1L); } - @After + @AfterEach public void afterEach() { TenantContext.clear(); } @@ -65,7 +62,7 @@ public void findPostcodeRangesForAgency_Should_returnExpectedResult_When_postcod .getEmbedded(); assertThat(postcodeRange, notNullValue()); assertThat(postcodeRange.getId(), notNullValue()); - Assert.assertEquals("", postcodeRange.getPostcodeRanges()); + Assertions.assertEquals("", postcodeRange.getPostcodeRanges()); } @Test diff --git a/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agencypostcoderange/AgencyPostcodeRangeAdminServiceTest.java b/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agencypostcoderange/AgencyPostcodeRangeAdminServiceTest.java index 684fbf22..d6e273df 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agencypostcoderange/AgencyPostcodeRangeAdminServiceTest.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/admin/service/agencypostcoderange/AgencyPostcodeRangeAdminServiceTest.java @@ -145,7 +145,7 @@ void updatePostcodeRange_Should_RemovePostcodeToOverwrite_BeforeValidation() { AgencyPostcodeRange.class)); agencyPostcodeRangeAdminService.updatePostcodeRange(AGENCY_ID, postcodeRangeDTO); - ArgumentCaptor> captor = ArgumentCaptor.forClass((Class) List.class); + ArgumentCaptor> captor = ArgumentCaptor.forClass((Class) Set.class); verify(postcodeRangeValidator).validatePostcodeRanges(captor.capture()); assertThat(captor.getValue(), not(hasItem(agencyPostCodeRange))); } diff --git a/src/test/java/de/caritas/cob/agencyservice/api/admin/validation/AgencyValidatorIT.java b/src/test/java/de/caritas/cob/agencyservice/api/admin/validation/AgencyValidatorIT.java index e95dcd22..c6147123 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/admin/validation/AgencyValidatorIT.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/admin/validation/AgencyValidatorIT.java @@ -6,6 +6,7 @@ import static de.caritas.cob.agencyservice.testHelper.TestConstants.INVALID_POSTCODE; import static de.caritas.cob.agencyservice.testHelper.TestConstants.VALID_POSTCODE; import static java.util.Collections.singletonList; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; @@ -14,20 +15,25 @@ import de.caritas.cob.agencyservice.AgencyServiceApplication; import de.caritas.cob.agencyservice.api.admin.service.UserAdminService; +import de.caritas.cob.agencyservice.api.admin.validation.validators.AgencyDataProtectionValidator; import de.caritas.cob.agencyservice.api.exception.MissingConsultingTypeException; import de.caritas.cob.agencyservice.api.exception.httpresponses.InvalidConsultingTypeException; import de.caritas.cob.agencyservice.api.exception.httpresponses.InvalidOfflineStatusException; import de.caritas.cob.agencyservice.api.exception.httpresponses.InvalidPostcodeException; +import de.caritas.cob.agencyservice.api.service.TenantService; import de.caritas.cob.agencyservice.api.util.AuthenticatedUser; import de.caritas.cob.agencyservice.api.manager.consultingtype.ConsultingTypeManager; import de.caritas.cob.agencyservice.api.model.AgencyDTO; import de.caritas.cob.agencyservice.api.model.UpdateAgencyDTO; import de.caritas.cob.agencyservice.consultingtypeservice.generated.web.model.ExtendedConsultingTypeResponseDTO; import de.caritas.cob.agencyservice.consultingtypeservice.generated.web.model.ExtendedConsultingTypeResponseDTOAllOfWhiteSpot; +import de.caritas.cob.agencyservice.tenantservice.generated.web.model.RestrictedTenantDTO; import de.caritas.cob.agencyservice.useradminservice.generated.web.model.ConsultantAdminResponseDTO; +import org.aspectj.lang.annotation.Before; import org.jeasy.random.EasyRandom; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace; @@ -36,14 +42,12 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; -@RunWith(SpringRunner.class) @SpringBootTest(classes = AgencyServiceApplication.class) @TestPropertySource(properties = "spring.profiles.active=testing") @AutoConfigureTestDatabase(replace = Replace.ANY) @DirtiesContext(classMode = ClassMode.BEFORE_CLASS) -public class AgencyValidatorIT { +class AgencyValidatorIT { @Autowired private AgencyValidator agencyValidator; @@ -57,47 +61,62 @@ public class AgencyValidatorIT { @MockBean private AuthenticatedUser authenticatedUser; - @Test(expected = InvalidPostcodeException.class) - public void validate_Should_ThrowInvalidPostcodeException_WhenCreateAndAgencyPostcodeIsInvalid() { - AgencyDTO agencyDTO = getValidAgencyDTO(); - agencyDTO.setPostcode(INVALID_POSTCODE); - agencyValidator.validate(agencyDTO); + @MockBean TenantService tenantService; + + @MockBean + AgencyDataProtectionValidator agencyDataProtectionValidator; + + + @BeforeEach + public void setUp() { + Mockito.when(tenantService.getRestrictedTenantDataByTenantId(Mockito.anyLong())).thenReturn(new RestrictedTenantDTO()); } @Test - public void validate_Should_NotThrowInvalidPostcodeException_WhenCreateAndAgencyPostcodeIsValid() { + void validate_Should_ThrowInvalidPostcodeException_WhenCreateAndAgencyPostcodeIsInvalid() { + assertThrows(InvalidPostcodeException.class, () -> { + AgencyDTO agencyDTO = getValidAgencyDTO(); + agencyDTO.setPostcode(INVALID_POSTCODE); + agencyValidator.validate(agencyDTO); + }); + } + + @Test + void validate_Should_NotThrowInvalidPostcodeException_WhenCreateAndAgencyPostcodeIsValid() { AgencyDTO agencyDTO = getValidAgencyDTO(); agencyDTO.setPostcode(VALID_POSTCODE); agencyValidator.validate(agencyDTO); } - @Test(expected = InvalidConsultingTypeException.class) - public void validate_Should_ThrowInvalidConsultingTypeException_WhenCreateAndAgencyConsultingTypeIsInvalid() - throws MissingConsultingTypeException { - when(consultingTypeManager.getConsultingTypeSettings(anyInt())).thenThrow(new MissingConsultingTypeException("")); - AgencyDTO agencyDTO = getValidAgencyDTO(); - agencyDTO.setConsultingType(INVALID_CONSULTING_TYPE_VALUE); - agencyValidator.validate(agencyDTO); + @Test + void validate_Should_ThrowInvalidConsultingTypeException_WhenCreateAndAgencyConsultingTypeIsInvalid() { + assertThrows(InvalidConsultingTypeException.class, () -> { + when(consultingTypeManager.getConsultingTypeSettings(anyInt())).thenThrow(new MissingConsultingTypeException("")); + AgencyDTO agencyDTO = getValidAgencyDTO(); + agencyDTO.setConsultingType(INVALID_CONSULTING_TYPE_VALUE); + agencyValidator.validate(agencyDTO); + }); } @Test - public void validate_Should_NotThrowInvalidConsultingTypeException_WhenCreateAndAgencyConsultingTypeIsValid() { + void validate_Should_NotThrowInvalidConsultingTypeException_WhenCreateAndAgencyConsultingTypeIsValid() { AgencyDTO agencyDTO = getValidAgencyDTO(); agencyDTO.setConsultingType(CONSULTING_TYPE_SUCHT); agencyValidator.validate(agencyDTO); } - @Test(expected = InvalidPostcodeException.class) - public void validate_Should_ThrowInvalidPostcodeException_WhenUpdateAndAgencyPostcodeIsInvalid() - throws MissingConsultingTypeException { - when(consultingTypeManager.getConsultingTypeSettings(0)).thenReturn(CONSULTING_TYPE_SETTINGS_SUCHT); - UpdateAgencyDTO updateAgencyDTO = getValidUpdateAgencyDTO(); - updateAgencyDTO.setPostcode(INVALID_POSTCODE); - agencyValidator.validate(1L, updateAgencyDTO); + @Test + void validate_Should_ThrowInvalidPostcodeException_WhenUpdateAndAgencyPostcodeIsInvalid() { + assertThrows(InvalidPostcodeException.class, () -> { + when(consultingTypeManager.getConsultingTypeSettings(0)).thenReturn(CONSULTING_TYPE_SETTINGS_SUCHT); + UpdateAgencyDTO updateAgencyDTO = getValidUpdateAgencyDTO(); + updateAgencyDTO.setPostcode(INVALID_POSTCODE); + agencyValidator.validate(1L, updateAgencyDTO); + }); } @Test - public void validate_Should_NotThrowInvalidPostcodeException_WhenUpdateAndAgencyPostcodeIsValid() + void validate_Should_NotThrowInvalidPostcodeException_WhenUpdateAndAgencyPostcodeIsValid() throws MissingConsultingTypeException { when(consultingTypeManager.getConsultingTypeSettings(0)).thenReturn(CONSULTING_TYPE_SETTINGS_SUCHT); UpdateAgencyDTO updateAgencyDTO = getValidUpdateAgencyDTO(); @@ -105,20 +124,21 @@ public void validate_Should_NotThrowInvalidPostcodeException_WhenUpdateAndAgency agencyValidator.validate(1L, updateAgencyDTO); } - @Test(expected = InvalidOfflineStatusException.class) - public void validate_Should_ThrowInvalidOfflineStatusException_WhenUpdateAndOfflineStatusIsInvalid() - throws MissingConsultingTypeException { - EasyRandom easyRandom = new EasyRandom(); - UpdateAgencyDTO updateAgencyDTO = getValidUpdateAgencyDTO(); - updateAgencyDTO.setOffline(false); - var extendedConsultingTypeResponseDTO = new ExtendedConsultingTypeResponseDTO(); - extendedConsultingTypeResponseDTO.setWhiteSpot(easyRandom.nextObject(ExtendedConsultingTypeResponseDTOAllOfWhiteSpot.class)); - when(consultingTypeManager.getConsultingTypeSettings(19)).thenReturn(extendedConsultingTypeResponseDTO); - agencyValidator.validate(1734L, updateAgencyDTO); + @Test + void validate_Should_ThrowInvalidOfflineStatusException_WhenUpdateAndOfflineStatusIsInvalid() { + assertThrows(InvalidOfflineStatusException.class, () -> { + EasyRandom easyRandom = new EasyRandom(); + UpdateAgencyDTO updateAgencyDTO = getValidUpdateAgencyDTO(); + updateAgencyDTO.setOffline(false); + var extendedConsultingTypeResponseDTO = new ExtendedConsultingTypeResponseDTO(); + extendedConsultingTypeResponseDTO.setWhiteSpot(easyRandom.nextObject(ExtendedConsultingTypeResponseDTOAllOfWhiteSpot.class)); + when(consultingTypeManager.getConsultingTypeSettings(19)).thenReturn(extendedConsultingTypeResponseDTO); + agencyValidator.validate(1734L, updateAgencyDTO); + }); } @Test - public void validate_Should_NotThrowInvalidOfflineStatusException_WhenUpdateAndOfflineStatusIsValid() + void validate_Should_NotThrowInvalidOfflineStatusException_WhenUpdateAndOfflineStatusIsValid() throws MissingConsultingTypeException { when(this.userAdminService.getConsultantsOfAgency(anyLong(), anyInt(), anyInt())) .thenReturn(singletonList(mock(ConsultantAdminResponseDTO.class))); diff --git a/src/test/java/de/caritas/cob/agencyservice/api/admin/validation/DeleteAgencyValidatorTest.java b/src/test/java/de/caritas/cob/agencyservice/api/admin/validation/DeleteAgencyValidatorTest.java index 8737f73c..652fce79 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/admin/validation/DeleteAgencyValidatorTest.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/admin/validation/DeleteAgencyValidatorTest.java @@ -2,6 +2,7 @@ import static de.caritas.cob.agencyservice.testHelper.TestConstants.CONSULTING_TYPE_SUCHT; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.when; @@ -16,13 +17,13 @@ import java.util.Collections; import java.util.stream.Collectors; import org.jeasy.random.EasyRandom; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) public class DeleteAgencyValidatorTest { @InjectMocks @@ -36,19 +37,21 @@ public class DeleteAgencyValidatorTest { private final EasyRandom easyRandom = new EasyRandom(); - @Test(expected = ConflictException.class) + @Test public void validate_Should_throwConflictException_When_agencyStillHasAConsultantAssigned() { - when(this.userAdminService.getConsultantsOfAgency(any(), anyInt(), anyInt())) - .thenReturn( - this.easyRandom - .objects(ConsultantAdminResponseDTO.class, 1) - .collect(Collectors.toList())); + assertThrows(ConflictException.class, () -> { + when(this.userAdminService.getConsultantsOfAgency(any(), anyInt(), anyInt())) + .thenReturn( + this.easyRandom + .objects(ConsultantAdminResponseDTO.class, 1) + .collect(Collectors.toList())); - easyRandom.nextObject(ExtendedConsultingTypeResponseDTO.class); + easyRandom.nextObject(ExtendedConsultingTypeResponseDTO.class); - Agency agency = this.easyRandom.nextObject(Agency.class); - agency.setConsultingTypeId(CONSULTING_TYPE_SUCHT); - this.deleteAgencyValidator.validate(agency); + Agency agency = this.easyRandom.nextObject(Agency.class); + agency.setConsultingTypeId(CONSULTING_TYPE_SUCHT); + this.deleteAgencyValidator.validate(agency); + }); } @Test diff --git a/src/test/java/de/caritas/cob/agencyservice/api/admin/validation/validators/AgencyConsultingTypeValidatorTest.java b/src/test/java/de/caritas/cob/agencyservice/api/admin/validation/validators/AgencyConsultingTypeValidatorTest.java index 9d8b2cf6..1b79bc33 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/admin/validation/validators/AgencyConsultingTypeValidatorTest.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/admin/validation/validators/AgencyConsultingTypeValidatorTest.java @@ -1,6 +1,7 @@ package de.caritas.cob.agencyservice.api.admin.validation.validators; import static de.caritas.cob.agencyservice.testHelper.TestConstants.CONSULTING_TYPE_AIDS; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.when; @@ -13,8 +14,8 @@ import de.caritas.cob.agencyservice.api.exception.httpresponses.InvalidConsultingTypeException; import de.caritas.cob.agencyservice.api.manager.consultingtype.ConsultingTypeManager; import org.jeasy.random.EasyRandom; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; public class AgencyConsultingTypeValidatorTest { @@ -26,7 +27,7 @@ public class AgencyConsultingTypeValidatorTest { private ExtendedConsultingTypeResponseDTO consultingTypeSettings; - @Before + @BeforeEach public void setup() { initMocks(this); EasyRandom easyRandom = new EasyRandom(); @@ -34,14 +35,15 @@ public void setup() { this.consultingTypeSettings = easyRandom.nextObject(ExtendedConsultingTypeResponseDTO.class); } - @Test(expected = InvalidConsultingTypeException.class) - public void validate_Should_ThrowInvalidConsultingTypeException_WhenConsultingTypeIsInvalid() - throws MissingConsultingTypeException { - this.validateAgencyDto.setConsultingType(-1); + @Test + public void validate_Should_ThrowInvalidConsultingTypeException_WhenConsultingTypeIsInvalid() { + assertThrows(InvalidConsultingTypeException.class, () -> { + this.validateAgencyDto.setConsultingType(-1); - when(consultingTypeManager.getConsultingTypeSettings(anyInt())).thenThrow(new MissingConsultingTypeException("")); + when(consultingTypeManager.getConsultingTypeSettings(anyInt())).thenThrow(new MissingConsultingTypeException("")); - new AgencyConsultingTypeValidator(consultingTypeManager).validate(validateAgencyDto); + new AgencyConsultingTypeValidator(consultingTypeManager).validate(validateAgencyDto); + }); } @Test diff --git a/src/test/java/de/caritas/cob/agencyservice/api/admin/validation/validators/AgencyOfflineStatusValidatorTest.java b/src/test/java/de/caritas/cob/agencyservice/api/admin/validation/validators/AgencyOfflineStatusValidatorTest.java index 2411937e..395665b9 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/admin/validation/validators/AgencyOfflineStatusValidatorTest.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/admin/validation/validators/AgencyOfflineStatusValidatorTest.java @@ -28,8 +28,8 @@ import java.util.Random; import java.util.stream.Stream; import org.jeasy.random.EasyRandom; -import org.junit.Test; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; diff --git a/src/test/java/de/caritas/cob/agencyservice/api/admin/validation/validators/AgencyPostcodeValidatorTest.java b/src/test/java/de/caritas/cob/agencyservice/api/admin/validation/validators/AgencyPostcodeValidatorTest.java index 9ff6ca0b..49317375 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/admin/validation/validators/AgencyPostcodeValidatorTest.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/admin/validation/validators/AgencyPostcodeValidatorTest.java @@ -2,6 +2,7 @@ import static de.caritas.cob.agencyservice.testHelper.TestConstants.INVALID_POSTCODE; import static de.caritas.cob.agencyservice.testHelper.TestConstants.VALID_POSTCODE; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import de.caritas.cob.agencyservice.api.admin.validation.validators.annotation.CreateAgencyValidator; @@ -9,23 +10,25 @@ import de.caritas.cob.agencyservice.api.admin.validation.validators.model.ValidateAgencyDTO; import de.caritas.cob.agencyservice.api.exception.httpresponses.InvalidPostcodeException; import org.jeasy.random.EasyRandom; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class AgencyPostcodeValidatorTest { private ValidateAgencyDTO validateAgencyDto; - @Before + @BeforeEach public void setup() { EasyRandom easyRandom = new EasyRandom(); this.validateAgencyDto = easyRandom.nextObject(ValidateAgencyDTO.class); } - @Test(expected = InvalidPostcodeException.class) + @Test public void validate_Should_ThrowInvalidPostcodeException_WhenPostcodeIsInvalid() { - this.validateAgencyDto.setPostcode(INVALID_POSTCODE); - new AgencyPostcodeValidator().validate(validateAgencyDto); + assertThrows(InvalidPostcodeException.class, () -> { + this.validateAgencyDto.setPostcode(INVALID_POSTCODE); + new AgencyPostcodeValidator().validate(validateAgencyDto); + }); } @Test diff --git a/src/test/java/de/caritas/cob/agencyservice/api/admin/validation/validators/AgencyUpdatePermissionValidatorTest.java b/src/test/java/de/caritas/cob/agencyservice/api/admin/validation/validators/AgencyUpdatePermissionValidatorTest.java index 81e33d25..75e160ed 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/admin/validation/validators/AgencyUpdatePermissionValidatorTest.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/admin/validation/validators/AgencyUpdatePermissionValidatorTest.java @@ -14,7 +14,6 @@ import org.mockito.junit.jupiter.MockitoExtension; import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) diff --git a/src/test/java/de/caritas/cob/agencyservice/api/authorization/AuthorityTest.java b/src/test/java/de/caritas/cob/agencyservice/api/authorization/AuthorityTest.java index 46fa0154..3d36ab2e 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/authorization/AuthorityTest.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/authorization/AuthorityTest.java @@ -6,7 +6,7 @@ import de.caritas.cob.agencyservice.api.authorization.Authority.AuthorityValue; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class AuthorityTest { diff --git a/src/test/java/de/caritas/cob/agencyservice/api/authorization/RoleAuthorizationAuthorityMapperTest.java b/src/test/java/de/caritas/cob/agencyservice/api/authorization/RoleAuthorizationAuthorityMapperTest.java index e7af266b..54703f01 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/authorization/RoleAuthorizationAuthorityMapperTest.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/authorization/RoleAuthorizationAuthorityMapperTest.java @@ -8,7 +8,7 @@ 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; diff --git a/src/test/java/de/caritas/cob/agencyservice/api/config/apiclient/UserAdminApiClientTest.java b/src/test/java/de/caritas/cob/agencyservice/api/config/apiclient/UserAdminApiClientTest.java index 3d18a591..c0e4271c 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/config/apiclient/UserAdminApiClientTest.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/config/apiclient/UserAdminApiClientTest.java @@ -5,52 +5,46 @@ import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.collection.IsMapContaining.hasEntry; +import static org.junit.jupiter.api.Assertions.assertThrows; import de.caritas.cob.agencyservice.api.exception.httpresponses.InternalServerErrorException; import de.caritas.cob.agencyservice.config.apiclient.UserAdminApiClient; import de.caritas.cob.agencyservice.useradminservice.generated.web.model.ConsultantFilter; import java.util.List; import org.jeasy.random.EasyRandom; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.util.MultiValueMap; -@RunWith(SpringRunner.class) -public class UserAdminApiClientTest { +@ExtendWith(SpringExtension.class) +class UserAdminApiClientTest { private static final String FILTER_NAME = "filter"; @InjectMocks UserAdminApiClient userAdminApiClient; - @Test(expected = InternalServerErrorException.class) - public void parameterToMultiValueMap_Should_throwInternalServerErrorException_When_reflectionOfQueryValueObjectFails() { - userAdminApiClient.parameterToMultiValueMap(null, FILTER_NAME, new InvalidObject()); - } - @Test - public void parameterToMultiValueMap_Should_notAddNullValuesToQueryParamMap() { + void parameterToMultiValueMap_Should_notAddNullValuesToQueryParamMap() { EasyRandom easyRandom = new EasyRandom(); ConsultantFilter consultantFilter = easyRandom.nextObject(ConsultantFilter.class); consultantFilter.setEmail(null); - MultiValueMap result = - userAdminApiClient.parameterToMultiValueMap(null, FILTER_NAME, consultantFilter); + MultiValueMap result = userAdminApiClient.parameterToMultiValueMap(null, FILTER_NAME, consultantFilter); assertThat(result, not(hasEntry("email", null))); } @Test - public void parameterToMultiValueMap_Should_containAllNonNullValuesAsQueryParams() { + void parameterToMultiValueMap_Should_containAllNonNullValuesAsQueryParams() { ConsultantFilter consultantFilter = new ConsultantFilter() .lastname("lastname") .email("email") .agencyId(1L); - MultiValueMap result = - userAdminApiClient.parameterToMultiValueMap(null, FILTER_NAME, consultantFilter); + MultiValueMap result = userAdminApiClient.parameterToMultiValueMap(null, FILTER_NAME, consultantFilter); assertThat(result.size(), is(3)); assertThat(result.get("lastname").get(0), is("lastname")); @@ -59,11 +53,10 @@ public void parameterToMultiValueMap_Should_containAllNonNullValuesAsQueryParams } @Test - public void parameterToMultiValueMap_Should_returnValuesFormattedBySuperClass_When_providedWithInvalidQueryParams() { + void parameterToMultiValueMap_Should_returnValuesFormattedBySuperClass_When_providedWithInvalidQueryParams() { List list = asList("lastname", "email"); - MultiValueMap result = - userAdminApiClient.parameterToMultiValueMap(null, "no_filter", list); + MultiValueMap result = userAdminApiClient.parameterToMultiValueMap(null, "no_filter", list); assertThat(result.size(), is(1)); assertThat(result.get("no_filter").get(0), is("lastname,email")); @@ -71,7 +64,7 @@ public void parameterToMultiValueMap_Should_returnValuesFormattedBySuperClass_Wh class InvalidObject { - public String getValueWithoutProperty() { + String getValueWithoutProperty() { return "test"; } } diff --git a/src/test/java/de/caritas/cob/agencyservice/api/controller/ActuatorControllerIT.java b/src/test/java/de/caritas/cob/agencyservice/api/controller/ActuatorControllerIT.java index 0d643308..a2b0e3ad 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/controller/ActuatorControllerIT.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/controller/ActuatorControllerIT.java @@ -11,7 +11,7 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -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/agencyservice/api/controller/AgencyAdminControllerIT.java b/src/test/java/de/caritas/cob/agencyservice/api/controller/AgencyAdminControllerIT.java index 01397182..4d371043 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/controller/AgencyAdminControllerIT.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/controller/AgencyAdminControllerIT.java @@ -1,9 +1,8 @@ package de.caritas.cob.agencyservice.api.controller; -import static javax.ws.rs.core.MediaType.APPLICATION_JSON; +import static jakarta.ws.rs.core.MediaType.APPLICATION_JSON; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; -import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.anyInt; import static org.mockito.Mockito.when; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; diff --git a/src/test/java/de/caritas/cob/agencyservice/api/controller/AgencyAdminControllerWithDemographicsIT.java b/src/test/java/de/caritas/cob/agencyservice/api/controller/AgencyAdminControllerWithDemographicsIT.java index 489b4f90..a7a31f0b 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/controller/AgencyAdminControllerWithDemographicsIT.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/controller/AgencyAdminControllerWithDemographicsIT.java @@ -1,7 +1,7 @@ package de.caritas.cob.agencyservice.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.contains; import static org.mockito.Mockito.anyInt; import static org.mockito.Mockito.when; diff --git a/src/test/java/de/caritas/cob/agencyservice/api/controller/AgencyAdminControllerWithTopicsIT.java b/src/test/java/de/caritas/cob/agencyservice/api/controller/AgencyAdminControllerWithTopicsIT.java index 6d47367b..f8d05828 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/controller/AgencyAdminControllerWithTopicsIT.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/controller/AgencyAdminControllerWithTopicsIT.java @@ -1,7 +1,7 @@ package de.caritas.cob.agencyservice.api.controller; -import static javax.ws.rs.core.MediaType.APPLICATION_JSON; +import static jakarta.ws.rs.core.MediaType.APPLICATION_JSON; import static org.mockito.Mockito.anyInt; import static org.mockito.Mockito.when; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; diff --git a/src/test/java/de/caritas/cob/agencyservice/api/controller/AgencyControllerIT.java b/src/test/java/de/caritas/cob/agencyservice/api/controller/AgencyControllerIT.java index f6ae2b9d..ae2430dd 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/controller/AgencyControllerIT.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/controller/AgencyControllerIT.java @@ -16,7 +16,6 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; diff --git a/src/test/java/de/caritas/cob/agencyservice/api/exception/customheader/CustomHttpHeaderTest.java b/src/test/java/de/caritas/cob/agencyservice/api/exception/customheader/CustomHttpHeaderTest.java index 7563627d..ef84f3e3 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/exception/customheader/CustomHttpHeaderTest.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/exception/customheader/CustomHttpHeaderTest.java @@ -1,10 +1,10 @@ package de.caritas.cob.agencyservice.api.exception.customheader; -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 de.caritas.cob.agencyservice.api.exception.httpresponses.HttpStatusExceptionReason; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; public class CustomHttpHeaderTest { diff --git a/src/test/java/de/caritas/cob/agencyservice/api/manager/consultingtype/ConsultingTypeManagerIT.java b/src/test/java/de/caritas/cob/agencyservice/api/manager/consultingtype/ConsultingTypeManagerIT.java index 912a4a94..b2c82a39 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/manager/consultingtype/ConsultingTypeManagerIT.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/manager/consultingtype/ConsultingTypeManagerIT.java @@ -1,7 +1,7 @@ package de.caritas.cob.agencyservice.api.manager.consultingtype; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.when; @@ -10,18 +10,15 @@ import de.caritas.cob.agencyservice.api.exception.MissingConsultingTypeException; import de.caritas.cob.agencyservice.api.service.ConsultingTypeService; import de.caritas.cob.agencyservice.consultingtypeservice.generated.web.model.ExtendedConsultingTypeResponseDTO; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestClientException; -@RunWith(SpringRunner.class) @SpringBootTest(classes = AgencyServiceApplication.class) @TestPropertySource(properties = "spring.profiles.active=testing") @AutoConfigureTestDatabase(replace = Replace.ANY) diff --git a/src/test/java/de/caritas/cob/agencyservice/api/manager/consultingtype/ConsultingTypeManagerTest.java b/src/test/java/de/caritas/cob/agencyservice/api/manager/consultingtype/ConsultingTypeManagerTest.java index 5fcd5545..4e09a1db 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/manager/consultingtype/ConsultingTypeManagerTest.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/manager/consultingtype/ConsultingTypeManagerTest.java @@ -2,7 +2,7 @@ import static de.caritas.cob.agencyservice.testHelper.TestConstants.CONSULTING_TYPE_SETTINGS_SUCHT; import static de.caritas.cob.agencyservice.testHelper.TestConstants.CONSULTING_TYPE_SUCHT; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.when; @@ -10,14 +10,14 @@ import de.caritas.cob.agencyservice.api.exception.MissingConsultingTypeException; import de.caritas.cob.agencyservice.api.service.ConsultingTypeService; import de.caritas.cob.agencyservice.consultingtypeservice.generated.web.model.ExtendedConsultingTypeResponseDTO; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.web.client.RestClientException; -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class ConsultingTypeManagerTest { @InjectMocks diff --git a/src/test/java/de/caritas/cob/agencyservice/api/repository/agency/AgencyRepositoryIT.java b/src/test/java/de/caritas/cob/agencyservice/api/repository/agency/AgencyRepositoryIT.java index f0db961d..c475eb1d 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/repository/agency/AgencyRepositoryIT.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/repository/agency/AgencyRepositoryIT.java @@ -4,18 +4,15 @@ import de.caritas.cob.agencyservice.api.repository.agencytopic.AgencyTopic; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit.jupiter.SpringExtension; @TestPropertySource(properties = {"spring.profiles.active=testing"}) @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.ANY) -@ExtendWith(SpringExtension.class) @DataJpaTest class AgencyRepositoryIT { diff --git a/src/test/java/de/caritas/cob/agencyservice/api/repository/agency/AgencyRepositoryTenantAwareIT.java b/src/test/java/de/caritas/cob/agencyservice/api/repository/agency/AgencyRepositoryTenantAwareIT.java index 6a774d35..db41347c 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/repository/agency/AgencyRepositoryTenantAwareIT.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/repository/agency/AgencyRepositoryTenantAwareIT.java @@ -3,17 +3,14 @@ import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit.jupiter.SpringExtension; @TestPropertySource(properties = {"spring.profiles.active=testing"}) @TestPropertySource(properties = "multitenancy.enabled=true") @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.ANY) -@ExtendWith(SpringExtension.class) @DataJpaTest class AgencyRepositoryTenantAwareIT { diff --git a/src/test/java/de/caritas/cob/agencyservice/api/service/AgencyServiceIT.java b/src/test/java/de/caritas/cob/agencyservice/api/service/AgencyServiceIT.java index dafcdb23..552db80c 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/service/AgencyServiceIT.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/service/AgencyServiceIT.java @@ -4,17 +4,14 @@ import de.caritas.cob.agencyservice.api.exception.MissingConsultingTypeException; import de.caritas.cob.agencyservice.api.manager.consultingtype.ConsultingTypeManager; import de.caritas.cob.agencyservice.api.repository.agency.AgencyRepository; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; -@RunWith(SpringRunner.class) @SpringBootTest(classes = AgencyServiceApplication.class) @TestPropertySource(properties = "spring.profiles.active=testing") @AutoConfigureTestDatabase(replace = Replace.ANY) diff --git a/src/test/java/de/caritas/cob/agencyservice/api/service/AgencyServiceITBase.java b/src/test/java/de/caritas/cob/agencyservice/api/service/AgencyServiceITBase.java index f51fdb95..7a1956a5 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/service/AgencyServiceITBase.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/service/AgencyServiceITBase.java @@ -20,8 +20,8 @@ import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.when; public class AgencyServiceITBase { diff --git a/src/test/java/de/caritas/cob/agencyservice/api/service/AgencyServiceTenantAwareIT.java b/src/test/java/de/caritas/cob/agencyservice/api/service/AgencyServiceTenantAwareIT.java index 454dfee6..8b519d32 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/service/AgencyServiceTenantAwareIT.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/service/AgencyServiceTenantAwareIT.java @@ -4,10 +4,9 @@ import de.caritas.cob.agencyservice.api.exception.MissingConsultingTypeException; import de.caritas.cob.agencyservice.api.tenant.TenantContext; import de.caritas.cob.agencyservice.tenantservice.generated.web.model.RestrictedTenantDTO; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; @@ -19,13 +18,11 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.jdbc.Sql.ExecutionPhase; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; -@RunWith(SpringRunner.class) @SpringBootTest(classes = AgencyServiceApplication.class) @TestPropertySource(properties = "spring.profiles.active=testing") @AutoConfigureTestDatabase(replace = Replace.ANY) @@ -41,13 +38,13 @@ public class AgencyServiceTenantAwareIT extends AgencyServiceITBase { @MockBean TenantService tenantService; - @Before + @BeforeEach public void beforeEach() { TenantContext.setCurrentTenant(1L); Mockito.when(tenantService.getRestrictedTenantDataByTenantId(Mockito.anyLong())).thenReturn(new RestrictedTenantDTO()); } - @After + @AfterEach public void afterEach() { TenantContext.clear(); } diff --git a/src/test/java/de/caritas/cob/agencyservice/api/service/AgencyServiceTenantAwareTest.java b/src/test/java/de/caritas/cob/agencyservice/api/service/AgencyServiceTenantAwareTest.java index cfcfa262..46945f6b 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/service/AgencyServiceTenantAwareTest.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/service/AgencyServiceTenantAwareTest.java @@ -1,5 +1,6 @@ package de.caritas.cob.agencyservice.api.service; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -15,16 +16,16 @@ import de.caritas.cob.agencyservice.tenantservice.generated.web.model.RestrictedTenantDTO; import de.caritas.cob.agencyservice.tenantservice.generated.web.model.Settings; import java.util.Optional; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.test.util.ReflectionTestUtils; -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class AgencyServiceTenantAwareTest { @InjectMocks @@ -50,39 +51,40 @@ public class AgencyServiceTenantAwareTest { private static final Long TENANT_ID = 1L; - @Before + @BeforeEach public void before() { ReflectionTestUtils.setField(agencyService, "multitenancy", true); TenantContext.setCurrentTenant(TENANT_ID); } - @After + @AfterEach public void tearDown() { ReflectionTestUtils.setField(agencyService, "topicsFeatureEnabled", false); ReflectionTestUtils.setField(agencyService, "multitenancy", false); TenantContext.clear(); } - @Test(expected = BadRequestException.class) - public void getAgencies_Should_throwBadRequestException_When_topicIdNotProvidedAndFeatureEnabled() - throws MissingConsultingTypeException { - // given - ReflectionTestUtils.setField(agencyService, "topicsFeatureEnabled", true); - ExtendedConsultingTypeResponseDTO dto = new ExtendedConsultingTypeResponseDTO().registration( - new BasicConsultingTypeResponseDTORegistration().minPostcodeSize(5)); - when(consultingTypeManager.getConsultingTypeSettings(1)).thenReturn(dto); - RestrictedTenantDTO restrictedTenantDTO = new RestrictedTenantDTO().settings( - new Settings().topicsInRegistrationEnabled(true)); - when(tenantService.getRestrictedTenantDataByTenantId(TENANT_ID)).thenReturn( - restrictedTenantDTO); - - // when - this.agencyService.getAgencies(Optional.of("12123"), 1, Optional.empty()); - - // then - verify(agencyRepository).searchWithTopic("12123", 5, 1, 2, null, - null, null, - TENANT_ID); + @Test + public void getAgencies_Should_throwBadRequestException_When_topicIdNotProvidedAndFeatureEnabled() { + assertThrows(BadRequestException.class, () -> { + // given + ReflectionTestUtils.setField(agencyService, "topicsFeatureEnabled", true); + ExtendedConsultingTypeResponseDTO dto = new ExtendedConsultingTypeResponseDTO().registration( + new BasicConsultingTypeResponseDTORegistration().minPostcodeSize(5)); + when(consultingTypeManager.getConsultingTypeSettings(1)).thenReturn(dto); + RestrictedTenantDTO restrictedTenantDTO = new RestrictedTenantDTO().settings( + new Settings().topicsInRegistrationEnabled(true)); + when(tenantService.getRestrictedTenantDataByTenantId(TENANT_ID)).thenReturn( + restrictedTenantDTO); + + // when + this.agencyService.getAgencies(Optional.of("12123"), 1, Optional.empty()); + + // then + verify(agencyRepository).searchWithTopic("12123", 5, 1, 2, null, + null, null, + TENANT_ID); + }); } @Test diff --git a/src/test/java/de/caritas/cob/agencyservice/api/service/AgencyServiceTest.java b/src/test/java/de/caritas/cob/agencyservice/api/service/AgencyServiceTest.java index e4aa639b..677b16ed 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/service/AgencyServiceTest.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/service/AgencyServiceTest.java @@ -21,9 +21,10 @@ import static org.hamcrest.CoreMatchers.everyItem; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.times; @@ -52,17 +53,17 @@ import javax.swing.text.html.Option; import org.hamcrest.collection.IsEmptyCollection; import org.jeasy.random.EasyRandom; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.dao.DataAccessException; import org.springframework.test.util.ReflectionTestUtils; -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class AgencyServiceTest { private static final Integer AGE = null; @@ -93,7 +94,7 @@ public class AgencyServiceTest { private static final Long TENANT_ID = null; - @After + @AfterEach public void tearDown() { TenantContext.clear(); ReflectionTestUtils.setField(agencyService, "topicsFeatureEnabled", false); @@ -121,7 +122,7 @@ private void callGetAgencies() { agencyService.getAgencies(Optional.of(VALID_POSTCODE), CONSULTING_TYPE_SUCHT, emptyTopicIds); fail("Expected exception: ServiceException"); } catch (InternalServerErrorException internalServerErrorException) { - assertTrue("Excepted ServiceException thrown", true); + assertTrue(true, "Excepted ServiceException thrown"); } } @@ -263,13 +264,14 @@ public void getAgencies_Should_ReturnEmptyList_When_NoAgencyFoundForGivenId() { IsEmptyCollection.empty()); } - @Test(expected = InternalServerErrorException.class) - public void getAgencies_Should_ThrowInternalServerError_When_MissingConsultingTypeExceptionIsThrown() - throws MissingConsultingTypeException { + @Test + public void getAgencies_Should_ThrowInternalServerError_When_MissingConsultingTypeExceptionIsThrown() { + assertThrows(InternalServerErrorException.class, () -> { - when(consultingTypeManager.getConsultingTypeSettings(anyInt())) - .thenThrow(new MissingConsultingTypeException("")); - agencyService.getAgencies(Optional.of(""), 0, Optional.empty()); + when(consultingTypeManager.getConsultingTypeSettings(anyInt())) + .thenThrow(new MissingConsultingTypeException("")); + agencyService.getAgencies(Optional.of(""), 0, Optional.empty()); + }); } @Test @@ -282,36 +284,41 @@ public void setAgencyOffline_Should_SaveAgency() { verify(agencyRepository, times(1)).save(any()); } - @Test(expected = NotFoundException.class) + @Test public void setAgencyOffline_Should_ThrowNotFoundException_WhenAgencyIsNotFound() { + assertThrows(NotFoundException.class, () -> { - when(agencyRepository.findById(AGENCY_ID)).thenReturn(Optional.empty()); - agencyService.setAgencyOffline(AGENCY_ID); + when(agencyRepository.findById(AGENCY_ID)).thenReturn(Optional.empty()); + agencyService.setAgencyOffline(AGENCY_ID); - } + }); - @Test(expected = BadRequestException.class) - public void getAgenciesByConsultingType_Should_throwBadRequestException_When_ConsultingTypeIsInvalid() - throws MissingConsultingTypeException { - when(consultingTypeManager.getConsultingTypeSettings(-10)) - .thenThrow(new MissingConsultingTypeException("")); - this.agencyService.getAgencies(-10); } - @Test(expected = BadRequestException.class) - public void getAgencies_Should_throwBadRequestException_When_TopicIdNotProvidedAndFeatureEnabled() - throws MissingConsultingTypeException { - // given - ReflectionTestUtils.setField(agencyService, "topicsFeatureEnabled", true); - ExtendedConsultingTypeResponseDTO dto = new ExtendedConsultingTypeResponseDTO().registration( - new BasicConsultingTypeResponseDTORegistration().minPostcodeSize(5)); - when(consultingTypeManager.getConsultingTypeSettings(1)).thenReturn(dto); - RestrictedTenantDTO restrictedTenantDTO = new RestrictedTenantDTO().settings( - new Settings().topicsInRegistrationEnabled(true)); - when(tenantService.getRestrictedTenantDataForSingleTenant()).thenReturn(restrictedTenantDTO); + @Test + public void getAgenciesByConsultingType_Should_throwBadRequestException_When_ConsultingTypeIsInvalid() { + assertThrows(BadRequestException.class, () -> { + when(consultingTypeManager.getConsultingTypeSettings(-10)) + .thenThrow(new MissingConsultingTypeException("")); + this.agencyService.getAgencies(-10); + }); + } - // when - this.agencyService.getAgencies(Optional.of("12123"), 1, Optional.empty()); + @Test + public void getAgencies_Should_throwBadRequestException_When_TopicIdNotProvidedAndFeatureEnabled() { + assertThrows(BadRequestException.class, () -> { + // given + ReflectionTestUtils.setField(agencyService, "topicsFeatureEnabled", true); + ExtendedConsultingTypeResponseDTO dto = new ExtendedConsultingTypeResponseDTO().registration( + new BasicConsultingTypeResponseDTORegistration().minPostcodeSize(5)); + when(consultingTypeManager.getConsultingTypeSettings(1)).thenReturn(dto); + RestrictedTenantDTO restrictedTenantDTO = new RestrictedTenantDTO().settings( + new Settings().topicsInRegistrationEnabled(true)); + when(tenantService.getRestrictedTenantDataForSingleTenant()).thenReturn(restrictedTenantDTO); + + // when + this.agencyService.getAgencies(Optional.of("12123"), 1, Optional.empty()); + }); } @Test diff --git a/src/test/java/de/caritas/cob/agencyservice/api/service/AppointmentServiceTest.java b/src/test/java/de/caritas/cob/agencyservice/api/service/AppointmentServiceTest.java index 8b4dc058..db42b14b 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/service/AppointmentServiceTest.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/service/AppointmentServiceTest.java @@ -2,7 +2,6 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; diff --git a/src/test/java/de/caritas/cob/agencyservice/api/service/CentralDataProtectionTemplateServiceTest.java b/src/test/java/de/caritas/cob/agencyservice/api/service/CentralDataProtectionTemplateServiceTest.java index b1ce330c..89b06f30 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/service/CentralDataProtectionTemplateServiceTest.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/service/CentralDataProtectionTemplateServiceTest.java @@ -17,17 +17,14 @@ import de.caritas.cob.agencyservice.tenantservice.generated.web.model.RestrictedTenantDTO; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.util.ReflectionTestUtils; -@RunWith(SpringRunner.class) @SpringBootTest @ActiveProfiles("testing") @AutoConfigureTestDatabase(replace = Replace.ANY) diff --git a/src/test/java/de/caritas/cob/agencyservice/api/service/ConsultingTypeServiceTest.java b/src/test/java/de/caritas/cob/agencyservice/api/service/ConsultingTypeServiceTest.java index 76f81151..9f652fc7 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/service/ConsultingTypeServiceTest.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/service/ConsultingTypeServiceTest.java @@ -1,6 +1,6 @@ package de.caritas.cob.agencyservice.api.service; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; import de.caritas.cob.agencyservice.api.service.securityheader.SecurityHeaderSupplier; diff --git a/src/test/java/de/caritas/cob/agencyservice/api/service/LogServiceTest.java b/src/test/java/de/caritas/cob/agencyservice/api/service/LogServiceTest.java index 52d73932..747c7486 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/service/LogServiceTest.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/service/LogServiceTest.java @@ -5,14 +5,14 @@ import static org.mockito.Mockito.verify; import java.io.PrintWriter; -import javax.ws.rs.BadRequestException; -import org.junit.Test; -import org.junit.runner.RunWith; +import jakarta.ws.rs.BadRequestException; +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.http.HttpStatus; -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class LogServiceTest { @Mock diff --git a/src/test/java/de/caritas/cob/agencyservice/api/tenant/AccessTokenTenantResolverTest.java b/src/test/java/de/caritas/cob/agencyservice/api/tenant/AccessTokenTenantResolverTest.java index 5d5df081..84ca30d2 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/tenant/AccessTokenTenantResolverTest.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/tenant/AccessTokenTenantResolverTest.java @@ -16,7 +16,6 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken; import org.keycloak.representations.AccessToken; -import org.mockito.Answers; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; diff --git a/src/test/java/de/caritas/cob/agencyservice/api/util/AuthenticatedUserTest.java b/src/test/java/de/caritas/cob/agencyservice/api/util/AuthenticatedUserTest.java index 5f57a630..cb0d6907 100644 --- a/src/test/java/de/caritas/cob/agencyservice/api/util/AuthenticatedUserTest.java +++ b/src/test/java/de/caritas/cob/agencyservice/api/util/AuthenticatedUserTest.java @@ -1,26 +1,34 @@ package de.caritas.cob.agencyservice.api.util; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import static org.junit.jupiter.api.Assertions.assertThrows; -@RunWith(MockitoJUnitRunner.class) +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) public class AuthenticatedUserTest { - @Test(expected = NullPointerException.class) + @Test public void AuthenticatedUser_Should_ThrowNullPointerExceptionWhenArgumentsAreNull() { - new AuthenticatedUser(null, null, null, null); + assertThrows(NullPointerException.class, () -> { + new AuthenticatedUser(null, null, null, null); + }); } - @Test(expected = NullPointerException.class) + @Test public void AuthenticatedUser_Should_ThrowNullPointerExceptionWhenUserIdIsNull() { - AuthenticatedUser authenticatedUser = new AuthenticatedUser(); - authenticatedUser.setUserId(null); + assertThrows(NullPointerException.class, () -> { + AuthenticatedUser authenticatedUser = new AuthenticatedUser(); + authenticatedUser.setUserId(null); + }); } - @Test(expected = NullPointerException.class) + @Test public void AuthenticatedUser_Should_ThrowNullPointerExceptionWhenUsernameIsNull() { - AuthenticatedUser authenticatedUser = new AuthenticatedUser(); - authenticatedUser.setUsername(null); + assertThrows(NullPointerException.class, () -> { + AuthenticatedUser authenticatedUser = new AuthenticatedUser(); + authenticatedUser.setUsername(null); + }); } } diff --git a/src/test/java/de/caritas/cob/agencyservice/config/resttemplate/CustomResponseErrorHandlerTest.java b/src/test/java/de/caritas/cob/agencyservice/config/resttemplate/CustomResponseErrorHandlerTest.java index 5ec590b8..9e6b08ad 100644 --- a/src/test/java/de/caritas/cob/agencyservice/config/resttemplate/CustomResponseErrorHandlerTest.java +++ b/src/test/java/de/caritas/cob/agencyservice/config/resttemplate/CustomResponseErrorHandlerTest.java @@ -2,13 +2,13 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.IOException; import java.net.URI; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpResponse; diff --git a/src/test/java/de/caritas/cob/agencyservice/filter/SubdomainExtractorTest.java b/src/test/java/de/caritas/cob/agencyservice/filter/SubdomainExtractorTest.java index 6fab8006..09eff9d3 100644 --- a/src/test/java/de/caritas/cob/agencyservice/filter/SubdomainExtractorTest.java +++ b/src/test/java/de/caritas/cob/agencyservice/filter/SubdomainExtractorTest.java @@ -4,7 +4,6 @@ import static java.util.Collections.enumeration; import static java.util.Optional.of; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; -import static org.mockito.Mockito.when; import com.google.common.collect.Lists; import java.net.URISyntaxException; @@ -14,7 +13,6 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) diff --git a/src/test/java/de/caritas/cob/agencyservice/testHelper/TestConstants.java b/src/test/java/de/caritas/cob/agencyservice/testHelper/TestConstants.java index 6854ceca..7b55b30b 100644 --- a/src/test/java/de/caritas/cob/agencyservice/testHelper/TestConstants.java +++ b/src/test/java/de/caritas/cob/agencyservice/testHelper/TestConstants.java @@ -220,18 +220,22 @@ public class TestConstants { + " \"external\": true\n" + "}"; - public static final String VALID_AGENCY_UPDATE_DTO = "{\n" - + " \"city\": \"City\",\n" - + " \"description\": \"Description\",\n" - + " \"name\": \"Agency\",\n" - + " \"postcode\": \"76000\",\n" - + " \"offline\": true,\n" - + " \"external\": false\n" - + "}"; + public static final String VALID_AGENCY_UPDATE_DTO = """ + { + "city": "City", + "description": "Description", + "name": "Agency", + "postcode": "76000", + "offline": true, + "external": false + }\ + """; - public static final String VALID_POSTCODE_RANGE_DTO = "{\n" - + " \"postcodeFrom\": \"51107\",\n" - + " \"postcodeTo\": \"51109\"\n" - + "}"; + public static final String VALID_POSTCODE_RANGE_DTO = """ + { + "postcodeFrom": "51107", + "postcodeTo": "51109" + }\ + """; }