001/*
002 * Copyright 2002-2019 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.test.web.servlet.result;
018
019import org.hamcrest.Matcher;
020
021import org.springframework.test.web.servlet.ResultMatcher;
022
023import static org.hamcrest.MatcherAssert.assertThat;
024import static org.springframework.test.util.AssertionErrors.assertEquals;
025import static org.springframework.test.util.AssertionErrors.assertNotNull;
026
027/**
028 * Factory for "output" flash attribute assertions.
029 *
030 * <p>An instance of this class is typically accessed via
031 * {@link MockMvcResultMatchers#flash}.
032 *
033 * @author Rossen Stoyanchev
034 * @since 3.2
035 */
036public class FlashAttributeResultMatchers {
037
038        /**
039         * Protected constructor.
040         * Use {@link MockMvcResultMatchers#flash()}.
041         */
042        protected FlashAttributeResultMatchers() {
043        }
044
045
046        /**
047         * Assert a flash attribute's value with the given Hamcrest {@link Matcher}.
048         */
049        @SuppressWarnings("unchecked")
050        public <T> ResultMatcher attribute(String name, Matcher<T> matcher) {
051                return result -> assertThat("Flash attribute '" + name + "'", (T) result.getFlashMap().get(name), matcher);
052        }
053
054        /**
055         * Assert a flash attribute's value.
056         */
057        public ResultMatcher attribute(String name, Object value) {
058                return result -> assertEquals("Flash attribute '" + name + "'", value, result.getFlashMap().get(name));
059        }
060
061        /**
062         * Assert the existence of the given flash attributes.
063         */
064        public ResultMatcher attributeExists(String... names) {
065                return result -> {
066                        for (String name : names) {
067                                assertNotNull("Flash attribute '" + name + "' does not exist", result.getFlashMap().get(name));
068                        }
069                };
070        }
071
072        /**
073         * Assert the number of flash attributes.
074         */
075        public ResultMatcher attributeCount(int count) {
076                return result -> assertEquals("FlashMap size", count, result.getFlashMap().size());
077        }
078
079}