001/*
002 * Copyright 2002-2017 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.MvcResult;
022import org.springframework.test.web.servlet.ResultMatcher;
023import org.springframework.web.servlet.ModelAndView;
024
025import static org.hamcrest.MatcherAssert.*;
026import static org.springframework.test.util.AssertionErrors.*;
027
028/**
029 * Factory for assertions on the selected view.
030 *
031 * <p>An instance of this class is typically accessed via
032 * {@link MockMvcResultMatchers#view}.
033 *
034 * @author Rossen Stoyanchev
035 * @since 3.2
036 */
037public class ViewResultMatchers {
038
039        /**
040         * Protected constructor.
041         * Use {@link MockMvcResultMatchers#view()}.
042         */
043        protected ViewResultMatchers() {
044        }
045
046
047        /**
048         * Assert the selected view name with the given Hamcrest {@link Matcher}.
049         */
050        public ResultMatcher name(final Matcher<? super String> matcher) {
051                return new ResultMatcher() {
052                        @Override
053                        public void match(MvcResult result) throws Exception {
054                                ModelAndView mav = result.getModelAndView();
055                                assertTrue("No ModelAndView found", mav != null);
056                                assertThat("View name", mav.getViewName(), matcher);
057                        }
058                };
059        }
060
061        /**
062         * Assert the selected view name.
063         */
064        public ResultMatcher name(final String expectedViewName) {
065                return new ResultMatcher() {
066                        @Override
067                        public void match(MvcResult result) throws Exception {
068                                ModelAndView mav = result.getModelAndView();
069                                assertTrue("No ModelAndView found", mav != null);
070                                assertEquals("View name", expectedViewName, mav.getViewName());
071                        }
072                };
073        }
074
075}