ResourceValidator { public void validate(ResourceDto resource) throws BadRequestException { if (resource == null) { throw new BadRequestException("Missed resource"); } final Set<String> units = resourcesTypesToUnits.get(resource.getType()); if (units == null) { throw new BadRequestException( "Specified resources type '" + resource.getType() + "' is not supported"); } if (resource.getUnit() == null) { resource.setUnit(resourcesTypesToDefaultUnit.get(resource.getType())); } else { if (!units.contains(resource.getUnit())) { throw new BadRequestException( "Specified resources type '" + resource.getType() + "' support only following units: " + units.stream().collect(Collectors.joining(", "))); } } if (resource.getAmount() < -1) { throw new BadRequestException( "Resources with type '" + resource.getType() + "' has negative amount"); } } @Inject  ResourceValidator(Set<ResourceType> supportedResources); void validate(ResourceDto resource);  }
@Test( expectedExceptions = BadRequestException.class, expectedExceptionsMessageRegExp = "Specified resources type 'unsupported' is not supported") public void shouldThrowBadRequestExceptionWhenResourceHasNonSupportedType() throws Exception { validator.validate(DtoFactory.newDto(ResourceDto.class).withType("unsupported").withUnit("mb")); }
@Test( expectedExceptions = BadRequestException.class, expectedExceptionsMessageRegExp = "Specified resources type 'test' support only following units: mb, gb") public void shouldThrowBadRequestExceptionWhenResourceHasNonSupportedUnit() throws Exception { validator.validate(DtoFactory.newDto(ResourceDto.class).withType(RESOURCE_TYPE).withUnit("kb")); }
@Test public void shouldSetDefaultResourceUnitWhenItIsMissed() throws Exception { ResourceDto toValidate = DtoFactory.newDto(ResourceDto.class).withType(RESOURCE_TYPE).withUnit(null); validator.validate(toValidate); assertEquals(toValidate.getUnit(), DEFAULT_RESOURCE_UNIT); }
@Test( expectedExceptions = BadRequestException.class, expectedExceptionsMessageRegExp = "Resources with type 'test' has negative amount") public void shouldThrowBadRequestExceptionWhenResourceHasNegativeAmount() throws Exception { validator.validate( DtoFactory.newDto(ResourceDto.class) .withType(RESOURCE_TYPE) .withAmount(-1024) .withUnit("mb")); }
@Test public void shouldNotThrowAnyExceptionsWhenResourceHasSupportedTypeAndUnit() throws Exception { validator.validate(DtoFactory.newDto(ResourceDto.class).withType(RESOURCE_TYPE).withUnit("mb")); }