Migrate exception checking tests to use AssertJ

Migrate tests that use `@Test(expectedException=...)` or
`try...fail...catch` to use AssertJ's `assertThatException`
instead.
This commit is contained in:
Phillip Webb
2019-05-20 10:34:51 -07:00
parent fb26fc3f94
commit 02850f357f
561 changed files with 6592 additions and 10389 deletions

View File

@@ -45,6 +45,8 @@ import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.SimpleWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
@@ -54,7 +56,6 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Tests for {@link ContextLoader} and {@link ContextLoaderListener}.
@@ -231,13 +232,9 @@ public class ContextLoaderTests {
sc.addInitParameter(ContextLoader.CONTEXT_INITIALIZER_CLASSES_PARAM,
StringUtils.arrayToCommaDelimitedString(new Object[] {UnknownContextInitializer.class.getName()}));
ContextLoaderListener listener = new ContextLoaderListener();
try {
listener.contextInitialized(new ServletContextEvent(sc));
fail("expected exception");
}
catch (ApplicationContextException ex) {
assertTrue(ex.getMessage().contains("not assignable"));
}
assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() ->
listener.contextInitialized(new ServletContextEvent(sc)))
.withMessageContaining("not assignable");
}
@Test
@@ -260,14 +257,9 @@ public class ContextLoaderTests {
sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "/WEB-INF/myContext.xml");
ServletContextListener listener = new ContextLoaderListener();
ServletContextEvent event = new ServletContextEvent(sc);
try {
listener.contextInitialized(event);
fail("Should have thrown BeanDefinitionStoreException");
}
catch (BeanDefinitionStoreException ex) {
// expected
assertTrue(ex.getCause() instanceof FileNotFoundException);
}
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() ->
listener.contextInitialized(event))
.withCauseInstanceOf(FileNotFoundException.class);
}
@Test
@@ -277,14 +269,9 @@ public class ContextLoaderTests {
"org.springframework.web.context.support.InvalidWebApplicationContext");
ServletContextListener listener = new ContextLoaderListener();
ServletContextEvent event = new ServletContextEvent(sc);
try {
listener.contextInitialized(event);
fail("Should have thrown ApplicationContextException");
}
catch (ApplicationContextException ex) {
// expected
assertTrue(ex.getCause() instanceof ClassNotFoundException);
}
assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() ->
listener.contextInitialized(event))
.withCauseInstanceOf(ClassNotFoundException.class);
}
@Test
@@ -292,30 +279,20 @@ public class ContextLoaderTests {
MockServletContext sc = new MockServletContext("");
ServletContextListener listener = new ContextLoaderListener();
ServletContextEvent event = new ServletContextEvent(sc);
try {
listener.contextInitialized(event);
fail("Should have thrown BeanDefinitionStoreException");
}
catch (BeanDefinitionStoreException ex) {
// expected
assertTrue(ex.getCause() instanceof IOException);
assertTrue(ex.getCause().getMessage().contains("/WEB-INF/applicationContext.xml"));
}
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() ->
listener.contextInitialized(event))
.withCauseInstanceOf(IOException.class)
.satisfies(ex -> assertThat(ex.getCause()).hasMessageContaining("/WEB-INF/applicationContext.xml"));
}
@Test
public void testFrameworkServletWithDefaultLocation() throws Exception {
DispatcherServlet servlet = new DispatcherServlet();
servlet.setContextClass(XmlWebApplicationContext.class);
try {
servlet.init(new MockServletConfig(new MockServletContext(""), "test"));
fail("Should have thrown BeanDefinitionStoreException");
}
catch (BeanDefinitionStoreException ex) {
// expected
assertTrue(ex.getCause() instanceof IOException);
assertTrue(ex.getCause().getMessage().contains("/WEB-INF/test-servlet.xml"));
}
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() ->
servlet.init(new MockServletConfig(new MockServletContext(""), "test")))
.withCauseInstanceOf(IOException.class)
.satisfies(ex -> assertThat(ex.getCause()).hasMessageContaining("/WEB-INF/test-servlet.xml"));
}
@Test
@@ -347,25 +324,26 @@ public class ContextLoaderTests {
assertTrue("Has kerry", context.containsBean("kerry"));
}
@Test(expected = BeanCreationException.class)
@Test
@SuppressWarnings("resource")
public void testSingletonDestructionOnStartupFailure() throws IOException {
new ClassPathXmlApplicationContext(new String[] {
"/org/springframework/web/context/WEB-INF/applicationContext.xml",
"/org/springframework/web/context/WEB-INF/fail.xml" }) {
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
new ClassPathXmlApplicationContext(new String[] {
"/org/springframework/web/context/WEB-INF/applicationContext.xml",
"/org/springframework/web/context/WEB-INF/fail.xml" }) {
@Override
public void refresh() throws BeansException {
try {
super.refresh();
}
catch (BeanCreationException ex) {
DefaultListableBeanFactory factory = (DefaultListableBeanFactory) getBeanFactory();
assertEquals(0, factory.getSingletonCount());
throw ex;
}
}
};
@Override
public void refresh() throws BeansException {
try {
super.refresh();
}
catch (BeanCreationException ex) {
DefaultListableBeanFactory factory = (DefaultListableBeanFactory) getBeanFactory();
assertEquals(0, factory.getSingletonCount());
throw ex;
}
}
});
}

View File

@@ -33,13 +33,15 @@ import org.springframework.context.NoSuchMessageException;
import org.springframework.context.TestListener;
import org.springframework.mock.web.test.MockServletContext;
import org.springframework.tests.sample.beans.TestBean;
import org.springframework.util.Assert;
import org.springframework.web.context.support.XmlWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Rod Johnson
@@ -124,13 +126,8 @@ public class XmlWebApplicationContextTests extends AbstractApplicationContextTes
wac.setNamespace("testNamespace");
wac.setConfigLocations(new String[] {"/org/springframework/web/context/WEB-INF/test-servlet.xml"});
wac.refresh();
try {
wac.getMessage("someMessage", null, Locale.getDefault());
fail("Should have thrown NoSuchMessageException");
}
catch (NoSuchMessageException ex) {
// expected;
}
assertThatExceptionOfType(NoSuchMessageException.class).isThrownBy(() ->
wac.getMessage("someMessage", null, Locale.getDefault()));
String msg = wac.getMessage("someMessage", null, "default", Locale.getDefault());
assertTrue("Default message returned", "default".equals(msg));
}
@@ -180,34 +177,26 @@ public class XmlWebApplicationContextTests extends AbstractApplicationContextTes
@Override
public void afterPropertiesSet() {
if (this.initMethodInvoked)
fail();
assertThat(this.initMethodInvoked).isFalse();
this.afterPropertiesSetInvoked = true;
}
/** Init method */
public void customInit() throws ServletException {
if (!this.afterPropertiesSetInvoked)
fail();
assertThat(this.afterPropertiesSetInvoked).isTrue();
this.initMethodInvoked = true;
}
@Override
public void destroy() {
if (this.customDestroyed)
fail();
if (this.destroyed) {
throw new IllegalStateException("Already destroyed");
}
assertThat(this.customDestroyed).isFalse();
Assert.state(!this.destroyed, "Already destroyed");
this.destroyed = true;
}
public void customDestroy() {
if (!this.destroyed)
fail();
if (this.customDestroyed) {
throw new IllegalStateException("Already customDestroyed");
}
assertThat(this.destroyed).isTrue();
Assert.state(!this.customDestroyed, "Already customDestroyed");
this.customDestroyed = true;
}
}

View File

@@ -31,9 +31,10 @@ import org.springframework.mock.web.test.MockServletContext;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.context.WebApplicationContext;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
/**
* @author Juergen Hoeller
@@ -74,23 +75,15 @@ public class HttpRequestHandlerTests {
servlet.service(request, response);
assertEquals("myResponse", response.getContentAsString());
try {
request.setParameter("exception", "ServletException");
servlet.service(request, response);
fail("Should have thrown ServletException");
}
catch (ServletException ex) {
assertEquals("test", ex.getMessage());
}
request.setParameter("exception", "ServletException");
assertThatExceptionOfType(ServletException.class).isThrownBy(() ->
servlet.service(request, response))
.withMessage("test");
try {
request.setParameter("exception", "IOException");
servlet.service(request, response);
fail("Should have thrown IOException");
}
catch (IOException ex) {
assertEquals("test", ex.getMessage());
}
request.setParameter("exception", "IOException");
assertThatIOException().isThrownBy(() ->
servlet.service(request, response))
.withMessage("test");
}
}

View File

@@ -31,10 +31,10 @@ import org.springframework.core.io.Resource;
import org.springframework.mock.web.test.MockServletContext;
import org.springframework.tests.sample.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Tests for various ServletContext-related support classes.
@@ -73,15 +73,10 @@ public class ServletContextSupportTests {
pvs.add("attributeName", "myAttr");
wac.registerSingleton("importedAttr", ServletContextAttributeFactoryBean.class, pvs);
try {
wac.refresh();
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
// expected
assertTrue(ex.getCause() instanceof IllegalStateException);
assertTrue(ex.getCause().getMessage().contains("myAttr"));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
wac::refresh)
.withCauseInstanceOf(IllegalStateException.class)
.withMessageContaining("myAttr");
}
@Test
@@ -112,15 +107,10 @@ public class ServletContextSupportTests {
pvs.add("initParamName", "myParam");
wac.registerSingleton("importedParam", ServletContextParameterFactoryBean.class, pvs);
try {
wac.refresh();
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
// expected
assertTrue(ex.getCause() instanceof IllegalStateException);
assertTrue(ex.getCause().getMessage().contains("myParam"));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
wac::refresh)
.withCauseInstanceOf(IllegalStateException.class)
.withMessageContaining("myParam");
}
@Test

View File

@@ -25,8 +25,8 @@ import org.springframework.context.support.StaticApplicationContext;
import org.springframework.mock.web.test.MockServletContext;
import org.springframework.web.util.WebUtils;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
* @author Juergen Hoeller
@@ -55,13 +55,8 @@ public class WebApplicationObjectSupportTests {
StaticApplicationContext ac = new StaticApplicationContext();
ac.registerBeanDefinition("test", new RootBeanDefinition(TestWebApplicationObject.class));
WebApplicationObjectSupport wao = (WebApplicationObjectSupport) ac.getBean("test");
try {
wao.getWebApplicationContext();
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
assertThatIllegalStateException().isThrownBy(
wao::getWebApplicationContext);
}

View File

@@ -58,6 +58,8 @@ import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.util.WebUtils;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.notNullValue;
@@ -70,7 +72,6 @@ import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
@@ -295,14 +296,9 @@ public class DispatcherServletTests {
request.addUserRole("role1");
request.addParameter("fail", "yes");
MockHttpServletResponse response = new MockHttpServletResponse();
try {
complexDispatcherServlet.service(request, response);
assertEquals(200, response.getStatus());
assertTrue("forwarded to failed", "failed1.jsp".equals(response.getForwardedUrl()));
}
catch (ServletException ex) {
fail("Should not have thrown ServletException: " + ex.getMessage());
}
complexDispatcherServlet.service(request, response);
assertEquals(200, response.getStatus());
assertTrue("forwarded to failed", "failed1.jsp".equals(response.getForwardedUrl()));
}
@Test
@@ -416,13 +412,8 @@ public class DispatcherServletTests {
request.addParameter("theme", "mytheme");
request.addParameter("theme2", "theme");
MockHttpServletResponse response = new MockHttpServletResponse();
try {
complexDispatcherServlet.service(request, response);
assertTrue("Not forwarded", response.getForwardedUrl() == null);
}
catch (ServletException ex) {
fail("Should not have thrown ServletException: " + ex.getMessage());
}
complexDispatcherServlet.service(request, response);
assertTrue("Not forwarded", response.getForwardedUrl() == null);
}
@Test
@@ -430,13 +421,8 @@ public class DispatcherServletTests {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do");
request.addPreferredLocale(Locale.CANADA);
MockHttpServletResponse response = new MockHttpServletResponse();
try {
complexDispatcherServlet.service(request, response);
assertTrue("Correct response", response.getStatus() == HttpServletResponse.SC_FORBIDDEN);
}
catch (ServletException ex) {
fail("Should not have thrown ServletException: " + ex.getMessage());
}
complexDispatcherServlet.service(request, response);
assertTrue("Correct response", response.getStatus() == HttpServletResponse.SC_FORBIDDEN);
}
@Test
@@ -572,14 +558,9 @@ public class DispatcherServletTests {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/unknown.do");
MockHttpServletResponse response = new MockHttpServletResponse();
try {
complexDispatcherServlet.service(request, response);
fail("Should have thrown ServletException");
}
catch (ServletException ex) {
// expected
assertTrue(ex.getMessage().contains("No adapter for handler"));
}
assertThatExceptionOfType(ServletException.class).isThrownBy(() ->
complexDispatcherServlet.service(request, response))
.withMessageContaining("No adapter for handler");
}
@Test
@@ -592,14 +573,9 @@ public class DispatcherServletTests {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/unknown.do");
MockHttpServletResponse response = new MockHttpServletResponse();
try {
complexDispatcherServlet.service(request, response);
fail("Should have thrown ServletException");
}
catch (ServletException ex) {
// expected
assertTrue(ex.getMessage().contains("failed0"));
}
assertThatExceptionOfType(ServletException.class).isThrownBy(() ->
complexDispatcherServlet.service(request, response))
.withMessageContaining("failed0");
}
@Test
@@ -733,13 +709,8 @@ public class DispatcherServletTests {
MockHttpServletRequest request = new MockHttpServletRequest(servletContext, "GET", "/noview");
MockHttpServletResponse response = new MockHttpServletResponse();
try {
complexDispatcherServlet.service(request, response);
fail("Should have thrown ServletException");
}
catch (ServletException ex) {
ex.printStackTrace();
}
assertThatExceptionOfType(ServletException.class).isThrownBy(() ->
complexDispatcherServlet.service(request, response));
}
@Test
@@ -812,12 +783,8 @@ public class DispatcherServletTests {
ConfigurableEnvironment env1 = new StandardServletEnvironment();
servlet.setEnvironment(env1); // should succeed
assertThat(servlet.getEnvironment(), sameInstance(env1));
try {
servlet.setEnvironment(new DummyEnvironment());
fail("expected IllegalArgumentException for non-configurable Environment");
}
catch (IllegalArgumentException ex) {
}
assertThatIllegalArgumentException().as("non-configurable Environment").isThrownBy(() ->
servlet.setEnvironment(new DummyEnvironment()));
class CustomServletEnvironment extends StandardServletEnvironment { }
@SuppressWarnings("serial")
DispatcherServlet custom = new DispatcherServlet() {

View File

@@ -141,6 +141,7 @@ import org.springframework.web.servlet.view.tiles3.TilesConfigurer;
import org.springframework.web.servlet.view.tiles3.TilesViewResolver;
import org.springframework.web.util.UrlPathHelper;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.instanceOf;
@@ -262,7 +263,7 @@ public class MvcNamespaceTests {
assertEquals(BeanNameUrlHandlerMapping.class, introspector.getHandlerMappings().get(1).getClass());
}
@Test(expected = TypeMismatchException.class)
@Test
public void testCustomConversionService() throws Exception {
loadBeanDefinitions("mvc-config-custom-conversion-service.xml");
@@ -285,7 +286,8 @@ public class MvcNamespaceTests {
RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
assertNotNull(adapter);
adapter.handle(request, response, handlerMethod);
assertThatExceptionOfType(TypeMismatchException.class).isThrownBy(() ->
adapter.handle(request, response, handlerMethod));
}
@Test

View File

@@ -44,6 +44,8 @@ import org.springframework.util.MultiValueMap;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
/**
@@ -150,7 +152,7 @@ public class DefaultServerRequestTests {
assertEquals("bar", request.pathVariable("foo"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void pathVariableNotFound() {
MockHttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/");
Map<String, String> pathVariables = Collections.singletonMap("foo", "bar");
@@ -160,7 +162,8 @@ public class DefaultServerRequestTests {
DefaultServerRequest request = new DefaultServerRequest(servletRequest,
this.messageConverters);
request.pathVariable("baz");
assertThatIllegalArgumentException().isThrownBy(() ->
request.pathVariable("baz"));
}
@Test
@@ -253,7 +256,7 @@ public class DefaultServerRequestTests {
assertEquals("bar", result.get(1));
}
@Test(expected = HttpMediaTypeNotSupportedException.class)
@Test
public void bodyUnacceptable() throws Exception {
MockHttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/");
servletRequest.setContentType(MediaType.TEXT_PLAIN_VALUE);
@@ -262,7 +265,8 @@ public class DefaultServerRequestTests {
DefaultServerRequest request =
new DefaultServerRequest(servletRequest, Collections.emptyList());
request.body(String.class);
assertThatExceptionOfType(HttpMediaTypeNotSupportedException.class).isThrownBy(() ->
request.body(String.class));
}
@Test

View File

@@ -31,7 +31,6 @@ import static java.util.Collections.emptyList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.springframework.web.servlet.function.RequestPredicates.HEAD;
/**
@@ -95,9 +94,8 @@ public class RouterFunctionBuilderTests {
try {
return handlerFunction.handle(request);
}
catch (Exception e) {
fail(e.getMessage());
return null;
catch (Exception ex) {
throw new AssertionError(ex.getMessage(), ex);
}
}

View File

@@ -26,7 +26,6 @@ import static java.util.Collections.emptyList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Arjen Poutsma
@@ -112,9 +111,8 @@ public class RouterFunctionTests {
try {
return hf.handle(request);
}
catch (Exception e) {
fail(e.getMessage());
return null;
catch (Exception ex) {
throw new AssertionError(ex.getMessage(), ex);
}
});
assertTrue(resultHandlerFunction.isPresent());

View File

@@ -29,8 +29,8 @@ import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerMapping;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Rod Johnson
@@ -193,13 +193,8 @@ public class BeanNameUrlHandlerMappingTests {
@Test
public void doubleMappings() throws ServletException {
BeanNameUrlHandlerMapping hm = (BeanNameUrlHandlerMapping) wac.getBean("handlerMapping");
try {
hm.registerHandler("/mypath/welcome.html", new Object());
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
assertThatIllegalStateException().isThrownBy(() ->
hm.registerHandler("/mypath/welcome.html", new Object()));
}
}

View File

@@ -39,6 +39,7 @@ import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
@@ -109,14 +110,15 @@ public class HandlerMappingIntrospectorTests {
assertNull("Attributes changes not ignored", request.getAttribute(BEST_MATCHING_PATTERN_ATTRIBUTE));
}
@Test(expected = IllegalStateException.class)
@Test
public void getMatchableWhereHandlerMappingDoesNotImplementMatchableInterface() throws Exception {
StaticWebApplicationContext cxt = new StaticWebApplicationContext();
cxt.registerSingleton("hm1", TestHandlerMapping.class);
cxt.refresh();
MockHttpServletRequest request = new MockHttpServletRequest();
getIntrospector(cxt).getMatchableHandlerMapping(request);
assertThatIllegalStateException().isThrownBy(() ->
getIntrospector(cxt).getMatchableHandlerMapping(request));
}
@Test

View File

@@ -38,6 +38,7 @@ import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.util.UrlPathHelper;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
@@ -70,10 +71,11 @@ public class HandlerMethodMappingTests {
}
@Test(expected = IllegalStateException.class)
@Test
public void registerDuplicates() {
this.mapping.registerMapping("foo", this.handler, this.method1);
this.mapping.registerMapping("foo", this.handler, this.method2);
assertThatIllegalStateException().isThrownBy(() ->
this.mapping.registerMapping("foo", this.handler, this.method2));
}
@Test
@@ -98,12 +100,13 @@ public class HandlerMethodMappingTests {
assertEquals(result, request.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE));
}
@Test(expected = IllegalStateException.class)
@Test
public void ambiguousMatch() throws Exception {
this.mapping.registerMapping("/f?o", this.handler, this.method1);
this.mapping.registerMapping("/fo?", this.handler, this.method2);
this.mapping.getHandlerInternal(new MockHttpServletRequest("GET", "/foo"));
assertThatIllegalStateException().isThrownBy(() ->
this.mapping.getHandlerInternal(new MockHttpServletRequest("GET", "/foo")));
}
@Test

View File

@@ -32,11 +32,12 @@ import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.util.WebUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Rod Johnson
@@ -57,14 +58,10 @@ public class SimpleUrlHandlerMappingTests {
wac.setServletContext(sc);
wac.setNamespace("map2err");
wac.setConfigLocations("/org/springframework/web/servlet/handler/map2err.xml");
try {
wac.refresh();
fail("Should have thrown NoSuchBeanDefinitionException");
}
catch (FatalBeanException ex) {
NoSuchBeanDefinitionException nestedEx = (NoSuchBeanDefinitionException) ex.getCause();
assertEquals("mainControlle", nestedEx.getBeanName());
}
assertThatExceptionOfType(FatalBeanException.class).isThrownBy(
wac::refresh)
.withCauseInstanceOf(NoSuchBeanDefinitionException.class)
.satisfies(ex -> assertThat(((NoSuchBeanDefinitionException) ex.getCause()).getBeanName()).isEqualTo("mainControlle"));
}
@Test

View File

@@ -31,12 +31,12 @@ import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
import org.springframework.web.util.WebUtils;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Alef Arendsen
@@ -93,14 +93,10 @@ public class CookieLocaleResolverTests {
CookieLocaleResolver resolver = new CookieLocaleResolver();
resolver.setCookieName("LanguageKoekje");
try {
resolver.resolveLocaleContext(request);
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
assertTrue(ex.getMessage().contains("LanguageKoekje"));
assertTrue(ex.getMessage().contains("++ GMT+1"));
}
assertThatIllegalStateException().isThrownBy(() ->
resolver.resolveLocaleContext(request))
.withMessageContaining("LanguageKoekje")
.withMessageContaining("++ GMT+1");
}
@Test
@@ -128,14 +124,10 @@ public class CookieLocaleResolverTests {
CookieLocaleResolver resolver = new CookieLocaleResolver();
resolver.setCookieName("LanguageKoekje");
try {
resolver.resolveLocaleContext(request);
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
assertTrue(ex.getMessage().contains("LanguageKoekje"));
assertTrue(ex.getMessage().contains("nl X-MT"));
}
assertThatIllegalStateException().isThrownBy(() ->
resolver.resolveLocaleContext(request))
.withMessageContaining("LanguageKoekje")
.withMessageContaining("nl X-MT");
}
@Test

View File

@@ -31,6 +31,7 @@ import org.springframework.mock.web.test.MockServletContext;
import org.springframework.web.servlet.LocaleContextResolver;
import org.springframework.web.servlet.LocaleResolver;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
@@ -75,16 +76,13 @@ public class LocaleResolverTests {
// set new locale
try {
localeResolver.setLocale(request, response, Locale.GERMANY);
if (!shouldSet)
fail("should not be able to set Locale");
assertThat(shouldSet).as("should not be able to set Locale").isTrue();
// check new locale
locale = localeResolver.resolveLocale(request);
assertEquals(Locale.GERMANY, locale);
}
catch (UnsupportedOperationException ex) {
if (shouldSet) {
fail("should be able to set Locale");
}
assertThat(shouldSet).as("should be able to set Locale").isFalse();
}
// check LocaleContext

View File

@@ -24,6 +24,7 @@ import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
@@ -160,10 +161,11 @@ public class WebContentInterceptorTests {
assertThat(cacheControlHeaders, Matchers.contains("max-age=10, must-revalidate"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void throwsExceptionWithNullPathMatcher() throws Exception {
WebContentInterceptor interceptor = new WebContentInterceptor();
interceptor.setPathMatcher(null);
assertThatIllegalArgumentException().isThrownBy(() ->
interceptor.setPathMatcher(null));
}
}

View File

@@ -24,6 +24,7 @@ import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.web.bind.annotation.RequestMethod;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
@@ -73,11 +74,12 @@ public class CompositeRequestConditionTests {
assertSame(notEmpty, empty.combine(notEmpty));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void combineDifferentLength() {
CompositeRequestCondition cond1 = new CompositeRequestCondition(this.param1);
CompositeRequestCondition cond2 = new CompositeRequestCondition(this.param1, this.header1);
cond1.combine(cond2);
assertThatIllegalArgumentException().isThrownBy(() ->
cond1.combine(cond2));
}
@Test
@@ -132,11 +134,12 @@ public class CompositeRequestConditionTests {
assertEquals(1, empty.compareTo(notEmpty, request));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void compareDifferentLength() {
CompositeRequestCondition cond1 = new CompositeRequestCondition(this.param1);
CompositeRequestCondition cond2 = new CompositeRequestCondition(this.param1, this.header1);
cond1.compareTo(cond2, new MockHttpServletRequest());
assertThatIllegalArgumentException().isThrownBy(() ->
cond1.compareTo(cond2, new MockHttpServletRequest()));
}
}

View File

@@ -25,11 +25,11 @@ import org.springframework.http.HttpHeaders;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.web.servlet.mvc.condition.ConsumesRequestCondition.ConsumeMediaTypeExpression;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Arjen Poutsma
@@ -207,21 +207,8 @@ public class ConsumesRequestConditionTests {
private void assertConditions(ConsumesRequestCondition condition, String... expected) {
Collection<ConsumeMediaTypeExpression> expressions = condition.getContent();
assertEquals("Invalid amount of conditions", expressions.size(), expected.length);
for (String s : expected) {
boolean found = false;
for (ConsumeMediaTypeExpression expr : expressions) {
String conditionMediaType = expr.getMediaType().toString();
if (conditionMediaType.equals(s)) {
found = true;
break;
}
}
if (!found) {
fail("Condition [" + s + "] not found");
}
}
assertThat(expressions.stream().map(expr -> expr.getMediaType().toString()))
.containsExactlyInAnyOrder(expected);
}
}

View File

@@ -30,11 +30,11 @@ import org.springframework.web.accept.FixedContentNegotiationStrategy;
import org.springframework.web.accept.HeaderContentNegotiationStrategy;
import org.springframework.web.servlet.mvc.condition.ProducesRequestCondition.ProduceMediaTypeExpression;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Unit tests for {@link ProducesRequestCondition}.
@@ -370,21 +370,8 @@ public class ProducesRequestConditionTests {
private void assertConditions(ProducesRequestCondition condition, String... expected) {
Collection<ProduceMediaTypeExpression> expressions = condition.getContent();
assertEquals("Invalid number of conditions", expressions.size(), expected.length);
for (String s : expected) {
boolean found = false;
for (ProduceMediaTypeExpression expr : expressions) {
String conditionMediaType = expr.getMediaType().toString();
if (conditionMediaType.equals(s)) {
found = true;
break;
}
}
if (!found) {
fail("Condition [" + s + "] not found");
}
}
assertThat(expressions.stream().map(expr -> expr.getMediaType().toString()))
.containsExactlyInAnyOrder(expected);
}
}

View File

@@ -23,6 +23,7 @@ import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.web.bind.annotation.RequestMethod;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
@@ -53,11 +54,12 @@ public class RequestConditionHolderTests {
assertSame(notEmpty, empty.combine(notEmpty));
}
@Test(expected = ClassCastException.class)
@Test
public void combineIncompatible() {
RequestConditionHolder params = new RequestConditionHolder(new ParamsRequestCondition("name"));
RequestConditionHolder headers = new RequestConditionHolder(new HeadersRequestCondition("name"));
params.combine(headers);
assertThatExceptionOfType(ClassCastException.class).isThrownBy(() ->
params.combine(headers));
}
@Test
@@ -112,11 +114,12 @@ public class RequestConditionHolderTests {
assertEquals(1, empty.compareTo(notEmpty, request));
}
@Test(expected = ClassCastException.class)
@Test
public void compareIncompatible() {
RequestConditionHolder params = new RequestConditionHolder(new ParamsRequestCondition("name"));
RequestConditionHolder headers = new RequestConditionHolder(new HeadersRequestCondition("name"));
params.compareTo(headers, new MockHttpServletRequest());
assertThatExceptionOfType(ClassCastException.class).isThrownBy(() ->
params.compareTo(headers, new MockHttpServletRequest()));
}
}

View File

@@ -20,7 +20,6 @@ import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
@@ -59,14 +58,12 @@ import org.springframework.web.servlet.mvc.condition.ProducesRequestCondition;
import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition;
import org.springframework.web.util.UrlPathHelper;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.Assert.assertArrayEquals;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
/**
* Test fixture with {@link RequestMappingInfoHandlerMapping}.
@@ -150,23 +147,19 @@ public class RequestMappingInfoHandlerMappingTests {
@Test
public void getHandlerRequestMethodNotAllowed() throws Exception {
try {
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/bar");
this.handlerMapping.getHandler(request);
fail("HttpRequestMethodNotSupportedException expected");
}
catch (HttpRequestMethodNotSupportedException ex) {
assertArrayEquals("Invalid supported methods", new String[]{"GET", "HEAD"},
ex.getSupportedMethods());
}
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/bar");
assertThatExceptionOfType(HttpRequestMethodNotSupportedException.class).isThrownBy(() ->
this.handlerMapping.getHandler(request))
.satisfies(ex -> assertThat(ex.getSupportedMethods()).containsExactly("GET", "HEAD"));
}
@Test(expected = HttpMediaTypeNotAcceptableException.class) // SPR-9603
@Test // SPR-9603
public void getHandlerRequestMethodMatchFalsePositive() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/users");
request.addHeader("Accept", "application/xml");
this.handlerMapping.registerHandler(new UserController());
this.handlerMapping.getHandler(request);
assertThatExceptionOfType(HttpMediaTypeNotAcceptableException.class).isThrownBy(() ->
this.handlerMapping.getHandler(request));
}
@Test // SPR-8462
@@ -186,15 +179,11 @@ public class RequestMappingInfoHandlerMappingTests {
@Test
public void getHandlerTestInvalidContentType() throws Exception {
try {
MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/person/1");
request.setContentType("bogus");
this.handlerMapping.getHandler(request);
fail("HttpMediaTypeNotSupportedException expected");
}
catch (HttpMediaTypeNotSupportedException ex) {
assertEquals("Invalid mime type \"bogus\": does not contain '/'", ex.getMessage());
}
MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/person/1");
request.setContentType("bogus");
assertThatExceptionOfType(HttpMediaTypeNotSupportedException.class).isThrownBy(() ->
this.handlerMapping.getHandler(request))
.withMessage("Invalid mime type \"bogus\": does not contain '/'");
}
@Test // SPR-8462
@@ -206,17 +195,11 @@ public class RequestMappingInfoHandlerMappingTests {
@Test // SPR-12854
public void getHandlerUnsatisfiedServletRequestParameterException() throws Exception {
try {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/params");
this.handlerMapping.getHandler(request);
fail("UnsatisfiedServletRequestParameterException expected");
}
catch (UnsatisfiedServletRequestParameterException ex) {
List<String[]> groups = ex.getParamConditionGroups();
assertEquals(2, groups.size());
assertThat(Arrays.asList("foo=bar", "bar=baz"),
containsInAnyOrder(groups.get(0)[0], groups.get(1)[0]));
}
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/params");
assertThatExceptionOfType(UnsatisfiedServletRequestParameterException.class).isThrownBy(() ->
this.handlerMapping.getHandler(request))
.satisfies(ex -> assertThat(ex.getParamConditionGroups().stream().map(group -> group[0]))
.containsExactlyInAnyOrder("foo=bar", "bar=baz"));
}
@Test
@@ -395,17 +378,11 @@ public class RequestMappingInfoHandlerMappingTests {
}
private void testHttpMediaTypeNotSupportedException(String url) throws Exception {
try {
MockHttpServletRequest request = new MockHttpServletRequest("PUT", url);
request.setContentType("application/json");
this.handlerMapping.getHandler(request);
fail("HttpMediaTypeNotSupportedException expected");
}
catch (HttpMediaTypeNotSupportedException ex) {
assertEquals("Invalid supported consumable media types",
Collections.singletonList(new MediaType("application", "xml")),
ex.getSupportedMediaTypes());
}
MockHttpServletRequest request = new MockHttpServletRequest("PUT", url);
request.setContentType("application/json");
assertThatExceptionOfType(HttpMediaTypeNotSupportedException.class).isThrownBy(() ->
this.handlerMapping.getHandler(request))
.satisfies(ex -> assertThat(ex.getSupportedMediaTypes()).containsExactly(MediaType.APPLICATION_XML));
}
private void testHttpOptions(String requestURI, String allowHeader) throws Exception {
@@ -422,17 +399,11 @@ public class RequestMappingInfoHandlerMappingTests {
}
private void testHttpMediaTypeNotAcceptableException(String url) throws Exception {
try {
MockHttpServletRequest request = new MockHttpServletRequest("GET", url);
request.addHeader("Accept", "application/json");
this.handlerMapping.getHandler(request);
fail("HttpMediaTypeNotAcceptableException expected");
}
catch (HttpMediaTypeNotAcceptableException ex) {
assertEquals("Invalid supported producible media types",
Collections.singletonList(new MediaType("application", "xml")),
ex.getSupportedMediaTypes());
}
MockHttpServletRequest request = new MockHttpServletRequest("GET", url);
request.addHeader("Accept", "application/json");
assertThatExceptionOfType(HttpMediaTypeNotAcceptableException.class).isThrownBy(() ->
this.handlerMapping.getHandler(request))
.satisfies(ex -> assertThat(ex.getSupportedMediaTypes()).containsExactly(MediaType.APPLICATION_XML));
}
private void handleMatch(MockHttpServletRequest request, String pattern, String lookupPath) {

View File

@@ -41,13 +41,13 @@ import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@@ -96,13 +96,9 @@ public abstract class AbstractRequestAttributesArgumentResolverTests {
@Test
public void resolve() throws Exception {
MethodParameter param = initMethodParameter(0);
try {
testResolveArgument(param);
fail("Should be required by default");
}
catch (ServletRequestBindingException ex) {
assertTrue(ex.getMessage().startsWith("Missing "));
}
assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() ->
testResolveArgument(param))
.withMessageStartingWith("Missing ");
Foo foo = new Foo();
this.webRequest.setAttribute("foo", foo, getScope());

View File

@@ -36,6 +36,7 @@ import org.springframework.web.method.ResolvableMethod;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.HandlerMapping;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@@ -109,19 +110,21 @@ public class MatrixVariablesMethodArgumentResolverTests {
assertEquals("2013", resolver.resolveArgument(param, this.mavContainer, this.webRequest, null));
}
@Test(expected = ServletRequestBindingException.class)
@Test
public void resolveArgumentMultipleMatches() throws Exception {
getVariablesFor("var1").add("colors", "red");
getVariablesFor("var2").add("colors", "green");
MethodParameter param = this.testMethod.annot(matrixAttribute().noName()).arg(List.class, String.class);
this.resolver.resolveArgument(param, this.mavContainer, this.webRequest, null);
assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() ->
this.resolver.resolveArgument(param, this.mavContainer, this.webRequest, null));
}
@Test(expected = ServletRequestBindingException.class)
@Test
public void resolveArgumentRequired() throws Exception {
MethodParameter param = this.testMethod.annot(matrixAttribute().noName()).arg(List.class, String.class);
this.resolver.resolveArgument(param, this.mavContainer, this.webRequest, null);
assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() ->
this.resolver.resolveArgument(param, this.mavContainer, this.webRequest, null));
}
@Test

View File

@@ -33,6 +33,7 @@ import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.annotation.ModelAndViewResolver;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
@@ -77,11 +78,12 @@ public class ModelAndViewResolverMethodReturnValueHandlerTests {
assertFalse(mavContainer.isRequestHandled());
}
@Test(expected = UnsupportedOperationException.class)
@Test
public void modelAndViewResolverUnresolved() throws Exception {
MethodParameter returnType = new MethodParameter(getClass().getDeclaredMethod("intReturnValue"), -1);
mavResolvers.add(new TestModelAndViewResolver(TestBean.class));
handler.handleReturnValue(99, returnType, mavContainer, request);
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
handler.handleReturnValue(99, returnType, mavContainer, request));
}
@Test
@@ -94,10 +96,11 @@ public class ModelAndViewResolverMethodReturnValueHandlerTests {
assertTrue(mavContainer.getModel().isEmpty());
}
@Test(expected = UnsupportedOperationException.class)
@Test
public void handleSimpleType() throws Exception {
MethodParameter returnType = new MethodParameter(getClass().getDeclaredMethod("intReturnValue"), -1);
handler.handleReturnValue(55, returnType, mavContainer, request);
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
handler.handleReturnValue(55, returnType, mavContainer, request));
}
@Test

View File

@@ -62,6 +62,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
@@ -383,12 +384,13 @@ public class MvcUriComponentsBuilderTests {
assertEquals("http://localhost/hotels/42/bookings/21", uriComponents.encode().toUri().toString());
}
@Test(expected = IllegalStateException.class) // SPR-16710
@Test // SPR-16710
public void fromMethodCallWithStringReturnType() {
UriComponents uriComponents = fromMethodCall(
on(BookingControllerWithString.class).getBooking(21L)).buildAndExpand(42);
assertEquals("http://localhost/hotels/42/bookings/21", uriComponents.encode().toUri().toString());
assertThatIllegalStateException().isThrownBy(() -> {
UriComponents uriComponents = fromMethodCall(
on(BookingControllerWithString.class).getBooking(21L)).buildAndExpand(42);
uriComponents.encode().toUri().toString();
});
}
@Test // SPR-16710

View File

@@ -40,12 +40,12 @@ import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.View;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Test fixture with {@link PathVariableMethodArgumentResolver}.
@@ -164,10 +164,10 @@ public class PathVariableMethodArgumentResolverTests {
assertEquals("oldValue", pathVars.get("oldName"));
}
@Test(expected = MissingPathVariableException.class)
@Test
public void handleMissingValue() throws Exception {
resolver.resolveArgument(paramNamedString, mavContainer, webRequest, null);
fail("Unresolved path variable should lead to exception");
assertThatExceptionOfType(MissingPathVariableException.class).isThrownBy(() ->
resolver.resolveArgument(paramNamedString, mavContainer, webRequest, null));
}
@Test

View File

@@ -42,6 +42,7 @@ import org.springframework.mock.web.test.MockMultipartFile;
import org.springframework.mock.web.test.MockMultipartHttpServletRequest;
import org.springframework.mock.web.test.MockPart;
import org.springframework.util.ReflectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.WebDataBinder;
@@ -55,12 +56,13 @@ import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.BDDMockito.given;
@@ -280,15 +282,14 @@ public class RequestPartMethodArgumentResolverTests {
@Test
public void resolveRequestPartNotValid() throws Exception {
try {
testResolveArgument(new SimpleBean(null), paramValidRequestPart);
fail("Expected exception");
}
catch (MethodArgumentNotValidException ex) {
assertEquals("requestPart", ex.getBindingResult().getObjectName());
assertEquals(1, ex.getBindingResult().getErrorCount());
assertNotNull(ex.getBindingResult().getFieldError("name"));
}
assertThatExceptionOfType(MethodArgumentNotValidException.class).isThrownBy(() ->
testResolveArgument(new SimpleBean(null), paramValidRequestPart))
.satisfies(ex -> {
BindingResult bindingResult = ex.getBindingResult();
assertThat(bindingResult.getObjectName()).isEqualTo("requestPart");
assertThat(bindingResult.getErrorCount()).isEqualTo(1);
assertThat(bindingResult.getFieldError("name")).isNotNull();
});
}
@Test
@@ -298,13 +299,9 @@ public class RequestPartMethodArgumentResolverTests {
@Test
public void resolveRequestPartRequired() throws Exception {
try {
testResolveArgument(null, paramValidRequestPart);
fail("Expected exception");
}
catch (MissingServletRequestPartException ex) {
assertEquals("requestPart", ex.getRequestPartName());
}
assertThatExceptionOfType(MissingServletRequestPartException.class).isThrownBy(() ->
testResolveArgument(null, paramValidRequestPart))
.satisfies(ex -> assertThat(ex.getRequestPartName()).isEqualTo("requestPart"));
}
@Test
@@ -312,10 +309,11 @@ public class RequestPartMethodArgumentResolverTests {
testResolveArgument(new SimpleBean("foo"), paramValidRequestPart);
}
@Test(expected = MultipartException.class)
@Test
public void isMultipartRequest() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
resolver.resolveArgument(paramMultipartFile, new ModelAndViewContainer(), new ServletWebRequest(request), null);
assertThatExceptionOfType(MultipartException.class).isThrownBy(() ->
resolver.resolveArgument(paramMultipartFile, new ModelAndViewContainer(), new ServletWebRequest(request), null));
}
@Test // SPR-9079

View File

@@ -40,6 +40,7 @@ import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.lang.Nullable;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
import org.springframework.validation.BindingResult;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
@@ -53,12 +54,12 @@ import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.HandlerMapping;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.ArgumentMatchers.argThat;
@@ -173,15 +174,14 @@ public class RequestResponseBodyMethodProcessorMockTests {
@Test
public void resolveArgumentNotValid() throws Exception {
try {
testResolveArgumentWithValidation(new SimpleBean(null));
fail("Expected exception");
}
catch (MethodArgumentNotValidException e) {
assertEquals("simpleBean", e.getBindingResult().getObjectName());
assertEquals(1, e.getBindingResult().getErrorCount());
assertNotNull(e.getBindingResult().getFieldError("name"));
}
assertThatExceptionOfType(MethodArgumentNotValidException.class).isThrownBy(() ->
testResolveArgumentWithValidation(new SimpleBean(null)))
.satisfies(ex -> {
BindingResult bindingResult = ex.getBindingResult();
assertThat(bindingResult.getObjectName()).isEqualTo("simpleBean");
assertThat(bindingResult.getErrorCount()).isEqualTo(1);
assertThat(bindingResult.getFieldError("name")).isNotNull();
});
}
@Test
@@ -204,7 +204,7 @@ public class RequestResponseBodyMethodProcessorMockTests {
processor.resolveArgument(paramValidBean, mavContainer, webRequest, new ValidatingBinderFactory());
}
@Test(expected = HttpMediaTypeNotSupportedException.class)
@Test
public void resolveArgumentCannotRead() throws Exception {
MediaType contentType = MediaType.TEXT_PLAIN;
servletRequest.addHeader("Content-Type", contentType.toString());
@@ -212,31 +212,35 @@ public class RequestResponseBodyMethodProcessorMockTests {
given(stringMessageConverter.canRead(String.class, contentType)).willReturn(false);
processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null);
assertThatExceptionOfType(HttpMediaTypeNotSupportedException.class).isThrownBy(() ->
processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null));
}
@Test(expected = HttpMediaTypeNotSupportedException.class)
@Test
public void resolveArgumentNoContentType() throws Exception {
servletRequest.setContent("payload".getBytes(StandardCharsets.UTF_8));
given(stringMessageConverter.canRead(String.class, MediaType.APPLICATION_OCTET_STREAM)).willReturn(false);
processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null);
assertThatExceptionOfType(HttpMediaTypeNotSupportedException.class).isThrownBy(() ->
processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null));
}
@Test(expected = HttpMediaTypeNotSupportedException.class)
@Test
public void resolveArgumentInvalidContentType() throws Exception {
this.servletRequest.setContentType("bad");
servletRequest.setContent("payload".getBytes(StandardCharsets.UTF_8));
processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null);
assertThatExceptionOfType(HttpMediaTypeNotSupportedException.class).isThrownBy(() ->
processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null));
}
@Test(expected = HttpMessageNotReadableException.class) // SPR-9942
@Test // SPR-9942
public void resolveArgumentRequiredNoContent() throws Exception {
servletRequest.setContentType(MediaType.TEXT_PLAIN_VALUE);
servletRequest.setContent(new byte[0]);
given(stringMessageConverter.canRead(String.class, MediaType.TEXT_PLAIN)).willReturn(true);
given(stringMessageConverter.read(eq(String.class), isA(HttpInputMessage.class))).willReturn(null);
assertNull(processor.resolveArgument(paramRequestBodyString, mavContainer,
webRequest, new ValidatingBinderFactory()));
assertThatExceptionOfType(HttpMessageNotReadableException.class).isThrownBy(() ->
processor.resolveArgument(paramRequestBodyString, mavContainer,
webRequest, new ValidatingBinderFactory()));
}
@Test
@@ -336,7 +340,7 @@ public class RequestResponseBodyMethodProcessorMockTests {
}
@Test(expected = HttpMediaTypeNotAcceptableException.class)
@Test
public void handleReturnValueNotAcceptable() throws Exception {
MediaType accepted = MediaType.APPLICATION_ATOM_XML;
servletRequest.addHeader("Accept", accepted.toString());
@@ -345,10 +349,11 @@ public class RequestResponseBodyMethodProcessorMockTests {
given(stringMessageConverter.getSupportedMediaTypes()).willReturn(Arrays.asList(MediaType.TEXT_PLAIN));
given(stringMessageConverter.canWrite(String.class, accepted)).willReturn(false);
processor.handleReturnValue("Foo", returnTypeString, mavContainer, webRequest);
assertThatExceptionOfType(HttpMediaTypeNotAcceptableException.class).isThrownBy(() ->
processor.handleReturnValue("Foo", returnTypeString, mavContainer, webRequest));
}
@Test(expected = HttpMediaTypeNotAcceptableException.class)
@Test
public void handleReturnValueNotAcceptableProduces() throws Exception {
MediaType accepted = MediaType.TEXT_PLAIN;
servletRequest.addHeader("Accept", accepted.toString());
@@ -357,7 +362,8 @@ public class RequestResponseBodyMethodProcessorMockTests {
given(stringMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
given(stringMessageConverter.canWrite(String.class, accepted)).willReturn(false);
processor.handleReturnValue("Foo", returnTypeStringProduces, mavContainer, webRequest);
assertThatExceptionOfType(HttpMediaTypeNotAcceptableException.class).isThrownBy(() ->
processor.handleReturnValue("Foo", returnTypeStringProduces, mavContainer, webRequest));
}
@Test

View File

@@ -70,6 +70,8 @@ import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import org.springframework.web.util.WebUtils;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
@@ -196,14 +198,15 @@ public class RequestResponseBodyMethodProcessorTests {
assertEquals("foobarbaz", result);
}
@Test(expected = HttpMessageNotReadableException.class) // SPR-9942
@Test // SPR-9942
public void resolveArgumentRequiredNoContent() throws Exception {
this.servletRequest.setContent(new byte[0]);
this.servletRequest.setContentType("text/plain");
List<HttpMessageConverter<?>> converters = new ArrayList<>();
converters.add(new StringHttpMessageConverter());
RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters);
processor.resolveArgument(paramString, container, request, factory);
assertThatExceptionOfType(HttpMessageNotReadableException.class).isThrownBy(() ->
processor.resolveArgument(paramString, container, request, factory));
}
@Test // SPR-12778
@@ -361,12 +364,14 @@ public class RequestResponseBodyMethodProcessorTests {
// SPR-13135
@Test(expected = IllegalArgumentException.class)
@Test
public void handleReturnValueWithInvalidReturnType() throws Exception {
Method method = getClass().getDeclaredMethod("handleAndReturnOutputStream");
MethodParameter returnType = new MethodParameter(method, -1);
RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(new ArrayList<>());
processor.writeWithMessageConverters(new ByteArrayOutputStream(), returnType, this.request);
assertThatIllegalArgumentException().isThrownBy(() -> {
RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(new ArrayList<>());
processor.writeWithMessageConverters(new ByteArrayOutputStream(), returnType, this.request);
});
}
@Test

View File

@@ -26,8 +26,9 @@ import org.mockito.MockitoAnnotations;
import org.springframework.http.MediaType;
import static org.assertj.core.api.Assertions.assertThatIOException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock;
@@ -98,10 +99,11 @@ public class ResponseBodyEmitterTests {
verifyNoMoreInteractions(this.handler);
}
@Test(expected = IllegalStateException.class)
@Test
public void sendFailsAfterComplete() throws Exception {
this.emitter.complete();
this.emitter.send("foo");
assertThatIllegalStateException().isThrownBy(() ->
this.emitter.send("foo"));
}
@Test
@@ -151,13 +153,8 @@ public class ResponseBodyEmitterTests {
IOException failure = new IOException();
willThrow(failure).given(this.handler).send("foo", MediaType.TEXT_PLAIN);
try {
this.emitter.send("foo", MediaType.TEXT_PLAIN);
fail("Expected exception");
}
catch (IOException ex) {
// expected
}
assertThatIOException().isThrownBy(() ->
this.emitter.send("foo", MediaType.TEXT_PLAIN));
verify(this.handler).send("foo", MediaType.TEXT_PLAIN);
verifyNoMoreInteractions(this.handler);
}

View File

@@ -52,10 +52,10 @@ import org.springframework.web.method.support.HandlerMethodReturnValueHandlerCom
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.view.RedirectView;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Test fixture with {@link ServletInvocableHandlerMethod}.
@@ -148,13 +148,13 @@ public class ServletInvocableHandlerMethodTests {
assertEquals("400 Bad Request", this.response.getErrorMessage());
}
@Test(expected = HttpMessageNotWritableException.class)
@Test
public void invokeAndHandle_Exception() throws Exception {
this.returnValueHandlers.addHandler(new ExceptionRaisingReturnValueHandler());
ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new Handler(), "handle");
handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer);
fail("Expected exception");
assertThatExceptionOfType(HttpMessageNotWritableException.class).isThrownBy(() ->
handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer));
}
@Test

View File

@@ -19,6 +19,7 @@ package org.springframework.web.servlet.resource;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
@@ -44,9 +45,10 @@ public class FixedVersionStrategyTests {
}
@Test(expected = IllegalArgumentException.class)
@Test
public void emptyPrefixVersion() {
new FixedVersionStrategy(" ");
assertThatIllegalArgumentException().isThrownBy(() ->
new FixedVersionStrategy(" "));
}
@Test

View File

@@ -42,6 +42,8 @@ import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.accept.ContentNegotiationManagerFactoryBean;
import org.springframework.web.servlet.HandlerMapping;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
@@ -510,16 +512,18 @@ public class ResourceHttpRequestHandlerTests {
assertEquals(404, this.response.getStatus());
}
@Test(expected = IllegalStateException.class)
@Test
public void noPathWithinHandlerMappingAttribute() throws Exception {
this.handler.handleRequest(this.request, this.response);
assertThatIllegalStateException().isThrownBy(() ->
this.handler.handleRequest(this.request, this.response));
}
@Test(expected = HttpRequestMethodNotSupportedException.class)
@Test
public void unsupportedHttpMethod() throws Exception {
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css");
this.request.setMethod("POST");
this.handler.handleRequest(this.request, this.response);
assertThatExceptionOfType(HttpRequestMethodNotSupportedException.class).isThrownBy(() ->
this.handler.handleRequest(this.request, this.response));
}
@Test

View File

@@ -41,12 +41,12 @@ import org.springframework.web.servlet.support.BindStatus;
import org.springframework.web.servlet.tags.form.FormTag;
import org.springframework.web.servlet.tags.form.TagWriter;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Juergen Hoeller
@@ -629,13 +629,8 @@ public class BindTagTests extends AbstractTagTests {
BindTag tag = new BindTag();
tag.setPageContext(pc);
tag.setPath("tb");
try {
tag.doStartTag();
fail("Should have thrown JspException");
}
catch (JspException ex) {
// expected
}
assertThatExceptionOfType(JspException.class).isThrownBy(
tag::doStartTag);
}
@@ -906,13 +901,8 @@ public class BindTagTests extends AbstractTagTests {
transform.setPageContext(pc);
transform.setVar("var");
transform.setValue("bla");
try {
transform.doStartTag();
fail("Tag can be executed outside BindTag");
}
catch (JspException e) {
// this is ok!
}
assertThatExceptionOfType(JspException.class).as("executed outside BindTag").isThrownBy(
transform::doStartTag);
// now try to execute the tag outside a bindtag, but inside a messageTag
MessageTag message = new MessageTag();
@@ -922,13 +912,8 @@ public class BindTagTests extends AbstractTagTests {
transform.setVar("var");
transform.setValue("bla");
transform.setParent(message);
try {
transform.doStartTag();
fail("Tag can be executed outside BindTag and inside messagetag");
}
catch (JspException e) {
// this is ok!
}
assertThatExceptionOfType(JspException.class).as("executed outside BindTag and inside messagetag").isThrownBy(
transform::doStartTag);
}
@Test

View File

@@ -27,6 +27,7 @@ import org.junit.Test;
import org.springframework.mock.web.test.MockBodyContent;
import org.springframework.mock.web.test.MockHttpServletResponse;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
@@ -122,12 +123,13 @@ public class ParamTagTests extends AbstractTagTests {
assertEquals("value2", parent.getParam().getValue());
}
@Test(expected = JspException.class)
@Test
public void paramWithNoParent() throws Exception {
tag.setName("name");
tag.setValue("value");
tag.setParent(null);
tag.doEndTag();
assertThatExceptionOfType(JspException.class).isThrownBy(
tag::doEndTag);
}
@SuppressWarnings("serial")

View File

@@ -39,9 +39,9 @@ import org.springframework.tests.sample.beans.TestBean;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
/**
* @author Rob Harrop
@@ -613,14 +613,9 @@ public class CheckboxTagTests extends AbstractFormTagTests {
@Test
public void withNullValue() throws Exception {
try {
this.tag.setPath("name");
this.tag.doStartTag();
fail("Should not be able to render with a null value when binding to a non-boolean.");
}
catch (IllegalArgumentException e) {
// success
}
this.tag.setPath("name");
assertThatIllegalArgumentException().as("null value binding to a non-boolean").isThrownBy(
this.tag::doStartTag);
}
@Test
@@ -648,13 +643,9 @@ public class CheckboxTagTests extends AbstractFormTagTests {
@Test
public void dynamicTypeAttribute() throws JspException {
try {
this.tag.setDynamicAttribute(null, "type", "email");
fail("Expected exception");
}
catch (IllegalArgumentException e) {
assertEquals("Attribute type=\"email\" is not allowed", e.getMessage());
}
assertThatIllegalArgumentException().isThrownBy(() ->
this.tag.setDynamicAttribute(null, "type", "email"))
.withMessage("Attribute type=\"email\" is not allowed");
}

View File

@@ -46,10 +46,10 @@ import org.springframework.util.ObjectUtils;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
/**
* @author Thomas Risberg
@@ -677,14 +677,9 @@ public class CheckboxesTagTests extends AbstractFormTagTests {
@Test
public void withNullValue() throws Exception {
try {
this.tag.setPath("name");
this.tag.doStartTag();
fail("Should not be able to render with a null value when binding to a non-boolean.");
}
catch (IllegalArgumentException ex) {
// success
}
this.tag.setPath("name");
assertThatIllegalArgumentException().as("null value binding to a non-boolean").isThrownBy(
this.tag::doStartTag);
}
@Test
@@ -733,13 +728,9 @@ public class CheckboxesTagTests extends AbstractFormTagTests {
@Test
public void dynamicTypeAttribute() throws JspException {
try {
this.tag.setDynamicAttribute(null, "type", "email");
fail("Expected exception");
}
catch (IllegalArgumentException e) {
assertEquals("Attribute type=\"email\" is not allowed", e.getMessage());
}
assertThatIllegalArgumentException().isThrownBy(() ->
this.tag.setDynamicAttribute(null, "type", "email"))
.withMessage("Attribute type=\"email\" is not allowed");
}

View File

@@ -25,11 +25,11 @@ import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.web.servlet.support.RequestDataValueProcessor;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
/**
@@ -219,14 +219,9 @@ public class FormTagTests extends AbstractHtmlElementTagTests {
@Test
public void withNullResolvedCommand() throws Exception {
try {
tag.setModelAttribute(null);
tag.doStartTag();
fail("Must not be able to have a command name that resolves to null");
}
catch (IllegalArgumentException ex) {
// expected
}
tag.setModelAttribute(null);
assertThatIllegalArgumentException().isThrownBy(
tag::doStartTag);
}
/**

View File

@@ -24,9 +24,9 @@ import org.junit.Test;
import org.springframework.tests.sample.beans.TestBean;
import org.springframework.validation.BeanPropertyBindingResult;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Rob Harrop
@@ -86,13 +86,9 @@ public class HiddenInputTagTests extends AbstractFormTagTests {
@Test
public void dynamicTypeAttribute() throws JspException {
try {
this.tag.setDynamicAttribute(null, "type", "email");
fail("Expected exception");
}
catch (IllegalArgumentException e) {
assertEquals("Attribute type=\"email\" is not allowed", e.getMessage());
}
assertThatIllegalArgumentException().isThrownBy(() ->
this.tag.setDynamicAttribute(null, "type", "email"))
.withMessage("Attribute type=\"email\" is not allowed");
}
@Test

View File

@@ -28,9 +28,9 @@ import org.springframework.web.servlet.support.BindStatus;
import org.springframework.web.servlet.tags.BindTag;
import org.springframework.web.servlet.tags.NestedPathTag;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Rob Harrop
@@ -360,24 +360,16 @@ public class InputTagTests extends AbstractFormTagTests {
@Test
public void dynamicTypeRadioAttribute() throws JspException {
try {
this.tag.setDynamicAttribute(null, "type", "radio");
fail("Expected exception");
}
catch (IllegalArgumentException e) {
assertEquals("Attribute type=\"radio\" is not allowed", e.getMessage());
}
assertThatIllegalArgumentException().isThrownBy(() ->
this.tag.setDynamicAttribute(null, "type", "radio"))
.withMessage("Attribute type=\"radio\" is not allowed");
}
@Test
public void dynamicTypeCheckboxAttribute() throws JspException {
try {
this.tag.setDynamicAttribute(null, "type", "checkbox");
fail("Expected exception");
}
catch (IllegalArgumentException e) {
assertEquals("Attribute type=\"checkbox\" is not allowed", e.getMessage());
}
assertThatIllegalArgumentException().isThrownBy(() ->
this.tag.setDynamicAttribute(null, "type", "checkbox"))
.withMessage("Attribute type=\"checkbox\" is not allowed");
}
protected final void assertTagClosed(String output) {

View File

@@ -35,9 +35,9 @@ import org.springframework.util.StringUtils;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.web.servlet.support.BindStatus;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Rob Harrop
@@ -199,13 +199,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
this.tag.setParent(null);
this.tag.setValue("foo");
this.tag.setLabel("Foo");
try {
tag.doStartTag();
fail("Must not be able to use <option> tag without exposed context.");
}
catch (IllegalStateException ex) {
// expected
}
assertThatIllegalStateException().as("not be able to use <option> tag without exposed context").isThrownBy(
tag::doStartTag);
}
@Test
@@ -469,15 +464,10 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
@Test
public void optionTagNotNestedWithinSelectTag() throws Exception {
try {
tag.setParent(null);
tag.setValue("foo");
tag.doStartTag();
fail("Must throw an IllegalStateException when not nested within a <select/> tag.");
}
catch (IllegalStateException ex) {
// expected
}
tag.setParent(null);
tag.setValue("foo");
assertThatIllegalStateException().as("when not nested within a <select/> tag").isThrownBy(
tag::doStartTag);
}

View File

@@ -22,8 +22,8 @@ import javax.servlet.jsp.tagext.Tag;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
* @author Rob Harrop
@@ -88,13 +88,9 @@ public class PasswordInputTagTests extends InputTagTests {
@Test
@Override
public void dynamicTypeAttribute() throws JspException {
try {
this.getTag().setDynamicAttribute(null, "type", "email");
fail("Expected exception");
}
catch (IllegalArgumentException e) {
assertEquals("Attribute type=\"email\" is not allowed", e.getMessage());
}
assertThatIllegalArgumentException().isThrownBy(() ->
this.getTag().setDynamicAttribute(null, "type", "email"))
.withMessage("Attribute type=\"email\" is not allowed");
}
@Override

View File

@@ -32,10 +32,10 @@ import org.springframework.tests.sample.beans.TestBean;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Rob Harrop
@@ -247,13 +247,9 @@ public class RadioButtonTagTests extends AbstractFormTagTests {
@Test
public void dynamicTypeAttribute() throws JspException {
try {
this.tag.setDynamicAttribute(null, "type", "email");
fail("Expected exception");
}
catch (IllegalArgumentException e) {
assertEquals("Attribute type=\"email\" is not allowed", e.getMessage());
}
assertThatIllegalArgumentException().isThrownBy(() ->
this.tag.setDynamicAttribute(null, "type", "email"))
.withMessage("Attribute type=\"email\" is not allowed");
}
private void assertTagOpened(String output) {

View File

@@ -42,9 +42,9 @@ import org.springframework.tests.sample.beans.TestBean;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
/**
* @author Thomas Risberg
@@ -532,14 +532,9 @@ public class RadioButtonsTagTests extends AbstractFormTagTests {
@Test
public void withNullValue() throws Exception {
try {
this.tag.setPath("name");
this.tag.doStartTag();
fail("Should not be able to render with a null value when binding to a non-boolean.");
}
catch (IllegalArgumentException ex) {
// success
}
this.tag.setPath("name");
assertThatIllegalArgumentException().as("null value when binding to a non-boolean").isThrownBy(
this.tag::doStartTag);
}
@Test
@@ -588,13 +583,9 @@ public class RadioButtonsTagTests extends AbstractFormTagTests {
@Test
public void dynamicTypeAttribute() throws JspException {
try {
this.tag.setDynamicAttribute(null, "type", "email");
fail("Expected exception");
}
catch (IllegalArgumentException e) {
assertEquals("Attribute type=\"email\" is not allowed", e.getMessage());
}
assertThatIllegalArgumentException().isThrownBy(() ->
this.tag.setDynamicAttribute(null, "type", "email"))
.withMessage("Attribute type=\"email\" is not allowed");
}
private Date getDate() {

View File

@@ -48,12 +48,12 @@ import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.support.BindStatus;
import org.springframework.web.servlet.tags.TransformTag;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Rob Harrop
@@ -351,15 +351,10 @@ public class SelectTagTests extends AbstractFormTagTests {
this.tag.setPath("country");
this.tag.setItems(new TestBean());
this.tag.setItemValue("isoCode");
try {
this.tag.doStartTag();
fail("Must not be able to use a non-Collection typed value as the value of 'items'");
}
catch (JspException expected) {
String message = expected.getMessage();
assertTrue(message.contains("items"));
assertTrue(message.contains("org.springframework.tests.sample.beans.TestBean"));
}
assertThatExceptionOfType(JspException.class).as("use a non-Collection typed value as the value of 'items'").isThrownBy(
this.tag::doStartTag)
.withMessageContaining("items")
.withMessageContaining("org.springframework.tests.sample.beans.TestBean");
}
@Test

View File

@@ -23,8 +23,8 @@ import org.springframework.mock.web.test.MockHttpServletResponse;
import org.springframework.mock.web.test.MockServletContext;
import org.springframework.web.servlet.ThemeResolver;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
* @author Jean-Pierre Pawlak
@@ -47,8 +47,7 @@ public class ThemeResolverTests {
// set new theme name
try {
themeResolver.setThemeName(request, response, TEST_THEME_NAME);
if (!shouldSet)
fail("should not be able to set Theme name");
assertThat(shouldSet).as("able to set theme name").isTrue();
// check new theme namelocale
themeName = themeResolver.resolveThemeName(request);
assertEquals(TEST_THEME_NAME, themeName);
@@ -57,8 +56,7 @@ public class ThemeResolverTests {
assertEquals(themeName, defaultName);
}
catch (UnsupportedOperationException ex) {
if (shouldSet)
fail("should be able to set Theme name");
assertThat(shouldSet).as("able to set theme name").isFalse();
}
}

View File

@@ -33,9 +33,9 @@ import org.springframework.mock.web.test.MockServletContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.View;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@@ -239,36 +239,21 @@ public class BaseViewTests {
@Test
public void attributeCSVParsingInvalid() {
AbstractView v = new ConcreteView();
try {
// No equals
v.setAttributesCSV("fweoiruiu");
fail();
}
catch (IllegalArgumentException ex) {
}
// No equals
assertThatIllegalArgumentException().isThrownBy(() ->
v.setAttributesCSV("fweoiruiu"));
try {
// No value
v.setAttributesCSV("fweoiruiu=");
fail();
}
catch (IllegalArgumentException ex) {
}
// No value
assertThatIllegalArgumentException().isThrownBy(() ->
v.setAttributesCSV("fweoiruiu="));
try {
// No closing ]
v.setAttributesCSV("fweoiruiu=[");
fail();
}
catch (IllegalArgumentException ex) {
}
try {
// Second one is bogus
v.setAttributesCSV("fweoiruiu=[de],=");
fail();
}
catch (IllegalArgumentException ex) {
}
// No closing ]
assertThatIllegalArgumentException().isThrownBy(() ->
v.setAttributesCSV("fweoiruiu=["));
// Second one is bogus
assertThatIllegalArgumentException().isThrownBy(() ->
v.setAttributesCSV("fweoiruiu=[de],="));
}
@Test

View File

@@ -30,6 +30,7 @@ import org.springframework.mock.web.test.MockServletContext;
import org.springframework.web.servlet.View;
import org.springframework.web.util.WebUtils;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@@ -62,9 +63,10 @@ public class InternalResourceViewTests {
/**
* If the url property isn't supplied, view initialization should fail.
*/
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsNullUrl() throws Exception {
view.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(
view::afterPropertiesSet);
}
@Test

View File

@@ -42,6 +42,7 @@ import org.springframework.web.servlet.support.RequestDataValueProcessorWrapper;
import org.springframework.web.servlet.support.SessionFlashMapManager;
import org.springframework.web.util.WebUtils;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@@ -79,10 +80,11 @@ public class RedirectViewTests {
}
@Test(expected = IllegalArgumentException.class)
@Test
public void noUrlSet() throws Exception {
RedirectView rv = new RedirectView();
rv.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(
rv::afterPropertiesSet);
}
@Test

View File

@@ -30,6 +30,7 @@ import org.springframework.web.servlet.FlashMap;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.support.SessionFlashMapManager;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
public class RedirectViewUriTemplateTests {
@@ -113,9 +114,10 @@ public class RedirectViewUriTemplateTests {
assertEquals(url + "/value1/v1/value2?key3=value3", this.response.getRedirectedUrl());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void uriTemplateNullValue() throws Exception {
new RedirectView("/{foo}").renderMergedOutputModel(new ModelMap(), this.request, this.response);
assertThatIllegalArgumentException().isThrownBy(() ->
new RedirectView("/{foo}").renderMergedOutputModel(new ModelMap(), this.request, this.response));
}
@Test

View File

@@ -32,12 +32,12 @@ import org.springframework.web.context.support.ServletContextResource;
import org.springframework.web.context.support.StaticWebApplicationContext;
import org.springframework.web.servlet.View;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;
/**
@@ -79,20 +79,10 @@ public class ResourceBundleViewResolverTests {
@Test
public void parentsAreAbstract() throws Exception {
try {
rb.resolveViewName("debug.Parent", Locale.ENGLISH);
fail("Should have thrown BeanIsAbstractException");
}
catch (BeanIsAbstractException ex) {
// expected
}
try {
rb.resolveViewName("testParent", Locale.ENGLISH);
fail("Should have thrown BeanIsAbstractException");
}
catch (BeanIsAbstractException ex) {
// expected
}
assertThatExceptionOfType(BeanIsAbstractException.class).isThrownBy(() ->
rb.resolveViewName("debug.Parent", Locale.ENGLISH));
assertThatExceptionOfType(BeanIsAbstractException.class).isThrownBy(() ->
rb.resolveViewName("testParent", Locale.ENGLISH));
}
@Test
@@ -158,10 +148,11 @@ public class ResourceBundleViewResolverTests {
assertEquals("test should have been initialized once, not ", 1, tv.initCount);
}
@Test(expected = MissingResourceException.class)
@Test
public void noSuchBasename() throws Exception {
rb.setBasename("weoriwoierqupowiuer");
rb.resolveViewName("debugView", Locale.ENGLISH);
assertThatExceptionOfType(MissingResourceException.class).isThrownBy(() ->
rb.resolveViewName("debugView", Locale.ENGLISH));
}

View File

@@ -36,7 +36,6 @@ import org.junit.Test;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.context.ApplicationContextException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.mock.web.test.MockHttpServletRequest;
@@ -53,11 +52,12 @@ import org.springframework.web.servlet.i18n.FixedLocaleResolver;
import org.springframework.web.servlet.support.RequestContext;
import org.springframework.web.servlet.theme.FixedThemeResolver;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Juergen Hoeller
@@ -437,14 +437,9 @@ public class ViewResolverTests {
wac.setServletContext(new MockServletContext());
wac.refresh();
XmlViewResolver vr = new XmlViewResolver();
try {
vr.setApplicationContext(wac);
vr.afterPropertiesSet();
fail("Should have thrown BeanDefinitionStoreException");
}
catch (BeanDefinitionStoreException ex) {
// expected
}
vr.setApplicationContext(wac);
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(
vr::afterPropertiesSet);
}
@Test
@@ -460,19 +455,9 @@ public class ViewResolverTests {
wac.refresh();
XmlViewResolver vr = new XmlViewResolver();
vr.setCache(false);
try {
vr.setApplicationContext(wac);
}
catch (ApplicationContextException ex) {
fail("Should not have thrown ApplicationContextException: " + ex.getMessage());
}
try {
vr.resolveViewName("example1", Locale.getDefault());
fail("Should have thrown BeanDefinitionStoreException");
}
catch (BeanDefinitionStoreException ex) {
// expected
}
vr.setApplicationContext(wac);
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() ->
vr.resolveViewName("example1", Locale.getDefault()));
}
@Test
@@ -486,16 +471,12 @@ public class ViewResolverTests {
View view = vr.resolveViewName("example1", Locale.getDefault());
View cached = vr.resolveViewName("example1", Locale.getDefault());
if (view != cached) {
fail("Caching doesn't work");
}
assertThat(cached).isSameAs(view);
vr.removeFromCache("example1", Locale.getDefault());
cached = vr.resolveViewName("example1", Locale.getDefault());
if (view == cached) {
// the chance of having the same reference (hashCode) twice if negligible).
fail("View wasn't removed from cache");
}
// the chance of having the same reference (hashCode) twice is negligible.
assertThat(cached).as("removed from cache").isNotSameAs(view);
}
@Test

View File

@@ -16,7 +16,6 @@
package org.springframework.web.servlet.view.freemarker;
import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;
@@ -35,6 +34,7 @@ import org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.ui.freemarker.SpringTemplateLoader;
import static org.assertj.core.api.Assertions.assertThatIOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertEquals;
@@ -46,14 +46,15 @@ import static org.junit.Assert.assertTrue;
*/
public class FreeMarkerConfigurerTests {
@Test(expected = IOException.class)
@Test
public void freeMarkerConfigurationFactoryBeanWithConfigLocation() throws Exception {
FreeMarkerConfigurationFactoryBean fcfb = new FreeMarkerConfigurationFactoryBean();
fcfb.setConfigLocation(new FileSystemResource("myprops.properties"));
Properties props = new Properties();
props.setProperty("myprop", "/mydir");
fcfb.setFreemarkerSettings(props);
fcfb.afterPropertiesSet();
assertThatIOException().isThrownBy(
fcfb::afterPropertiesSet);
}
@Test

View File

@@ -16,7 +16,6 @@
package org.springframework.web.servlet.view.groovy;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
@@ -32,11 +31,11 @@ import org.junit.Test;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.StaticApplicationContext;
import static org.assertj.core.api.Assertions.assertThatIOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
/**
* Unit tests for
@@ -165,11 +164,11 @@ public class GroovyMarkupConfigurerTests {
assertThat(url.getPath(), Matchers.containsString("i18n.tpl"));
}
@Test(expected = IOException.class)
@Test
public void failMissingTemplate() throws Exception {
LocaleContextHolder.setLocale(Locale.US);
this.configurer.resolveTemplate(getClass().getClassLoader(), TEMPLATE_PREFIX + "missing.tpl");
fail();
assertThatIOException().isThrownBy(() ->
this.configurer.resolveTemplate(getClass().getClassLoader(), TEMPLATE_PREFIX + "missing.tpl"));
}
}

View File

@@ -41,12 +41,12 @@ import org.springframework.mock.web.test.MockHttpServletResponse;
import org.springframework.mock.web.test.MockServletContext;
import org.springframework.web.context.WebApplicationContext;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@@ -77,13 +77,9 @@ public class GroovyMarkupViewTests {
.willReturn(new HashMap<>());
view.setUrl("sampleView");
try {
view.setApplicationContext(this.webAppContext);
fail();
}
catch (ApplicationContextException ex) {
assertTrue(ex.getMessage().contains("GroovyMarkupConfig"));
}
assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() ->
view.setApplicationContext(this.webAppContext))
.withMessageContaining("GroovyMarkupConfig");
}
@Test

View File

@@ -45,12 +45,12 @@ import org.springframework.mock.web.test.MockHttpServletResponse;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.View;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
/**
@@ -203,16 +203,14 @@ public class MappingJackson2XmlViewTests {
validateResult();
}
@Test(expected = IllegalStateException.class)
@Test
public void renderModelWithMultipleKeys() throws Exception {
Map<String, Object> model = new TreeMap<>();
model.put("foo", "foo");
model.put("bar", "bar");
view.render(model, request, response);
fail();
assertThatIllegalStateException().isThrownBy(() ->
view.render(model, request, response));
}
@Test

View File

@@ -32,8 +32,8 @@ import org.springframework.oxm.Marshaller;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.BDDMockito.given;
@@ -122,13 +122,9 @@ public class MarshallingViewTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
try {
view.render(model, request, response);
fail("IllegalStateException expected");
}
catch (IllegalStateException ex) {
// expected
}
assertThatIllegalStateException().isThrownBy(() ->
view.render(model, request, response));
assertEquals("Invalid content length", 0, response.getContentLength());
}
@@ -141,13 +137,9 @@ public class MarshallingViewTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
try {
view.render(model, request, response);
fail("IllegalStateException expected");
}
catch (IllegalStateException ex) {
// expected
}
assertThatIllegalStateException().isThrownBy(() ->
view.render(model, request, response));
assertEquals("Invalid content length", 0, response.getContentLength());
}
@@ -164,13 +156,8 @@ public class MarshallingViewTests {
given(marshallerMock.supports(Object.class)).willReturn(false);
try {
view.render(model, request, response);
fail("IllegalStateException expected");
}
catch (IllegalStateException ex) {
// expected
}
assertThatIllegalStateException().isThrownBy(() ->
view.render(model, request, response));
}
@Test
@@ -223,13 +210,8 @@ public class MarshallingViewTests {
given(marshallerMock.supports(Object.class)).willReturn(false);
try {
view.render(model, request, response);
fail("IllegalStateException expected");
}
catch (IllegalStateException ex) {
// expected
}
assertThatIllegalStateException().isThrownBy(() ->
view.render(model, request, response));
}
}

View File

@@ -42,6 +42,7 @@ import org.springframework.mock.web.test.MockHttpServletResponse;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonMap;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@@ -59,16 +60,18 @@ public class XsltViewTests {
private final MockHttpServletResponse response = new MockHttpServletResponse();
@Test(expected = IllegalArgumentException.class)
@Test
public void withNoSource() throws Exception {
final XsltView view = getXsltView(HTML_OUTPUT);
view.render(emptyMap(), request, response);
assertThatIllegalArgumentException().isThrownBy(() ->
view.render(emptyMap(), request, response));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void withoutUrl() throws Exception {
final XsltView view = new XsltView();
view.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(
view::afterPropertiesSet);
}
@Test