javax.validation.ConstraintViolationException Java Examples

The following examples show how to use javax.validation.ConstraintViolationException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ValidationEndToEndTest.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testRelationProperty() {
	Task task = new Task();
	task.setId(1L);
	task.setName("test");
	taskRepo.create(task);
	task.setName(ComplexValidator.INVALID_NAME);

	Project project = new Project();
	project.setName("test");
	project.setTask(task);

	try {
		projectRepo.create(project);
	} catch (ConstraintViolationException e) {
		Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
		Assert.assertEquals(1, violations.size());
		ConstraintViolationImpl violation = (ConstraintViolationImpl) violations.iterator().next();
		Assert.assertEquals("{complex.message}", violation.getMessageTemplate());
		Assert.assertEquals("task", violation.getPropertyPath().toString());
		Assert.assertEquals("/data/relationships/task", violation.getErrorData().getSourcePointer());
	}
}
 
Example #2
Source File: JdbcOperatorTest.java    From examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testApplication() throws Exception
{
  try {
    LocalMode lma = LocalMode.newInstance();
    Configuration conf = new Configuration(false);
    conf.addResource(this.getClass().getResourceAsStream("/META-INF/properties.xml"));
    lma.prepareDAG(new JdbcToJdbcApp(), conf);
    LocalMode.Controller lc = lma.getController();
    lc.runAsync();

    // wait for records to be added to table    
    Thread.sleep(5000);

    Assert.assertEquals("Events in store", 10, getNumOfEventsInStore());
    cleanTable();

  } catch (ConstraintViolationException e) {
    Assert.fail("constraint violations: " + e.getConstraintViolations());
  }
}
 
Example #3
Source File: ValidationUtils.java    From sundrio with Apache License 2.0 6 votes vote down vote up
public static <T> void validate(T item, Validator v) {
    if (v == null) {
        v = getValidator();
    }
    if (v == null) {
       return;
    }
    Set<ConstraintViolation<T>> violations = v.validate(item);
    if (!violations.isEmpty()) {
        StringBuilder sb = new StringBuilder("Constraint Validations: ");
        boolean first = true;
        for (ConstraintViolation violation : violations) {
            if (first) {
                first = false;
            } else {
                sb.append(", ");
            }
            Object leafBean = violation.getLeafBean();
            sb.append(violation.getPropertyPath() + " " + violation.getMessage() + " on bean: " + leafBean);
        }
        throw new ConstraintViolationException(sb.toString(), violations);
    }
}
 
Example #4
Source File: WaggleDance.java    From waggle-dance with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  // below is output *before* logging is configured so will appear on console
  logVersionInfo();

  int exitCode = -1;
  try {
    SpringApplication application = new SpringApplicationBuilder(WaggleDance.class)
        .properties("spring.config.location:${server-config:null},${federation-config:null}")
        .properties("server.port:${endpoint.port:18000}")
        .registerShutdownHook(true)
        .build();
    exitCode = SpringApplication.exit(registerListeners(application).run(args));
  } catch (BeanCreationException e) {
    Throwable mostSpecificCause = e.getMostSpecificCause();
    if (mostSpecificCause instanceof BindException) {
      printHelp(((BindException) mostSpecificCause).getAllErrors());
    }
    if (mostSpecificCause instanceof ConstraintViolationException) {
      logConstraintErrors(((ConstraintViolationException) mostSpecificCause));
    }
    throw e;
  }
  if (exitCode != 0) {
    throw new Exception("Waggle Dance didn't exit properly see logs for errors, exitCode=" + exitCode);
  }
}
 
Example #5
Source File: ValidationEndToEndTest.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testPropertyOnRelation() {
	Task task = new Task();
	task.setId(1L);
	task.setName("test");
	taskRepo.create(task);
	task.setName(null);

	Project project = new Project();
	project.setId(2L);
	project.setName("test");
	project.getTasks().add(task);

	try {
		projectRepo.create(project);
	} catch (ConstraintViolationException e) {
		Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
		Assert.assertEquals(1, violations.size());
		ConstraintViolationImpl violation = (ConstraintViolationImpl) violations.iterator().next();
		Assert.assertEquals("{javax.validation.constraints.NotNull.message}", violation.getMessageTemplate());
		Assert.assertEquals("tasks[0]", violation.getPropertyPath().toString());
		Assert.assertEquals("/data/relationships/tasks/0", violation.getErrorData().getSourcePointer());
	}
}
 
Example #6
Source File: TagService.java    From blog-spring with MIT License 6 votes vote down vote up
public Tag findOrCreateByName(String name) {
  Tag tag = tagRepository.findByName(name);
  if (tag == null) {
    try {
      tag = new Tag();
      tag.setName(name);
      tag.setPostCount(0);
      tagRepository.save(tag);
    } catch (ConstraintViolationException exception) {
      ConstraintViolation<?> violation = exception.getConstraintViolations().iterator().next();
      throw new InvalidTagException(
          "Invalid tag " + violation.getPropertyPath() + ": " + violation.getMessage());
    }
  }
  return tag;
}
 
Example #7
Source File: ApplicationTest.java    From examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testApplication() throws IOException, Exception {
  try {
    // create file in monitored HDFS directory
    createFile();

    // run app asynchronously; terminate after results are checked
    LocalMode.Controller lc = asyncRun();

    // get messages from Kafka topic and compare with input
    chkOutput();

    lc.shutdown();
  } catch (ConstraintViolationException e) {
    Assert.fail("constraint violations: " + e.getConstraintViolations());
  }
}
 
Example #8
Source File: ProductMilestoneTest.java    From pnc with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotCreateProductMilestoneWithMalformedVersion() {
    // given
    ProductMilestone productMilestone = ProductMilestone.Builder.newBuilder()
            .version("1.0.0-CD1")
            .productVersion(productVersion)
            .build();

    // when-then
    try {
        em.getTransaction().begin();
        em.persist(productMilestone);
        em.getTransaction().commit();
    } catch (RollbackException ex) {
        if (!(ex.getCause() instanceof ConstraintViolationException))
            fail("Creation of ProductMilestones with malformed version should not be allowed");
    }
}
 
Example #9
Source File: ServiceInterceptor.java    From conductor with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param invocation
 * @return
 * @throws ConstraintViolationException incase of any constraints
 * defined on method parameters are violated.
 */
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {

    if (skipMethod(invocation)) {
        return invocation.proceed();
    }

    ExecutableValidator executableValidator = validatorProvider.get().forExecutables();

    Set<ConstraintViolation<Object>> result = executableValidator.validateParameters(
            invocation.getThis(), invocation.getMethod(), invocation.getArguments());

    if (!result.isEmpty()) {
        throw new ConstraintViolationException(result);
    }

    return invocation.proceed();
}
 
Example #10
Source File: TargetTagManagementTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Step
private void createAndUpdateTagWithInvalidDescription(final Tag tag) {

    assertThatExceptionOfType(ConstraintViolationException.class)
            .isThrownBy(() -> targetTagManagement.create(
                    entityFactory.tag().create().name("a").description(RandomStringUtils.randomAlphanumeric(513))))
            .as("tag with too long description should not be created");

    assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(
            () -> targetTagManagement.create(entityFactory.tag().create().name("a").description(INVALID_TEXT_HTML)))
            .as("tag with invalid description should not be created");

    assertThatExceptionOfType(ConstraintViolationException.class)
            .isThrownBy(() -> targetTagManagement.update(
                    entityFactory.tag().update(tag.getId()).description(RandomStringUtils.randomAlphanumeric(513))))
            .as("tag with too long description should not be updated");

    assertThatExceptionOfType(ConstraintViolationException.class)
            .isThrownBy(() -> targetTagManagement
                    .update(entityFactory.tag().update(tag.getId()).description(INVALID_TEXT_HTML)))
            .as("tag with invalid description should not be updated");
}
 
Example #11
Source File: DefaultRuntimeContextFactoryTest.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Test
public void validationFailireThrowsException() {

    Config confg = mock(Config.class);
    EncryptorConfig encryptorConfig = mock(EncryptorConfig.class);
    when(encryptorConfig.getType()).thenReturn(EncryptorType.NACL);

    when(confg.getEncryptor()).thenReturn(encryptorConfig);

    KeyConfiguration keyConfiguration = mock(KeyConfiguration.class);

    when(confg.getKeys()).thenReturn(keyConfiguration);

    ConstraintViolation<?> violation = mock(ConstraintViolation.class);
    MockKeyVaultConfigValidations.addConstraintViolation(violation);

    try {
        runtimeContextFactory.create(confg);
        failBecauseExceptionWasNotThrown(ConstraintViolationException.class);
    } catch (ConstraintViolationException ex) {
        assertThat(ex.getConstraintViolations()).containsExactly(violation);
    }
}
 
Example #12
Source File: RpsServicoTest.java    From nfse with MIT License 6 votes vote down vote up
@Test(expected = ConstraintViolationException.class)
public void naoDevePermitirCodCnaeTamanhoInvalido() throws Exception {
  try {
    new ServicoBuilder(FabricaDeObjetosFake.getRpsValores(), "01.01")
        .comDiscriminacao("Descricao Teste")
        .comCodigoCnae("")
        .comCodigoMunicipio("3106200")
        .build();
  } catch (final ConstraintViolationException e) {
    new ServicoBuilder(FabricaDeObjetosFake.getRpsValores(), "01.01")
        .comDiscriminacao("Descricao Teste")
        .comCodigoCnae("00000000")
        .comCodigoMunicipio("3106200")
        .build();
  }
}
 
Example #13
Source File: ControllerManagementTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@Description("Tries to register a target with an invalid controller id")
public void findOrRegisterTargetIfItDoesNotExistThrowsExceptionForInvalidControllerIdParam() {
    assertThatExceptionOfType(ConstraintViolationException.class)
            .as("register target with null as controllerId should fail")
            .isThrownBy(() -> controllerManagement.findOrRegisterTargetIfItDoesNotExist(null, LOCALHOST));

    assertThatExceptionOfType(ConstraintViolationException.class)
            .as("register target with empty controllerId should fail")
            .isThrownBy(() -> controllerManagement.findOrRegisterTargetIfItDoesNotExist("", LOCALHOST));

    assertThatExceptionOfType(ConstraintViolationException.class)
            .as("register target with empty controllerId should fail")
            .isThrownBy(() -> controllerManagement.findOrRegisterTargetIfItDoesNotExist(" ", LOCALHOST));

    assertThatExceptionOfType(ConstraintViolationException.class)
            .as("register target with too long controllerId should fail")
            .isThrownBy(() -> controllerManagement.findOrRegisterTargetIfItDoesNotExist(
                    RandomStringUtils.randomAlphabetic(Target.CONTROLLER_ID_MAX_SIZE + 1), LOCALHOST));
}
 
Example #14
Source File: WebErrorHandlersIT.java    From errors-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Test
@Parameters(method = "provideValidationParams")
public void constraintViolationException_ShouldBeHandledProperly(Object pojo, Locale locale, CodedMessage... codedMessages) {
    contextRunner.run(ctx -> {
        HttpError error;

        WebErrorHandlers errorHandlers = ctx.getBean(WebErrorHandlers.class);
        javax.validation.Validator validator = ctx.getBean(javax.validation.Validator.class);

        ConstraintViolationException exception = new ConstraintViolationException(validator.validate(pojo));

        error = errorHandlers.handle(exception, null, locale);
        assertThat(error.getHttpStatus()).isEqualTo(HttpStatus.BAD_REQUEST);
        assertThat(error.getErrors()).containsOnly(codedMessages);

        verifyPostProcessorsHasBeenCalled(ctx);
    });
}
 
Example #15
Source File: OiOStreamTest.java    From attic-apex-core with Apache License 2.0 6 votes vote down vote up
@Test
public void validatePositiveOiOiOExtendeddiamond()
{
  logger.info("Checking the logic for sanity checking of OiO");

  LogicalPlan plan = new LogicalPlan();
  ThreadIdValidatingInputOperator inputOperator = plan.addOperator("inputOperator", new ThreadIdValidatingInputOperator());
  ThreadIdValidatingGenericIntermediateOperator intermediateOperator1 = plan.addOperator("intermediateOperator1", new ThreadIdValidatingGenericIntermediateOperator());
  ThreadIdValidatingGenericIntermediateOperator intermediateOperator2 = plan.addOperator("intermediateOperator2", new ThreadIdValidatingGenericIntermediateOperator());
  ThreadIdValidatingGenericIntermediateOperator intermediateOperator3 = plan.addOperator("intermediateOperator3", new ThreadIdValidatingGenericIntermediateOperator());
  ThreadIdValidatingGenericIntermediateOperator intermediateOperator4 = plan.addOperator("intermediateOperator4", new ThreadIdValidatingGenericIntermediateOperator());
  ThreadIdValidatingGenericOperatorWithTwoInputPorts outputOperator = plan.addOperator("outputOperator", new ThreadIdValidatingGenericOperatorWithTwoInputPorts());

  plan.addStream("OiOin", inputOperator.output, intermediateOperator1.input, intermediateOperator3.input).setLocality(Locality.THREAD_LOCAL);
  plan.addStream("OiOIntermediate1", intermediateOperator1.output, intermediateOperator2.input).setLocality(Locality.THREAD_LOCAL);
  plan.addStream("OiOIntermediate2", intermediateOperator3.output, intermediateOperator4.input).setLocality(Locality.THREAD_LOCAL);
  plan.addStream("OiOout1", intermediateOperator2.output, outputOperator.input).setLocality(Locality.THREAD_LOCAL);
  plan.addStream("OiOout2", intermediateOperator4.output, outputOperator.input2).setLocality(Locality.THREAD_LOCAL);

  try {
    plan.validate();
    Assert.assertTrue("OiOiO extended diamond validation", true);
  } catch (ConstraintViolationException ex) {
    Assert.fail("OIOIO extended diamond validation");
  }
}
 
Example #16
Source File: ProgrammaticallyValidatingServiceTest.java    From code-examples with MIT License 5 votes vote down vote up
@Test
void whenInputIsInvalid_thenThrowsException(){
  Input input = new Input();
  input.setNumberBetweenOneAndTen(0);
  input.setIpAddress("invalid");

  assertThrows(ConstraintViolationException.class, () -> {
    service.validateInput(input);
  });
}
 
Example #17
Source File: ValidationResponse.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
public ValidationResponse(final ConstraintViolationException cause) {
  super(false, new ArrayList<>());
  //noinspection ThrowableResultOfMethodCallIgnored
  checkNotNull(cause);
  Set<ConstraintViolation<?>> violations = cause.getConstraintViolations();
  if (violations != null && !violations.isEmpty()) {
    for (ConstraintViolation<?> violation : violations) {
      List<String> entries = new ArrayList<>();
      // iterate path to get the full path
      Iterator<Node> it = violation.getPropertyPath().iterator();
      while (it.hasNext()) {
        Node node = it.next();
        if (ElementKind.PROPERTY == node.getKind() || (ElementKind.PARAMETER == node.getKind() && !it.hasNext())) {
          if (node.getKey() != null) {
            entries.add(node.getKey().toString());
          }
          entries.add(node.getName());
        }
      }
      if (entries.isEmpty()) {
        if (messages == null) {
          messages = new ArrayList<>();
        }
        messages.add(violation.getMessage());
      }
      else {
        if (errors == null) {
          errors = new HashMap<>();
        }
        errors.put(Joiner.on('.').join(entries), violation.getMessage());
      }
    }
  }
  else if (cause.getMessage() != null) {
    messages = new ArrayList<>();
    messages.add(cause.getMessage());
  }
}
 
Example #18
Source File: ConstraintViolationExceptionMapper.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
@Override
public Response toResponse(ConstraintViolationException exception) {
    // start with the overall message which will be something like "Cannot create xyz"
    final StringBuilder errorMessage = new StringBuilder(exception.getMessage()).append(" - ");

    boolean first = true;
    for (final ConstraintViolation violation : exception.getConstraintViolations()) {
        if (!first) {
            errorMessage.append(", ");
        }
        first = false;

        // lastNode should end up as the field that failed validation
        Path.Node lastNode = null;
        for (final Path.Node node : violation.getPropertyPath()) {
            lastNode = node;
        }

        // append something like "xyz must not be..."
        errorMessage.append(lastNode.getName()).append(" ").append(violation.getMessage());
    }

    logger.info(String.format("%s. Returning %s response.", errorMessage, Response.Status.BAD_REQUEST));
    if (logger.isDebugEnabled()) {
        logger.debug(StringUtils.EMPTY, exception);
    }

    return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage.toString()).type("text/plain").build();
}
 
Example #19
Source File: CacheSynchronizationService.java    From extended-objects with Apache License 2.0 5 votes vote down vote up
private void validateInstance(Object instance) {
    if (!ValidationMode.NONE.equals(xoUnit.getValidationMode())) {
        Set<ConstraintViolation<Object>> constraintViolations = sessionContext.getInstanceValidationService().validate(instance);
        if (!constraintViolations.isEmpty()) {
            throw new ConstraintViolationException(constraintViolations);
        }
    }
}
 
Example #20
Source File: ValidatingServiceWithGroupsTest.java    From code-examples with MIT License 5 votes vote down vote up
@Test
void whenInputIsInvalidForUpdate_thenThrowsException() {
  InputWithCustomValidator input = validInput();
  input.setId(null);
  assertThrows(ConstraintViolationException.class, () -> {
    service.validateForUpdate(input);
  });
}
 
Example #21
Source File: RpsTomadorCpfCnpjTest.java    From nfse with MIT License 5 votes vote down vote up
@Test(expected = ConstraintViolationException.class)
public void naoDevePermitirDocumentoComTamanhoInvalido() throws Exception {
  try {
    new TomadorCpfCnpjBuilder().comDocumento("1234567890").build();
  } catch (final ConstraintViolationException e) {
    new TomadorCpfCnpjBuilder().comDocumento("123456789090").build();
  }
}
 
Example #22
Source File: InternalErrorInterceptor.java    From mamute with Apache License 2.0 5 votes vote down vote up
@Override
public void intercept(InterceptorStack stack, ControllerMethod method,
		Object instance) throws InterceptionException {
	try {
		stack.next(method, instance);
	}catch (Exception e) {
		
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		
		Throwable cause = e.getCause();
		if(cause != null){
			if (cause instanceof ConstraintViolationException) {
				Set<ConstraintViolation<?>> constraintViolations = ((ConstraintViolationException) cause).getConstraintViolations();
				pw.printf("\nConstraint Violations: \n");
				for (ConstraintViolation<?> constraintViolation : constraintViolations) {
					pw.printf("\t" +constraintViolation.getConstraintDescriptor().getAnnotation()+"\n");
				}
				pw.printf("\n");
				log.error(sw.toString());
			}
			cause.printStackTrace(pw);
		}else{
			e.printStackTrace(pw);
		}
		
		pw.close();
		result.include("stacktrace", sw.toString());
		throw e;
	}
}
 
Example #23
Source File: WriteOnceLinkedHashMap.java    From dcos-commons with Apache License 2.0 5 votes vote down vote up
@Override
public V put(K key, V value) {
  if (super.containsKey(key)) {
    HashSet<ConstraintViolation<String>> violations = new HashSet<>();
    violations.add(new DuplicateKeyConstraintViolation(key + ""));
    throw new ConstraintViolationException("Duplicate key: " + key, violations);
  }
  return super.put(key, value);
}
 
Example #24
Source File: ValidationExceptionMapper.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Response toResponse(ValidationException exception) {
    ValidationExceptionResponse response = new ValidationExceptionResponse();
    if (exception instanceof ConstraintViolationException) {
        ConstraintViolation<?> violation = ((ConstraintViolationException) exception).getConstraintViolations().iterator().next();
        response.path = violation.getPropertyPath().toString();
        response.errorMessage = violation.getMessage();
    } else {
        response.errorMessage = exception.getMessage();
    }
    return Response.status(400).entity(response)
        .type(MediaType.APPLICATION_JSON).build();
}
 
Example #25
Source File: JaxrsEndPointValidationInterceptor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@AroundInvoke
@Override
public Object validateMethodInvocation(InvocationContext ctx) throws Exception {
    try {
        return super.validateMethodInvocation(ctx);
    } catch (ConstraintViolationException e) {
        throw new ResteasyViolationExceptionImpl(e.getConstraintViolations(), getAccept(ctx.getMethod()));
    }
}
 
Example #26
Source File: PatientRepositoryTests.java    From spring-boot-jpa with Apache License 2.0 5 votes vote down vote up
@Test
public void test_PatientRepository_SaveWithEmpty_ExpectException() throws Exception {
    ConstraintViolationException exception =
assertThrows(ConstraintViolationException.class,
		() -> patientRepository.saveAndFlush(new Patient()));

    assertThat(exception).hasMessageContaining("'must not be blank'");
}
 
Example #27
Source File: RpcExceptionMapper.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
protected Response handleConstraintViolationException(ConstraintViolationException cve) {
    ViolationReport report = new ViolationReport();
    for (ConstraintViolation cv : cve.getConstraintViolations()) {
        report.addConstraintViolation(new RestConstraintViolation(
                cv.getPropertyPath().toString(),
                cv.getMessage(),
                cv.getInvalidValue() == null ? "null" : cv.getInvalidValue().toString()));
    }
    // TODO for now just do xml output 现在只执行xml输出
    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(report).type(ContentType.TEXT_XML_UTF_8).build();
}
 
Example #28
Source File: UsersResource.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
/**
 * POST  /rest/users -> create a new user.
 */
@RequestMapping(value = "/rest/users", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void createUser(@RequestBody UserRepresentation userRepresentation) {
    log.debug("REST request to create a User : {}");

        // all users are admins
    userRepresentation.setIsAdmin(true);

    if (userRepresentation.getLogin() == null) {
        throw new BadRequestException("user login is required");
    }
    
    if (userRepresentation.getPassword() == null) {
        throw new BadRequestException("a password is required");
    }
    
    try {
        User result = userService.createUser(userRepresentation);
        if(result == null) {
            throw new ConflictException("User with login '" + userRepresentation.getLogin() + "' already exists.");
        }
    } catch (IllegalArgumentException iae) {
        throw new BadRequestException(iae.getMessage());
    } catch (ConstraintViolationException cv) {
        String message = "Invalid user details";
        if (cv.getConstraintViolations().size() > 0) {
            message = cv.getConstraintViolations().iterator().next().getMessage();
        }
        throw new BadRequestException(message);
    }
    
}
 
Example #29
Source File: InstallationDaoTest.java    From aerogear-unifiedpush-server with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldValidateDeviceId() {
  // given
  final Installation installation = new Installation();
  installation.setDeviceToken("invalid");

  final iOSVariant variant = new iOSVariant();
  variant.setName("iOS Variant Name");
  variant.setPassphrase("12");
  variant.setProduction(false);
  variant.setCertificate("12".getBytes());
  entityManager.persist(variant);
  installation.setVariant(variant);

  // when
  installationDao.create(installation);
  try {
    entityManager.flush();
    fail("ConstraintViolationException should have been thrown");
  } catch (ConstraintViolationException violationException) {
    // then
    final Set<ConstraintViolation<?>> constraintViolations = violationException
        .getConstraintViolations();
    assertThat(constraintViolations).isNotEmpty();
    assertThat(constraintViolations.size()).isEqualTo(1);

    assertThat(constraintViolations.iterator().next().getMessage()).isEqualTo(
        "Device token is not valid for this device type");
  }
}
 
Example #30
Source File: BaseEntityTest.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * Test to make sure validation works and throws exception when no name entered.
 */
@Test
void testValidateNoVersion() {
    this.b.setVersion("");
    Assertions
        .assertThatExceptionOfType(ConstraintViolationException.class)
        .isThrownBy(() -> this.validate(this.b));
}