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; 022import org.springframework.web.servlet.ModelAndView; 023 024import static org.hamcrest.MatcherAssert.assertThat; 025import static org.springframework.test.util.AssertionErrors.assertEquals; 026import static org.springframework.test.util.AssertionErrors.fail; 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(Matcher<? super String> matcher) { 051 return result -> { 052 ModelAndView mav = result.getModelAndView(); 053 if (mav == null) { 054 fail("No ModelAndView found"); 055 } 056 assertThat("View name", mav.getViewName(), matcher); 057 }; 058 } 059 060 /** 061 * Assert the selected view name. 062 */ 063 public ResultMatcher name(String expectedViewName) { 064 return result -> { 065 ModelAndView mav = result.getModelAndView(); 066 if (mav == null) { 067 fail("No ModelAndView found"); 068 } 069 assertEquals("View name", expectedViewName, mav.getViewName()); 070 }; 071 } 072 073}