org.kisoonlineapp.model.validation.AustrianOrtConstraintTest.java Source code

Java tutorial

Introduction

Here is the source code for org.kisoonlineapp.model.validation.AustrianOrtConstraintTest.java

Source

/*
 * Copyright 2016 berni.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.kisoonlineapp.model.validation;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.apache.commons.lang3.StringUtils;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 *
 * @author berni
 */
public class AustrianOrtConstraintTest {

    private static ValidatorFactory vf;

    @BeforeClass
    public static void setUpClass() {
        vf = Validation.buildDefaultValidatorFactory();
    }

    @AfterClass
    public static void tearDownClass() {
    }

    private Validator validator;

    public AustrianOrtConstraintTest() {
    }

    @Before
    public void setUp() {
        validator = vf.getValidator();
    }

    @After
    public void tearDown() {
    }

    @Test
    public void testValidate_Passed() {
        AustrianOrtBean austrianOrtBean = new AustrianOrtBean();
        assertEquals(0, validator.validate(austrianOrtBean).size());

        austrianOrtBean.ort = "Wien";
        assertEquals(0, validator.validate(austrianOrtBean).size());
    }

    @Test
    public void testValidate_Failed() {
        AustrianOrtBean austrianOrtBean = new AustrianOrtBean();

        austrianOrtBean.ort = StringUtils.repeat('X', 101);
        Set<ConstraintViolation<AustrianOrtBean>> violations = validator.validate(austrianOrtBean);
        assertEquals(1, violations.size());
        List<ConstraintViolation<AustrianOrtBean>> violationList = new ArrayList<>(
                Collections.unmodifiableCollection(violations));
        assertEquals("size must be between 0 and 100", violationList.get(0).getMessage());
    }

    static class AustrianOrtBean {

        @AustrianOrtConstraint
        String ort;
    }

}