/* * Copyright 2000-2016 Vaadin Ltd. * * 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 com.vaadin.data; import java.util.Objects; import org.junit.Assert; import org.junit.Test; /** * @author Vaadin Ltd * */ public class ValidatorTest { @Test public void alwaysPass() { Validator alwaysPass = Validator.alwaysPass(); Result result = alwaysPass.apply("foo"); Assert.assertTrue(result instanceof SimpleResult); SimpleResult implRes = (SimpleResult) result; Assert.assertFalse(implRes.getMessage().isPresent()); } @Test public void chain_alwaysPassAndError() { Validator alwaysPass = Validator.alwaysPass(); Validator chain = alwaysPass .chain(value -> Result.error("foo")); Result result = chain.apply("bar"); Assert.assertTrue(result.isError()); Assert.assertEquals("foo", result.getMessage().get()); } @SuppressWarnings("serial") @Test public void chain_mixture() { Validator first = new Validator() { @Override public Result apply(String value) { if (value == null) { return Result.error("Cannot be null"); } return Result.ok(value); } }; Validator second = new Validator() { @Override public Result apply(String value) { if (value != null && value.isEmpty()) { return Result.error("Cannot be empty"); } return Result.ok(value); } }; Validator chain = first.chain(second); Result result = chain.apply("bar"); Assert.assertFalse(result.isError()); result = chain.apply(null); Assert.assertTrue(result.isError()); result = chain.apply(""); Assert.assertTrue(result.isError()); } @Test public void from() { Validator validator = Validator.from(Objects::nonNull, "Cannot be null"); Result result = validator.apply(null); Assert.assertTrue(result.isError()); result = validator.apply(""); Assert.assertFalse(result.isError()); } }