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

@@ -28,11 +28,11 @@ import javax.servlet.ServletResponse;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@@ -53,26 +53,30 @@ public class MockFilterChainTests {
this.response = new MockHttpServletResponse();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorNullServlet() {
new MockFilterChain((Servlet) null);
assertThatIllegalArgumentException().isThrownBy(() ->
new MockFilterChain((Servlet) null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorNullFilter() {
new MockFilterChain(mock(Servlet.class), (Filter) null);
assertThatIllegalArgumentException().isThrownBy(() ->
new MockFilterChain(mock(Servlet.class), (Filter) null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void doFilterNullRequest() throws Exception {
MockFilterChain chain = new MockFilterChain();
chain.doFilter(null, this.response);
assertThatIllegalArgumentException().isThrownBy(() ->
chain.doFilter(null, this.response));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void doFilterNullResponse() throws Exception {
MockFilterChain chain = new MockFilterChain();
chain.doFilter(this.request, null);
assertThatIllegalArgumentException().isThrownBy(() ->
chain.doFilter(this.request, null));
}
@Test
@@ -83,13 +87,9 @@ public class MockFilterChainTests {
assertThat(chain.getRequest(), is(request));
assertThat(chain.getResponse(), is(response));
try {
chain.doFilter(this.request, this.response);
fail("Expected Exception");
}
catch (IllegalStateException ex) {
assertEquals("This FilterChain has already been called!", ex.getMessage());
}
assertThatIllegalStateException().isThrownBy(() ->
chain.doFilter(this.request, this.response))
.withMessage("This FilterChain has already been called!");
}
@Test
@@ -98,13 +98,9 @@ public class MockFilterChainTests {
MockFilterChain chain = new MockFilterChain(servlet);
chain.doFilter(this.request, this.response);
verify(servlet).service(this.request, this.response);
try {
chain.doFilter(this.request, this.response);
fail("Expected Exception");
}
catch (IllegalStateException ex) {
assertEquals("This FilterChain has already been called!", ex.getMessage());
}
assertThatIllegalStateException().isThrownBy(() ->
chain.doFilter(this.request, this.response))
.withMessage("This FilterChain has already been called!");
}
@Test
@@ -122,13 +118,9 @@ public class MockFilterChainTests {
verify(servlet).service(this.request, this.response);
try {
chain.doFilter(this.request, this.response);
fail("Expected Exception");
}
catch (IllegalStateException ex) {
assertEquals("This FilterChain has already been called!", ex.getMessage());
}
assertThatIllegalStateException().isThrownBy(() ->
chain.doFilter(this.request, this.response))
.withMessage("This FilterChain has already been called!");
}

View File

@@ -35,6 +35,7 @@ import org.springframework.http.HttpHeaders;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StreamUtils;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -314,14 +315,16 @@ public class MockHttpServletRequestTests {
}
}
@Test(expected = IllegalArgumentException.class)
@Test
public void setPreferredLocalesWithNullList() {
request.setPreferredLocales(null);
assertThatIllegalArgumentException().isThrownBy(() ->
request.setPreferredLocales(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void setPreferredLocalesWithEmptyList() {
request.setPreferredLocales(new ArrayList<>());
assertThatIllegalArgumentException().isThrownBy(() ->
request.setPreferredLocales(new ArrayList<>()));
}
@Test
@@ -556,10 +559,11 @@ public class MockHttpServletRequestTests {
assertEquals(1437472800000L, request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void httpHeaderFormattedDateError() {
request.addHeader(HttpHeaders.IF_MODIFIED_SINCE, "This is not a date");
request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);
assertThatIllegalArgumentException().isThrownBy(() ->
request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE));
}
private void assertEqualEnumerations(Enumeration<?> enum1, Enumeration<?> enum2) {

View File

@@ -27,6 +27,7 @@ import org.junit.Test;
import org.springframework.http.HttpHeaders;
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.assertNotNull;
@@ -298,11 +299,12 @@ public class MockHttpServletResponseTests {
assertEquals(time, response.getDateHeader("Last-Modified"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void getInvalidDateHeader() {
response.setHeader("Last-Modified", "invalid");
assertEquals("invalid", response.getHeader("Last-Modified"));
response.getDateHeader("Last-Modified");
assertThatIllegalArgumentException().isThrownBy(() ->
response.getDateHeader("Last-Modified"));
}
@Test // SPR-16160

View File

@@ -22,6 +22,7 @@ import javax.servlet.http.HttpSessionBindingListener;
import org.junit.Test;
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.assertTrue;
@@ -45,109 +46,88 @@ public class MockHttpSessionTests {
assertTrue(session.isInvalid());
}
@Test(expected = IllegalStateException.class)
@Test
public void invalidateTwice() {
session.invalidate();
session.invalidate();
assertThatIllegalStateException().isThrownBy(
session::invalidate);
}
/**
* @since 4.0
*/
@Test(expected = IllegalStateException.class)
@Test
public void getCreationTimeOnInvalidatedSession() {
session.invalidate();
session.getCreationTime();
assertThatIllegalStateException().isThrownBy(
session::getCreationTime);
}
/**
* @since 4.0
*/
@Test(expected = IllegalStateException.class)
@Test
public void getLastAccessedTimeOnInvalidatedSession() {
session.invalidate();
session.getLastAccessedTime();
assertThatIllegalStateException().isThrownBy(
session::getLastAccessedTime);
}
/**
* @since 4.0
*/
@Test(expected = IllegalStateException.class)
@Test
public void getAttributeOnInvalidatedSession() {
session.invalidate();
session.getAttribute("foo");
assertThatIllegalStateException().isThrownBy(() ->
session.getAttribute("foo"));
}
/**
* @since 4.0
*/
@Test(expected = IllegalStateException.class)
@Test
public void getAttributeNamesOnInvalidatedSession() {
session.invalidate();
session.getAttributeNames();
assertThatIllegalStateException().isThrownBy(
session::getAttributeNames);
}
/**
* @since 4.0
*/
@Test(expected = IllegalStateException.class)
@Test
public void getValueOnInvalidatedSession() {
session.invalidate();
session.getValue("foo");
assertThatIllegalStateException().isThrownBy(() ->
session.getValue("foo"));
}
/**
* @since 4.0
*/
@Test(expected = IllegalStateException.class)
@Test
public void getValueNamesOnInvalidatedSession() {
session.invalidate();
session.getValueNames();
assertThatIllegalStateException().isThrownBy(
session::getValueNames);
}
/**
* @since 4.0
*/
@Test(expected = IllegalStateException.class)
@Test
public void setAttributeOnInvalidatedSession() {
session.invalidate();
session.setAttribute("name", "value");
assertThatIllegalStateException().isThrownBy(() ->
session.setAttribute("name", "value"));
}
/**
* @since 4.0
*/
@Test(expected = IllegalStateException.class)
@Test
public void putValueOnInvalidatedSession() {
session.invalidate();
session.putValue("name", "value");
assertThatIllegalStateException().isThrownBy(() ->
session.putValue("name", "value"));
}
/**
* @since 4.0
*/
@Test(expected = IllegalStateException.class)
@Test
public void removeAttributeOnInvalidatedSession() {
session.invalidate();
session.removeAttribute("name");
assertThatIllegalStateException().isThrownBy(() ->
session.removeAttribute("name"));
}
/**
* @since 4.0
*/
@Test(expected = IllegalStateException.class)
@Test
public void removeValueOnInvalidatedSession() {
session.invalidate();
session.removeValue("name");
assertThatIllegalStateException().isThrownBy(() ->
session.removeValue("name"));
}
/**
* @since 4.0
*/
@Test(expected = IllegalStateException.class)
@Test
public void isNewOnInvalidatedSession() {
session.invalidate();
session.isNew();
assertThatIllegalStateException().isThrownBy(
session::isNew);
}
@Test

View File

@@ -20,6 +20,8 @@ import java.lang.reflect.Method;
import org.junit.Test;
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.fail;
@@ -55,18 +57,17 @@ public class TestContextManagerSuppressedExceptionsTests {
TestContextManager testContextManager = new TestContextManager(testClass);
assertEquals("Registered TestExecutionListeners", 2, testContextManager.getTestExecutionListeners().size());
try {
Method testMethod = getClass().getMethod("toString");
callback.invoke(testContextManager, testClass, testMethod);
fail("should have thrown an AssertionError");
}
catch (AssertionError err) {
// 'after' callbacks are reversed, so 2 comes before 1.
assertEquals(useCase + "-2", err.getMessage());
Throwable[] suppressed = err.getSuppressed();
assertEquals(1, suppressed.length);
assertEquals(useCase + "-1", suppressed[0].getMessage());
}
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> {
Method testMethod = getClass().getMethod("toString");
callback.invoke(testContextManager, testClass, testMethod);
fail("should have thrown an AssertionError");
}).satisfies(ex -> {
// 'after' callbacks are reversed, so 2 comes before 1.
assertThat(ex.getMessage()).isEqualTo(useCase + "-2");
Throwable[] suppressed = ex.getSuppressed();
assertThat(suppressed).hasSize(1);
assertThat(suppressed[0].getMessage()).isEqualTo(useCase + "-1");
});
}

View File

@@ -35,6 +35,7 @@ import org.springframework.test.context.web.ServletTestExecutionListener;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.springframework.test.context.TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS;
@@ -164,9 +165,10 @@ public class TestExecutionListenersTests {
assertNumRegisteredListeners(MetaNonInheritedListenersWithOverridesTestCase.class, 8);
}
@Test(expected = AnnotationConfigurationException.class)
@Test
public void listenersAndValueAttributesDeclared() {
new TestContextManager(DuplicateListenersConfigTestCase.class);
assertThatExceptionOfType(AnnotationConfigurationException.class).isThrownBy(() ->
new TestContextManager(DuplicateListenersConfigTestCase.class));
}

View File

@@ -28,6 +28,7 @@ import org.springframework.test.util.ReflectionTestUtils;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -55,14 +56,16 @@ public class LruContextCacheTests {
private final ConfigurableApplicationContext bazContext = mock(ConfigurableApplicationContext.class);
@Test(expected = IllegalArgumentException.class)
@Test
public void maxCacheSizeNegativeOne() {
new DefaultContextCache(-1);
assertThatIllegalArgumentException().isThrownBy(() ->
new DefaultContextCache(-1));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void maxCacheSizeZero() {
new DefaultContextCache(0);
assertThatIllegalArgumentException().isThrownBy(() ->
new DefaultContextCache(0));
}
@Test

View File

@@ -29,8 +29,8 @@ import org.springframework.test.context.jdbc.Sql.ExecutionPhase;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.transaction.AfterTransaction;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD;
/**
@@ -52,13 +52,9 @@ public class TransactionalAfterTestMethodSqlScriptsTests extends AbstractTransac
@AfterTransaction
public void afterTransaction() {
if ("test01".equals(testName.getMethodName())) {
try {
assertNumUsers(99);
fail("Should throw a BadSqlGrammarException after test01, assuming 'drop-schema.sql' was executed");
}
catch (BadSqlGrammarException e) {
/* expected */
}
// Should throw a BadSqlGrammarException after test01, assuming 'drop-schema.sql' was executed
assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(() ->
assertNumUsers(99));
}
}

View File

@@ -25,6 +25,7 @@ import org.junit.runners.model.FrameworkMethod;
import org.springframework.test.annotation.Timed;
import org.springframework.test.context.TestContextManager;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
/**
@@ -36,7 +37,7 @@ import static org.junit.Assert.assertEquals;
*/
public class SpringJUnit4ClassRunnerTests {
@Test(expected = Exception.class)
@Test
public void checkThatExceptionsAreNotSilentlySwallowed() throws Exception {
SpringJUnit4ClassRunner runner = new SpringJUnit4ClassRunner(getClass()) {
@@ -52,7 +53,8 @@ public class SpringJUnit4ClassRunnerTests {
};
}
};
runner.createTest();
assertThatExceptionOfType(Exception.class).isThrownBy(
runner::createTest);
}
@Test

View File

@@ -32,6 +32,7 @@ import org.springframework.test.context.junit4.orm.domain.Person;
import org.springframework.test.context.junit4.orm.service.PersonService;
import org.springframework.transaction.annotation.Transactional;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.springframework.test.transaction.TransactionTestUtils.assertInTransaction;
@@ -98,9 +99,10 @@ public class HibernateSessionFlushingTests extends AbstractTransactionalJUnit4Sp
assertNotNull("Juergen's ID should have been set", juergen.getId());
}
@Test(expected = ConstraintViolationException.class)
@Test
public void saveJuergenWithNullDriversLicense() {
personService.save(new Person(JUERGEN));
assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(() ->
personService.save(new Person(JUERGEN)));
}
@Test
@@ -111,17 +113,19 @@ public class HibernateSessionFlushingTests extends AbstractTransactionalJUnit4Sp
// finally flushed (i.e., in production code)
}
@Test(expected = ConstraintViolationException.class)
@Test
public void updateSamWithNullDriversLicenseWithSessionFlush() throws Throwable {
updateSamWithNullDriversLicense();
// Manual flush is required to avoid false positive in test
try {
sessionFactory.getCurrentSession().flush();
}
catch (PersistenceException ex) {
// Wrapped in Hibernate 5.2, with the constraint violation as cause
throw ex.getCause();
}
assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(() -> {
// Manual flush is required to avoid false positive in test
try {
sessionFactory.getCurrentSession().flush();
}
catch (PersistenceException ex) {
// Wrapped in Hibernate 5.2, with the constraint violation as cause
throw ex.getCause();
}
});
}
private void updateSamWithNullDriversLicense() {

View File

@@ -31,6 +31,8 @@ import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ActiveProfilesResolver;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertArrayEquals;
import static org.springframework.test.context.support.ActiveProfilesUtils.resolveActiveProfiles;
@@ -189,17 +191,19 @@ public class ActiveProfilesUtilsTests extends AbstractContextConfigurationUtilsT
/**
* @since 4.0
*/
@Test(expected = AnnotationConfigurationException.class)
@Test
public void resolveActiveProfilesWithConflictingProfilesAndValue() {
resolveActiveProfiles(ConflictingProfilesAndValueTestCase.class);
assertThatExceptionOfType(AnnotationConfigurationException.class).isThrownBy(() ->
resolveActiveProfiles(ConflictingProfilesAndValueTestCase.class));
}
/**
* @since 4.0
*/
@Test(expected = IllegalStateException.class)
@Test
public void resolveActiveProfilesWithResolverWithoutDefaultConstructor() {
resolveActiveProfiles(NoDefaultConstructorActiveProfilesResolverTestCase.class);
assertThatIllegalStateException().isThrownBy(() ->
resolveActiveProfiles(NoDefaultConstructorActiveProfilesResolverTestCase.class));
}
/**

View File

@@ -25,6 +25,7 @@ import org.junit.Test;
import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@@ -38,9 +39,10 @@ import static org.springframework.test.context.support.AnnotationConfigContextLo
*/
public class AnnotationConfigContextLoaderUtilsTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void detectDefaultConfigurationClassesWithNullDeclaringClass() {
detectDefaultConfigurationClasses(null);
assertThatIllegalArgumentException().isThrownBy(() ->
detectDefaultConfigurationClasses(null));
}
@Test

View File

@@ -31,6 +31,7 @@ import org.springframework.test.context.ContextConfigurationAttributes;
import org.springframework.test.context.ContextHierarchy;
import org.springframework.test.context.ContextLoader;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.CoreMatchers.is;
@@ -38,7 +39,6 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.springframework.test.context.support.ContextLoaderUtils.GENERATED_CONTEXT_HIERARCHY_LEVEL_PREFIX;
import static org.springframework.test.context.support.ContextLoaderUtils.buildContextHierarchyMap;
import static org.springframework.test.context.support.ContextLoaderUtils.resolveContextHierarchyAttributes;
@@ -57,14 +57,16 @@ public class ContextLoaderUtilsContextHierarchyTests extends AbstractContextConf
// }
}
@Test(expected = IllegalStateException.class)
@Test
public void resolveContextHierarchyAttributesForSingleTestClassWithContextConfigurationAndContextHierarchy() {
resolveContextHierarchyAttributes(SingleTestClassWithContextConfigurationAndContextHierarchy.class);
assertThatIllegalStateException().isThrownBy(() ->
resolveContextHierarchyAttributes(SingleTestClassWithContextConfigurationAndContextHierarchy.class));
}
@Test(expected = IllegalStateException.class)
@Test
public void resolveContextHierarchyAttributesForSingleTestClassWithContextConfigurationAndContextHierarchyOnSingleMetaAnnotation() {
resolveContextHierarchyAttributes(SingleTestClassWithContextConfigurationAndContextHierarchyOnSingleMetaAnnotation.class);
assertThatIllegalStateException().isThrownBy(() ->
resolveContextHierarchyAttributes(SingleTestClassWithContextConfigurationAndContextHierarchyOnSingleMetaAnnotation.class));
}
@Test
@@ -319,16 +321,10 @@ public class ContextLoaderUtilsContextHierarchyTests extends AbstractContextConf
}
private void assertContextConfigEntriesAreNotUnique(Class<?> testClass) {
try {
buildContextHierarchyMap(testClass);
fail("Should throw an IllegalStateException");
}
catch (IllegalStateException e) {
String msg = String.format(
"The @ContextConfiguration elements configured via @ContextHierarchy in test class [%s] and its superclasses must define unique contexts per hierarchy level.",
testClass.getName());
assertEquals(msg, e.getMessage());
}
assertThatIllegalStateException().isThrownBy(() ->
buildContextHierarchyMap(testClass))
.withMessage(String.format(
"The @ContextConfiguration elements configured via @ContextHierarchy in test class [%s] and its superclasses must define unique contexts per hierarchy level.", testClass.getName()));
}
@Test

View File

@@ -27,6 +27,8 @@ import org.springframework.test.context.ContextLoader;
import org.springframework.test.context.MergedContextConfiguration;
import org.springframework.util.ObjectUtils;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
@@ -103,10 +105,10 @@ public class DelegatingSmartContextLoaderTests {
// --- SmartContextLoader - loadContext() ----------------------------------
@Test(expected = IllegalArgumentException.class)
@Test
public void loadContextWithNullConfig() throws Exception {
MergedContextConfiguration mergedConfig = null;
loader.loadContext(mergedConfig);
assertThatIllegalArgumentException().isThrownBy(() ->
loader.loadContext((MergedContextConfiguration) null));
}
@Test
@@ -160,14 +162,16 @@ public class DelegatingSmartContextLoaderTests {
// --- ContextLoader -------------------------------------------------------
@Test(expected = UnsupportedOperationException.class)
@Test
public void processLocations() {
loader.processLocations(getClass(), EMPTY_STRING_ARRAY);
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
loader.processLocations(getClass(), EMPTY_STRING_ARRAY));
}
@Test(expected = UnsupportedOperationException.class)
@Test
public void loadContextFromLocations() throws Exception {
loader.loadContext(EMPTY_STRING_ARRAY);
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
loader.loadContext(EMPTY_STRING_ARRAY));
}

View File

@@ -34,10 +34,10 @@ import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.SimpleTransactionStatus;
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.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.springframework.transaction.annotation.Propagation.NOT_SUPPORTED;
@@ -86,14 +86,9 @@ public class TransactionalTestExecutionListenerTests {
assertFalse("callback should not have been invoked", instance.invoked());
TransactionContextHolder.removeCurrentTransactionContext();
try {
listener.beforeTestMethod(testContext);
fail("Should have thrown an IllegalStateException");
}
catch (IllegalStateException e) {
assertTrue(e.getMessage().startsWith(
"Failed to retrieve PlatformTransactionManager for @Transactional test"));
}
assertThatIllegalStateException().isThrownBy(() ->
listener.beforeTestMethod(testContext))
.withMessageStartingWith("Failed to retrieve PlatformTransactionManager for @Transactional test");
}
@Test

View File

@@ -21,6 +21,7 @@ import org.junit.Test;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.AopUtils;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertNotSame;
@@ -40,9 +41,10 @@ public class AopTestUtilsTests {
private final FooImpl foo = new FooImpl();
@Test(expected = IllegalArgumentException.class)
@Test
public void getTargetObjectForNull() {
getTargetObject(null);
assertThatIllegalArgumentException().isThrownBy(() ->
getTargetObject(null));
}
@Test
@@ -75,9 +77,10 @@ public class AopTestUtilsTests {
assertNotSame(foo, target);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void getUltimateTargetObjectForNull() {
getUltimateTargetObject(null);
assertThatIllegalArgumentException().isThrownBy(() ->
getUltimateTargetObject(null));
}
@Test

View File

@@ -192,19 +192,22 @@ public class ReflectionTestUtilsTests {
assertNull("'favorite number' (package field)", person.getFavoriteNumber());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void setFieldWithNullValueForPrimitiveLong() throws Exception {
setField(person, "id", null, long.class);
assertThatIllegalArgumentException().isThrownBy(() ->
setField(person, "id", null, long.class));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void setFieldWithNullValueForPrimitiveInt() throws Exception {
setField(person, "age", null, int.class);
assertThatIllegalArgumentException().isThrownBy(() ->
setField(person, "age", null, int.class));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void setFieldWithNullValueForPrimitiveBoolean() throws Exception {
setField(person, "likesPets", null, boolean.class);
assertThatIllegalArgumentException().isThrownBy(() ->
setField(person, "likesPets", null, boolean.class));
}
@Test
@@ -307,19 +310,22 @@ public class ReflectionTestUtilsTests {
assertNull("'favorite number' (protected method for a Number)", person.getFavoriteNumber());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void invokeSetterMethodWithNullValueForPrimitiveLong() throws Exception {
invokeSetterMethod(person, "id", null, long.class);
assertThatIllegalArgumentException().isThrownBy(() ->
invokeSetterMethod(person, "id", null, long.class));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void invokeSetterMethodWithNullValueForPrimitiveInt() throws Exception {
invokeSetterMethod(person, "age", null, int.class);
assertThatIllegalArgumentException().isThrownBy(() ->
invokeSetterMethod(person, "age", null, int.class));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void invokeSetterMethodWithNullValueForPrimitiveBoolean() throws Exception {
invokeSetterMethod(person, "likesPets", null, boolean.class);
assertThatIllegalArgumentException().isThrownBy(() ->
invokeSetterMethod(person, "likesPets", null, boolean.class));
}
@Test

View File

@@ -23,7 +23,7 @@ import org.junit.Test;
import org.springframework.test.web.client.MockRestServiceServer.MockRestServiceServerBuilder;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.fail;
import static org.springframework.http.HttpMethod.POST;
import static org.springframework.test.web.client.ExpectedCount.once;
@@ -63,14 +63,15 @@ public class MockRestServiceServerTests {
server.verify();
}
@Test(expected = AssertionError.class)
@Test
public void exactExpectOrder() {
MockRestServiceServer server = MockRestServiceServer.bindTo(this.restTemplate)
.ignoreExpectOrder(false).build();
server.expect(requestTo("/foo")).andRespond(withSuccess());
server.expect(requestTo("/bar")).andRespond(withSuccess());
this.restTemplate.getForObject("/bar", Void.class);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.restTemplate.getForObject("/bar", Void.class));
}
@Test
@@ -143,21 +144,13 @@ public class MockRestServiceServerTests {
server.expect(once(), requestTo("/remoteurl")).andRespond(withSuccess());
this.restTemplate.postForEntity("/remoteurl", null, String.class);
try {
this.restTemplate.postForEntity("/remoteurl", null, String.class);
fail("Expected assertion error");
}
catch (AssertionError error) {
assertThat(error.getMessage()).startsWith("No further requests expected");
}
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.restTemplate.postForEntity("/remoteurl", null, String.class))
.withMessageStartingWith("No further requests expected");
try {
server.verify();
fail("Expected verify failure");
}
catch (AssertionError error) {
assertThat(error.getMessage()).startsWith("Some requests did not execute successfully");
}
assertThatExceptionOfType(AssertionError.class).isThrownBy(
server::verify)
.withMessageStartingWith("Some requests did not execute successfully");
}
}

View File

@@ -26,6 +26,7 @@ import org.springframework.mock.http.client.MockClientHttpRequest;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.Matchers.hasXPath;
/**
@@ -52,18 +53,20 @@ public class ContentRequestMatchersTests {
MockRestRequestMatchers.content().contentType(MediaType.APPLICATION_JSON).match(this.request);
}
@Test(expected = AssertionError.class)
@Test
public void testContentTypeNoMatch1() throws Exception {
this.request.getHeaders().setContentType(MediaType.APPLICATION_JSON);
MockRestRequestMatchers.content().contentType("application/xml").match(this.request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
MockRestRequestMatchers.content().contentType("application/xml").match(this.request));
}
@Test(expected = AssertionError.class)
@Test
public void testContentTypeNoMatch2() throws Exception {
this.request.getHeaders().setContentType(MediaType.APPLICATION_JSON);
MockRestRequestMatchers.content().contentType(MediaType.APPLICATION_ATOM_XML).match(this.request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
MockRestRequestMatchers.content().contentType(MediaType.APPLICATION_ATOM_XML).match(this.request));
}
@Test
@@ -73,11 +76,12 @@ public class ContentRequestMatchersTests {
MockRestRequestMatchers.content().string("test").match(this.request);
}
@Test(expected = AssertionError.class)
@Test
public void testStringNoMatch() throws Exception {
this.request.getBody().write("test".getBytes());
MockRestRequestMatchers.content().string("Test").match(this.request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
MockRestRequestMatchers.content().string("Test").match(this.request));
}
@Test
@@ -88,11 +92,12 @@ public class ContentRequestMatchersTests {
MockRestRequestMatchers.content().bytes(content).match(this.request);
}
@Test(expected = AssertionError.class)
@Test
public void testBytesNoMatch() throws Exception {
this.request.getBody().write("test".getBytes());
MockRestRequestMatchers.content().bytes("Test".getBytes()).match(this.request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
MockRestRequestMatchers.content().bytes("Test".getBytes()).match(this.request));
}
@Test
@@ -119,11 +124,12 @@ public class ContentRequestMatchersTests {
MockRestRequestMatchers.content().xml(content).match(this.request);
}
@Test(expected = AssertionError.class)
@Test
public void testXmlNoMatch() throws Exception {
this.request.getBody().write("<foo>11</foo>".getBytes());
MockRestRequestMatchers.content().xml("<foo>22</foo>").match(this.request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
MockRestRequestMatchers.content().xml("<foo>22</foo>").match(this.request));
}
@Test
@@ -134,12 +140,12 @@ public class ContentRequestMatchersTests {
MockRestRequestMatchers.content().node(hasXPath("/foo/bar")).match(this.request);
}
@Test(expected = AssertionError.class)
@Test
public void testNodeMatcherNoMatch() throws Exception {
String content = "<foo><bar>baz</bar></foo>";
this.request.getBody().write(content.getBytes());
MockRestRequestMatchers.content().node(hasXPath("/foo/bar/bar")).match(this.request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
MockRestRequestMatchers.content().node(hasXPath("/foo/bar/bar")).match(this.request));
}
@Test
@@ -164,30 +170,33 @@ public class ContentRequestMatchersTests {
.match(this.request);
}
@Test(expected = AssertionError.class)
@Test
public void testJsonLenientNoMatch() throws Exception {
String content = "{\n \"bar\" : \"foo\" \n}";
this.request.getBody().write(content.getBytes());
MockRestRequestMatchers
.content()
.json("{\n \"foo\" : \"bar\" \n}")
.match(this.request);
MockRestRequestMatchers
.content()
.json("{\n \"foo\" : \"bar\" \n}", false)
.match(this.request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
MockRestRequestMatchers
.content()
.json("{\n \"foo\" : \"bar\" \n}")
.match(this.request));
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
MockRestRequestMatchers
.content()
.json("{\n \"foo\" : \"bar\" \n}", false)
.match(this.request));
}
@Test(expected = AssertionError.class)
@Test
public void testJsonStrictNoMatch() throws Exception {
String content = "{\n \"foo array\":[\"first\",\"second\"] , \"someExtraProperty\": \"which is NOT allowed\" \n}";
this.request.getBody().write(content.getBytes());
MockRestRequestMatchers
.content()
.json("{\n \"foo array\":[\"second\",\"first\"] \n}", true)
.match(this.request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
MockRestRequestMatchers
.content()
.json("{\n \"foo array\":[\"second\",\"first\"] \n}", true)
.match(this.request));
}
}

View File

@@ -22,6 +22,7 @@ import org.junit.Test;
import org.springframework.mock.http.client.MockClientHttpRequest;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.CoreMatchers.equalTo;
/**
@@ -55,9 +56,10 @@ public class JsonPathRequestMatchersTests {
}
@Test(expected = AssertionError.class)
@Test
public void valueWithMismatch() throws Exception {
new JsonPathRequestMatchers("$.str").value("bogus").match(request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathRequestMatchers("$.str").value("bogus").match(request));
}
@Test
@@ -80,9 +82,10 @@ public class JsonPathRequestMatchersTests {
new JsonPathRequestMatchers("$.num").value(equalTo(5.0f), Float.class).match(request);
}
@Test(expected = AssertionError.class)
@Test
public void valueWithMatcherAndMismatch() throws Exception {
new JsonPathRequestMatchers("$.str").value(equalTo("bogus")).match(request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathRequestMatchers("$.str").value(equalTo("bogus")).match(request));
}
@Test
@@ -100,9 +103,10 @@ public class JsonPathRequestMatchersTests {
new JsonPathRequestMatchers("$.emptyMap").exists().match(request);
}
@Test(expected = AssertionError.class)
@Test
public void existsNoMatch() throws Exception {
new JsonPathRequestMatchers("$.bogus").exists().match(request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathRequestMatchers("$.bogus").exists().match(request));
}
@Test
@@ -110,19 +114,22 @@ public class JsonPathRequestMatchersTests {
new JsonPathRequestMatchers("$.bogus").doesNotExist().match(request);
}
@Test(expected = AssertionError.class)
@Test
public void doesNotExistNoMatch() throws Exception {
new JsonPathRequestMatchers("$.str").doesNotExist().match(request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathRequestMatchers("$.str").doesNotExist().match(request));
}
@Test(expected = AssertionError.class)
@Test
public void doesNotExistForAnEmptyArray() throws Exception {
new JsonPathRequestMatchers("$.emptyArray").doesNotExist().match(request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathRequestMatchers("$.emptyArray").doesNotExist().match(request));
}
@Test(expected = AssertionError.class)
@Test
public void doesNotExistForAnEmptyMap() throws Exception {
new JsonPathRequestMatchers("$.emptyMap").doesNotExist().match(request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathRequestMatchers("$.emptyMap").doesNotExist().match(request));
}
@Test
@@ -165,19 +172,22 @@ public class JsonPathRequestMatchersTests {
new JsonPathRequestMatchers("$.colorMap").isNotEmpty().match(request);
}
@Test(expected = AssertionError.class)
@Test
public void isNotEmptyForAnEmptyString() throws Exception {
new JsonPathRequestMatchers("$.emptyString").isNotEmpty().match(request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathRequestMatchers("$.emptyString").isNotEmpty().match(request));
}
@Test(expected = AssertionError.class)
@Test
public void isNotEmptyForAnEmptyArray() throws Exception {
new JsonPathRequestMatchers("$.emptyArray").isNotEmpty().match(request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathRequestMatchers("$.emptyArray").isNotEmpty().match(request));
}
@Test(expected = AssertionError.class)
@Test
public void isNotEmptyForAnEmptyMap() throws Exception {
new JsonPathRequestMatchers("$.emptyMap").isNotEmpty().match(request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathRequestMatchers("$.emptyMap").isNotEmpty().match(request));
}
@Test
@@ -190,9 +200,10 @@ public class JsonPathRequestMatchersTests {
new JsonPathRequestMatchers("$.emptyArray").isArray().match(request);
}
@Test(expected = AssertionError.class)
@Test
public void isArrayNoMatch() throws Exception {
new JsonPathRequestMatchers("$.str").isArray().match(request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathRequestMatchers("$.str").isArray().match(request));
}
@Test
@@ -205,9 +216,10 @@ public class JsonPathRequestMatchersTests {
new JsonPathRequestMatchers("$.emptyMap").isMap().match(request);
}
@Test(expected = AssertionError.class)
@Test
public void isMapNoMatch() throws Exception {
new JsonPathRequestMatchers("$.str").isMap().match(request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathRequestMatchers("$.str").isMap().match(request));
}
@Test
@@ -215,9 +227,10 @@ public class JsonPathRequestMatchersTests {
new JsonPathRequestMatchers("$.bool").isBoolean().match(request);
}
@Test(expected = AssertionError.class)
@Test
public void isBooleanNoMatch() throws Exception {
new JsonPathRequestMatchers("$.str").isBoolean().match(request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathRequestMatchers("$.str").isBoolean().match(request));
}
@Test
@@ -225,9 +238,10 @@ public class JsonPathRequestMatchersTests {
new JsonPathRequestMatchers("$.num").isNumber().match(request);
}
@Test(expected = AssertionError.class)
@Test
public void isNumberNoMatch() throws Exception {
new JsonPathRequestMatchers("$.str").isNumber().match(request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathRequestMatchers("$.str").isNumber().match(request));
}
@Test
@@ -235,9 +249,10 @@ public class JsonPathRequestMatchersTests {
new JsonPathRequestMatchers("$.str").isString().match(request);
}
@Test(expected = AssertionError.class)
@Test
public void isStringNoMatch() throws Exception {
new JsonPathRequestMatchers("$.arr").isString().match(request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathRequestMatchers("$.arr").isString().match(request));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,6 +24,8 @@ import org.junit.Test;
import org.springframework.mock.http.client.MockClientHttpRequest;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Unit tests for {@link XpathRequestMatchers}.
*
@@ -48,9 +50,10 @@ public class XpathRequestMatchersTests {
new XpathRequestMatchers("/foo/bar", null).node(Matchers.notNullValue()).match(this.request);
}
@Test(expected = AssertionError.class)
@Test
public void testNodeMatcherNoMatch() throws Exception {
new XpathRequestMatchers("/foo/bar", null).node(Matchers.nullValue()).match(this.request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new XpathRequestMatchers("/foo/bar", null).node(Matchers.nullValue()).match(this.request));
}
@Test
@@ -58,9 +61,10 @@ public class XpathRequestMatchersTests {
new XpathRequestMatchers("/foo/bar", null).exists().match(this.request);
}
@Test(expected = AssertionError.class)
@Test
public void testExistsNoMatch() throws Exception {
new XpathRequestMatchers("/foo/Bar", null).exists().match(this.request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new XpathRequestMatchers("/foo/Bar", null).exists().match(this.request));
}
@Test
@@ -68,9 +72,10 @@ public class XpathRequestMatchersTests {
new XpathRequestMatchers("/foo/Bar", null).doesNotExist().match(this.request);
}
@Test(expected = AssertionError.class)
@Test
public void testDoesNotExistNoMatch() throws Exception {
new XpathRequestMatchers("/foo/bar", null).doesNotExist().match(this.request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new XpathRequestMatchers("/foo/bar", null).doesNotExist().match(this.request));
}
@Test
@@ -78,9 +83,10 @@ public class XpathRequestMatchersTests {
new XpathRequestMatchers("/foo/bar", null).nodeCount(2).match(this.request);
}
@Test(expected = AssertionError.class)
@Test
public void testNodeCountNoMatch() throws Exception {
new XpathRequestMatchers("/foo/bar", null).nodeCount(1).match(this.request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new XpathRequestMatchers("/foo/bar", null).nodeCount(1).match(this.request));
}
@Test
@@ -88,9 +94,10 @@ public class XpathRequestMatchersTests {
new XpathRequestMatchers("/foo/bar[1]", null).string("111").match(this.request);
}
@Test(expected = AssertionError.class)
@Test
public void testStringNoMatch() throws Exception {
new XpathRequestMatchers("/foo/bar[1]", null).string("112").match(this.request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new XpathRequestMatchers("/foo/bar[1]", null).string("112").match(this.request));
}
@Test
@@ -98,9 +105,10 @@ public class XpathRequestMatchersTests {
new XpathRequestMatchers("/foo/bar[1]", null).number(111.0).match(this.request);
}
@Test(expected = AssertionError.class)
@Test
public void testNumberNoMatch() throws Exception {
new XpathRequestMatchers("/foo/bar[1]", null).number(111.1).match(this.request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new XpathRequestMatchers("/foo/bar[1]", null).number(111.1).match(this.request));
}
@Test
@@ -108,9 +116,10 @@ public class XpathRequestMatchersTests {
new XpathRequestMatchers("/foo/bar[2]", null).booleanValue(true).match(this.request);
}
@Test(expected = AssertionError.class)
@Test
public void testBooleanNoMatch() throws Exception {
new XpathRequestMatchers("/foo/bar[2]", null).booleanValue(false).match(this.request);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new XpathRequestMatchers("/foo/bar[2]", null).booleanValue(false).match(this.request));
}
}

View File

@@ -34,6 +34,7 @@ import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.springframework.test.web.client.ExpectedCount.manyTimes;
@@ -118,7 +119,7 @@ public class SampleTests {
this.mockServer.verify();
}
@Test(expected = AssertionError.class)
@Test
public void expectNeverViolated() {
String responseBody = "{\"name\" : \"Ludwig van Beethoven\", \"someDouble\" : \"1.6035\"}";
@@ -129,7 +130,8 @@ public class SampleTests {
.andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON));
this.restTemplate.getForObject("/composers/{id}", Person.class, 42);
this.restTemplate.getForObject("/composers/{id}", Person.class, 43);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.restTemplate.getForObject("/composers/{id}", Person.class, 43));
}
@Test

View File

@@ -33,10 +33,9 @@ import org.springframework.http.MediaType;
import org.springframework.mock.http.client.reactive.MockClientHttpRequest;
import org.springframework.mock.http.client.reactive.MockClientHttpResponse;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
/**
@@ -55,29 +54,17 @@ public class HeaderAssertionTests {
// Success
assertions.valueEquals("foo", "bar");
try {
assertions.valueEquals("what?!", "bar");
fail("Missing header expected");
}
catch (AssertionError error) {
// expected
}
// Missing header
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
assertions.valueEquals("what?!", "bar"));
try {
assertions.valueEquals("foo", "what?!");
fail("Wrong value expected");
}
catch (AssertionError error) {
// expected
}
// Wrong value
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
assertions.valueEquals("foo", "what?!"));
try {
assertions.valueEquals("foo", "bar", "what?!");
fail("Wrong # of values expected");
}
catch (AssertionError error) {
// expected
}
// Wrong # of values
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
assertions.valueEquals("foo", "bar", "what?!"));
}
@Test
@@ -90,21 +77,13 @@ public class HeaderAssertionTests {
// Success
assertions.valueEquals("foo", "bar", "baz");
try {
assertions.valueEquals("foo", "bar", "what?!");
fail("Wrong value expected");
}
catch (AssertionError error) {
// expected
}
// Wrong value
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
assertions.valueEquals("foo", "bar", "what?!"));
try {
assertions.valueEquals("foo", "bar");
fail("Too few values expected");
}
catch (AssertionError error) {
// expected
}
// Too few values
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
assertions.valueEquals("foo", "bar"));
}
@@ -117,16 +96,12 @@ public class HeaderAssertionTests {
// Success
assertions.valueMatches("Content-Type", ".*UTF-8.*");
try {
assertions.valueMatches("Content-Type", ".*ISO-8859-1.*");
fail("Wrong pattern expected");
}
catch (AssertionError error) {
Throwable cause = error.getCause();
assertNotNull(cause);
assertEquals("Response header 'Content-Type'=[application/json;charset=UTF-8] " +
"does not match [.*ISO-8859-1.*]", cause.getMessage());
}
// Wrong pattern
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
assertions.valueMatches("Content-Type", ".*ISO-8859-1.*"))
.satisfies(ex -> assertThat(ex.getCause()).hasMessage("Response header " +
"'Content-Type'=[application/json;charset=UTF-8] does not match " +
"[.*ISO-8859-1.*]"));
}
@Test
@@ -147,15 +122,10 @@ public class HeaderAssertionTests {
// Success
assertions.exists("Content-Type");
try {
assertions.exists("Framework");
fail("Header should not exist");
}
catch (AssertionError error) {
Throwable cause = error.getCause();
assertNotNull(cause);
assertEquals("Response header 'Framework' does not exist", cause.getMessage());
}
// Header should not exist
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
assertions.exists("Framework"))
.satisfies(ex -> assertThat(ex.getCause()).hasMessage("Response header 'Framework' does not exist"));
}
@Test
@@ -167,16 +137,11 @@ public class HeaderAssertionTests {
// Success
assertions.doesNotExist("Framework");
try {
assertions.doesNotExist("Content-Type");
fail("Existing header expected");
}
catch (AssertionError error) {
Throwable cause = error.getCause();
assertNotNull(cause);
assertEquals("Response header 'Content-Type' exists with " +
"value=[application/json;charset=UTF-8]", cause.getMessage());
}
// Existing header
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
assertions.doesNotExist("Content-Type"))
.satisfies(ex -> assertThat(ex.getCause()).hasMessage("Response header " +
"'Content-Type' exists with value=[application/json;charset=UTF-8]"));
}
@Test
@@ -188,16 +153,11 @@ public class HeaderAssertionTests {
// Success
assertions.contentTypeCompatibleWith(MediaType.parseMediaType("application/*"));
try {
assertions.contentTypeCompatibleWith(MediaType.TEXT_XML);
fail("MediaTypes not compatible expected");
}
catch (AssertionError error) {
Throwable cause = error.getCause();
assertNotNull(cause);
assertEquals("Response header 'Content-Type'=[application/xml] " +
"is not compatible with [text/xml]", cause.getMessage());
}
// MediaTypes not compatible
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
assertions.contentTypeCompatibleWith(MediaType.TEXT_XML))
.satisfies(ex -> assertThat(ex.getCause()).hasMessage("Response header " +
"'Content-Type'=[application/xml] is not compatible with [text/xml]"));
}
@Test
@@ -211,13 +171,9 @@ public class HeaderAssertionTests {
// Success
assertions.cacheControl(control);
try {
assertions.cacheControl(CacheControl.noStore());
fail("Wrong value expected");
}
catch (AssertionError error) {
// Expected
}
// Wrong value
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
assertions.cacheControl(CacheControl.noStore()));
}
@Test
@@ -227,13 +183,10 @@ public class HeaderAssertionTests {
headers.setExpires(expires);
HeaderAssertions assertions = headerAssertions(headers);
assertions.expires(expires.toInstant().toEpochMilli());
try {
assertions.expires(expires.toInstant().toEpochMilli() + 1);
fail("Wrong value expected");
}
catch (AssertionError error) {
// Expected
}
// Wrong value
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
assertions.expires(expires.toInstant().toEpochMilli() + 1));
}
@Test
@@ -243,13 +196,10 @@ public class HeaderAssertionTests {
headers.setLastModified(lastModified.toInstant().toEpochMilli());
HeaderAssertions assertions = headerAssertions(headers);
assertions.lastModified(lastModified.toInstant().toEpochMilli());
try {
assertions.lastModified(lastModified.toInstant().toEpochMilli() + 1);
fail("Wrong value expected");
}
catch (AssertionError error) {
// Expected
}
// Wrong value
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
assertions.lastModified(lastModified.toInstant().toEpochMilli() + 1));
}
private HeaderAssertions headerAssertions(HttpHeaders responseHeaders) {

View File

@@ -27,9 +27,9 @@ import org.springframework.http.HttpStatus;
import org.springframework.mock.http.client.reactive.MockClientHttpRequest;
import org.springframework.mock.http.client.reactive.MockClientHttpResponse;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
/**
@@ -46,21 +46,13 @@ public class StatusAssertionTests {
assertions.isEqualTo(HttpStatus.CONFLICT);
assertions.isEqualTo(409);
try {
assertions.isEqualTo(HttpStatus.REQUEST_TIMEOUT);
fail("Wrong status expected");
}
catch (AssertionError error) {
// Expected
}
// Wrong status
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
assertions.isEqualTo(HttpStatus.REQUEST_TIMEOUT));
try {
assertions.isEqualTo(408);
fail("Wrong status value expected");
}
catch (AssertionError error) {
// Expected
}
// Wrong status value
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
assertions.isEqualTo(408));
}
@Test
@@ -70,13 +62,9 @@ public class StatusAssertionTests {
// Success
assertions.reasonEquals("Conflict");
try {
assertions.reasonEquals("Request Timeout");
fail("Wrong reason expected");
}
catch (AssertionError error) {
// Expected
}
// Wrong reason
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
assertions.reasonEquals("Request Timeout"));
}
@Test
@@ -86,13 +74,10 @@ public class StatusAssertionTests {
// Success
assertions.is1xxInformational();
try {
assertions.is2xxSuccessful();
fail("Wrong series expected");
}
catch (AssertionError error) {
// Expected
}
// Wrong series
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
assertions.is2xxSuccessful());
}
@Test
@@ -102,13 +87,9 @@ public class StatusAssertionTests {
// Success
assertions.is2xxSuccessful();
try {
assertions.is5xxServerError();
fail("Wrong series expected");
}
catch (AssertionError error) {
// Expected
}
// Wrong series
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
assertions.is5xxServerError());
}
@Test
@@ -118,13 +99,9 @@ public class StatusAssertionTests {
// Success
assertions.is3xxRedirection();
try {
assertions.is2xxSuccessful();
fail("Wrong series expected");
}
catch (AssertionError error) {
// Expected
}
// Wrong series
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
assertions.is2xxSuccessful());
}
@Test
@@ -134,13 +111,9 @@ public class StatusAssertionTests {
// Success
assertions.is4xxClientError();
try {
assertions.is2xxSuccessful();
fail("Wrong series expected");
}
catch (AssertionError error) {
// Expected
}
// Wrong series
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
assertions.is2xxSuccessful());
}
@Test
@@ -150,13 +123,9 @@ public class StatusAssertionTests {
// Success
assertions.is5xxServerError();
try {
assertions.is2xxSuccessful();
fail("Wrong series expected");
}
catch (AssertionError error) {
// Expected
}
// Wrong series
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
assertions.is2xxSuccessful());
}
@Test
@@ -167,13 +136,9 @@ public class StatusAssertionTests {
assertions.value(equalTo(409));
assertions.value(greaterThan(400));
try {
assertions.value(equalTo(200));
fail("Wrong status expected");
}
catch (AssertionError error) {
// Expected
}
// Wrong status
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
assertions.value(equalTo(200)));
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,6 +22,8 @@ import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* Test fixture for {@link DefaultMvcResult}.
*
@@ -38,9 +40,10 @@ public class DefaultMvcResultTests {
this.mvcResult.getAsyncResult();
}
@Test(expected = IllegalStateException.class)
@Test
public void getAsyncResultFailure() {
this.mvcResult.getAsyncResult(0);
assertThatIllegalStateException().isThrownBy(() ->
this.mvcResult.getAsyncResult(0));
}
}

View File

@@ -46,6 +46,7 @@ import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
@@ -86,19 +87,22 @@ public class HtmlUnitRequestBuilderTests {
// --- constructor
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorNullSessions() {
new HtmlUnitRequestBuilder(null, webClient, webRequest);
assertThatIllegalArgumentException().isThrownBy(() ->
new HtmlUnitRequestBuilder(null, webClient, webRequest));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorNullWebClient() {
new HtmlUnitRequestBuilder(sessions, null, webRequest);
assertThatIllegalArgumentException().isThrownBy(() ->
new HtmlUnitRequestBuilder(sessions, null, webRequest));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorNullWebRequest() {
new HtmlUnitRequestBuilder(sessions, webClient, null);
assertThatIllegalArgumentException().isThrownBy(() ->
new HtmlUnitRequestBuilder(sessions, webClient, null));
}
@@ -184,11 +188,12 @@ public class HtmlUnitRequestBuilderTests {
assertThat(contextPath, equalTo(""));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void buildRequestContextPathInvalid() {
requestBuilder.setContextPath("/invalid");
requestBuilder.buildRequest(servletContext).getContextPath();
assertThatIllegalArgumentException().isThrownBy(() ->
requestBuilder.buildRequest(servletContext).getContextPath());
}
@Test
@@ -823,14 +828,16 @@ public class HtmlUnitRequestBuilderTests {
assertThat(getContextPath(), isEmptyString());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void setContextPathDoesNotStartWithSlash() {
requestBuilder.setContextPath("abc/def");
assertThatIllegalArgumentException().isThrownBy(() ->
requestBuilder.setContextPath("abc/def"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void setContextPathEndsWithSlash() {
requestBuilder.setContextPath("/abc/def/");
assertThatIllegalArgumentException().isThrownBy(() ->
requestBuilder.setContextPath("/abc/def/"));
}
@Test

View File

@@ -40,6 +40,7 @@ import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
@@ -75,14 +76,16 @@ public class MockMvcConnectionBuilderSupportTests {
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorMockMvcNull() {
new MockMvcWebConnectionBuilderSupport((MockMvc) null){};
assertThatIllegalArgumentException().isThrownBy(() ->
new MockMvcWebConnectionBuilderSupport((MockMvc) null){});
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorContextNull() {
new MockMvcWebConnectionBuilderSupport((WebApplicationContext) null){};
assertThatIllegalArgumentException().isThrownBy(() ->
new MockMvcWebConnectionBuilderSupport((WebApplicationContext) null){});
}
@Test

View File

@@ -48,6 +48,7 @@ import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
@@ -77,14 +78,16 @@ public class MockMvcWebClientBuilderTests {
}
@Test(expected = IllegalArgumentException.class)
@Test
public void mockMvcSetupNull() {
MockMvcWebClientBuilder.mockMvcSetup(null);
assertThatIllegalArgumentException().isThrownBy(() ->
MockMvcWebClientBuilder.mockMvcSetup(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void webAppContextSetupNull() {
MockMvcWebClientBuilder.webAppContextSetup(null);
assertThatIllegalArgumentException().isThrownBy(() ->
MockMvcWebClientBuilder.webAppContextSetup(null));
}
@Test

View File

@@ -26,10 +26,11 @@ import org.junit.Test;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.assertj.core.api.Assertions.assertThat;
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.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
* Integration tests for {@link MockMvcWebConnection}.
@@ -62,21 +63,15 @@ public class MockMvcWebConnectionTests {
@Test
public void contextPathEmpty() throws IOException {
this.webClient.setWebConnection(new MockMvcWebConnection(this.mockMvc, this.webClient, ""));
try {
this.webClient.getPage("http://localhost/context/a");
fail("Empty context path (root context) should not match to a URL with a context path");
}
catch (FailingHttpStatusCodeException ex) {
assertEquals(404, ex.getStatusCode());
}
// Empty context path (root context) should not match to a URL with a context path
assertThatExceptionOfType(FailingHttpStatusCodeException.class).isThrownBy(() ->
this.webClient.getPage("http://localhost/context/a"))
.satisfies(ex -> assertThat(ex.getStatusCode()).isEqualTo(404));
this.webClient.setWebConnection(new MockMvcWebConnection(this.mockMvc, this.webClient));
try {
this.webClient.getPage("http://localhost/context/a");
fail("No context is the same providing an empty context path");
}
catch (FailingHttpStatusCodeException ex) {
assertEquals(404, ex.getStatusCode());
}
// No context is the same providing an empty context path
assertThatExceptionOfType(FailingHttpStatusCodeException.class).isThrownBy(() ->
this.webClient.getPage("http://localhost/context/a"))
.satisfies(ex -> assertThat(ex.getStatusCode()).isEqualTo(404));
}
@Test
@@ -86,16 +81,18 @@ public class MockMvcWebConnectionTests {
assertThat(page.getWebResponse().getContentAsString(), equalTo("hello"));
}
@Test(expected = IllegalArgumentException.class)
@Test
@SuppressWarnings("resource")
public void contextPathDoesNotStartWithSlash() throws IOException {
new MockMvcWebConnection(this.mockMvc, this.webClient, "context");
assertThatIllegalArgumentException().isThrownBy(() ->
new MockMvcWebConnection(this.mockMvc, this.webClient, "context"));
}
@Test(expected = IllegalArgumentException.class)
@Test
@SuppressWarnings("resource")
public void contextPathEndsWithSlash() throws IOException {
new MockMvcWebConnection(this.mockMvc, this.webClient, "/context/");
assertThatIllegalArgumentException().isThrownBy(() ->
new MockMvcWebConnection(this.mockMvc, this.webClient, "/context/"));
}
}

View File

@@ -29,6 +29,7 @@ import org.junit.Test;
import org.springframework.mock.web.MockHttpServletResponse;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.CoreMatchers.endsWith;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.startsWith;
@@ -58,14 +59,16 @@ public class MockWebResponseBuilderTests {
// --- constructor
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorWithNullWebRequest() {
new MockWebResponseBuilder(0L, null, this.response);
assertThatIllegalArgumentException().isThrownBy(() ->
new MockWebResponseBuilder(0L, null, this.response));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorWithNullResponse() throws Exception {
new MockWebResponseBuilder(0L, new WebRequest(new URL("http://example.com:80/test/this/here")), null);
assertThatIllegalArgumentException().isThrownBy(() ->
new MockWebResponseBuilder(0L, new WebRequest(new URL("http://example.com:80/test/this/here")), null));
}

View File

@@ -40,6 +40,7 @@ import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
@@ -75,14 +76,16 @@ public class MockMvcHtmlUnitDriverBuilderTests {
}
@Test(expected = IllegalArgumentException.class)
@Test
public void webAppContextSetupNull() {
MockMvcHtmlUnitDriverBuilder.webAppContextSetup(null);
assertThatIllegalArgumentException().isThrownBy(() ->
MockMvcHtmlUnitDriverBuilder.webAppContextSetup(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void mockMvcSetupNull() {
MockMvcHtmlUnitDriverBuilder.mockMvcSetup(null);
assertThatIllegalArgumentException().isThrownBy(() ->
MockMvcHtmlUnitDriverBuilder.mockMvcSetup(null));
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,6 +22,8 @@ import org.junit.Test;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.StubMvcResult;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Rossen Stoyanchev
*/
@@ -32,9 +34,10 @@ public class ContentResultMatchersTests {
new ContentResultMatchers().contentType("application/json;charset=UTF-8").match(getStubMvcResult());
}
@Test(expected = AssertionError.class)
@Test
public void typeNoMatch() throws Exception {
new ContentResultMatchers().contentType("text/plain").match(getStubMvcResult());
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new ContentResultMatchers().contentType("text/plain").match(getStubMvcResult()));
}
@Test
@@ -42,9 +45,10 @@ public class ContentResultMatchersTests {
new ContentResultMatchers().encoding("UTF-8").match(getStubMvcResult());
}
@Test(expected = AssertionError.class)
@Test
public void encodingNoMatch() throws Exception {
new ContentResultMatchers().encoding("ISO-8859-1").match(getStubMvcResult());
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new ContentResultMatchers().encoding("ISO-8859-1").match(getStubMvcResult()));
}
@Test
@@ -52,9 +56,10 @@ public class ContentResultMatchersTests {
new ContentResultMatchers().string(new String(CONTENT.getBytes("UTF-8"))).match(getStubMvcResult());
}
@Test(expected = AssertionError.class)
@Test
public void stringNoMatch() throws Exception {
new ContentResultMatchers().encoding("bogus").match(getStubMvcResult());
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new ContentResultMatchers().encoding("bogus").match(getStubMvcResult()));
}
@Test
@@ -63,9 +68,10 @@ public class ContentResultMatchersTests {
new ContentResultMatchers().string(Matchers.equalTo(content)).match(getStubMvcResult());
}
@Test(expected = AssertionError.class)
@Test
public void stringMatcherNoMatch() throws Exception {
new ContentResultMatchers().string(Matchers.equalTo("bogus")).match(getStubMvcResult());
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new ContentResultMatchers().string(Matchers.equalTo("bogus")).match(getStubMvcResult()));
}
@Test
@@ -73,9 +79,10 @@ public class ContentResultMatchersTests {
new ContentResultMatchers().bytes(CONTENT.getBytes("UTF-8")).match(getStubMvcResult());
}
@Test(expected = AssertionError.class)
@Test
public void bytesNoMatch() throws Exception {
new ContentResultMatchers().bytes("bogus".getBytes()).match(getStubMvcResult());
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new ContentResultMatchers().bytes("bogus".getBytes()).match(getStubMvcResult()));
}
@Test
@@ -90,14 +97,16 @@ public class ContentResultMatchersTests {
new ContentResultMatchers().json("{\n \"foo array\":[\"foo\",\"bar\"], \"foo\":\"bar\" \n}", true).match(getStubMvcResult());
}
@Test(expected = AssertionError.class)
@Test
public void jsonLenientNoMatch() throws Exception {
new ContentResultMatchers().json("{\n\"fooo\":\"bar\"\n}").match(getStubMvcResult());
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new ContentResultMatchers().json("{\n\"fooo\":\"bar\"\n}").match(getStubMvcResult()));
}
@Test(expected = AssertionError.class)
@Test
public void jsonStrictNoMatch() throws Exception {
new ContentResultMatchers().json("{\"foo\":\"bar\", \"foo array\":[\"bar\",\"foo\"]}", true).match(getStubMvcResult());
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new ContentResultMatchers().json("{\"foo\":\"bar\", \"foo array\":[\"bar\",\"foo\"]}", true).match(getStubMvcResult()));
}
private static final String CONTENT = "{\"foo\":\"bar\",\"foo array\":[\"foo\",\"bar\"]}";

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,6 +21,8 @@ import org.junit.Test;
import org.springframework.test.web.servlet.StubMvcResult;
import org.springframework.web.servlet.FlashMap;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Craig Walls
*/
@@ -31,9 +33,10 @@ public class FlashAttributeResultMatchersTests {
new FlashAttributeResultMatchers().attributeExists("good").match(getStubMvcResult());
}
@Test(expected = AssertionError.class)
@Test
public void attributeExists_doesntExist() throws Exception {
new FlashAttributeResultMatchers().attributeExists("bad").match(getStubMvcResult());
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new FlashAttributeResultMatchers().attributeExists("bad").match(getStubMvcResult()));
}
@Test
@@ -41,9 +44,10 @@ public class FlashAttributeResultMatchersTests {
new FlashAttributeResultMatchers().attribute("good", "good").match(getStubMvcResult());
}
@Test(expected = AssertionError.class)
@Test
public void attribute_incorrectValue() throws Exception {
new FlashAttributeResultMatchers().attribute("good", "not good").match(getStubMvcResult());
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new FlashAttributeResultMatchers().attribute("good", "not good").match(getStubMvcResult()));
}
private StubMvcResult getStubMvcResult() {

View File

@@ -22,6 +22,8 @@ import org.junit.Test;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.StubMvcResult;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Unit tests for {@link JsonPathResultMatchers}.
*
@@ -57,9 +59,10 @@ public class JsonPathResultMatchersTests {
}
}
@Test(expected = AssertionError.class)
@Test
public void valueWithMismatch() throws Exception {
new JsonPathResultMatchers("$.str").value("bogus").match(stubMvcResult);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.str").value("bogus").match(stubMvcResult));
}
@Test
@@ -82,9 +85,10 @@ public class JsonPathResultMatchersTests {
new JsonPathResultMatchers("$.num").value(Matchers.equalTo(5.0f), Float.class).match(stubMvcResult);
}
@Test(expected = AssertionError.class)
@Test
public void valueWithMatcherAndMismatch() throws Exception {
new JsonPathResultMatchers("$.str").value(Matchers.equalTo("bogus")).match(stubMvcResult);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.str").value(Matchers.equalTo("bogus")).match(stubMvcResult));
}
@Test
@@ -102,9 +106,10 @@ public class JsonPathResultMatchersTests {
new JsonPathResultMatchers("$.emptyMap").exists().match(stubMvcResult);
}
@Test(expected = AssertionError.class)
@Test
public void existsNoMatch() throws Exception {
new JsonPathResultMatchers("$.bogus").exists().match(stubMvcResult);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.bogus").exists().match(stubMvcResult));
}
@Test
@@ -112,19 +117,22 @@ public class JsonPathResultMatchersTests {
new JsonPathResultMatchers("$.bogus").doesNotExist().match(stubMvcResult);
}
@Test(expected = AssertionError.class)
@Test
public void doesNotExistNoMatch() throws Exception {
new JsonPathResultMatchers("$.str").doesNotExist().match(stubMvcResult);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.str").doesNotExist().match(stubMvcResult));
}
@Test(expected = AssertionError.class)
@Test
public void doesNotExistForAnEmptyArray() throws Exception {
new JsonPathResultMatchers("$.emptyArray").doesNotExist().match(stubMvcResult);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.emptyArray").doesNotExist().match(stubMvcResult));
}
@Test(expected = AssertionError.class)
@Test
public void doesNotExistForAnEmptyMap() throws Exception {
new JsonPathResultMatchers("$.emptyMap").doesNotExist().match(stubMvcResult);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.emptyMap").doesNotExist().match(stubMvcResult));
}
@Test
@@ -167,19 +175,22 @@ public class JsonPathResultMatchersTests {
new JsonPathResultMatchers("$.colorMap").isNotEmpty().match(stubMvcResult);
}
@Test(expected = AssertionError.class)
@Test
public void isNotEmptyForAnEmptyString() throws Exception {
new JsonPathResultMatchers("$.emptyString").isNotEmpty().match(stubMvcResult);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.emptyString").isNotEmpty().match(stubMvcResult));
}
@Test(expected = AssertionError.class)
@Test
public void isNotEmptyForAnEmptyArray() throws Exception {
new JsonPathResultMatchers("$.emptyArray").isNotEmpty().match(stubMvcResult);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.emptyArray").isNotEmpty().match(stubMvcResult));
}
@Test(expected = AssertionError.class)
@Test
public void isNotEmptyForAnEmptyMap() throws Exception {
new JsonPathResultMatchers("$.emptyMap").isNotEmpty().match(stubMvcResult);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.emptyMap").isNotEmpty().match(stubMvcResult));
}
@Test
@@ -192,9 +203,10 @@ public class JsonPathResultMatchersTests {
new JsonPathResultMatchers("$.emptyArray").isArray().match(stubMvcResult);
}
@Test(expected = AssertionError.class)
@Test
public void isArrayNoMatch() throws Exception {
new JsonPathResultMatchers("$.bar").isArray().match(stubMvcResult);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.bar").isArray().match(stubMvcResult));
}
@Test
@@ -207,9 +219,10 @@ public class JsonPathResultMatchersTests {
new JsonPathResultMatchers("$.emptyMap").isMap().match(stubMvcResult);
}
@Test(expected = AssertionError.class)
@Test
public void isMapNoMatch() throws Exception {
new JsonPathResultMatchers("$.str").isMap().match(stubMvcResult);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.str").isMap().match(stubMvcResult));
}
@Test
@@ -217,9 +230,10 @@ public class JsonPathResultMatchersTests {
new JsonPathResultMatchers("$.bool").isBoolean().match(stubMvcResult);
}
@Test(expected = AssertionError.class)
@Test
public void isBooleanNoMatch() throws Exception {
new JsonPathResultMatchers("$.str").isBoolean().match(stubMvcResult);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.str").isBoolean().match(stubMvcResult));
}
@Test
@@ -227,9 +241,10 @@ public class JsonPathResultMatchersTests {
new JsonPathResultMatchers("$.num").isNumber().match(stubMvcResult);
}
@Test(expected = AssertionError.class)
@Test
public void isNumberNoMatch() throws Exception {
new JsonPathResultMatchers("$.str").isNumber().match(stubMvcResult);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.str").isNumber().match(stubMvcResult));
}
@Test
@@ -237,23 +252,26 @@ public class JsonPathResultMatchersTests {
new JsonPathResultMatchers("$.str").isString().match(stubMvcResult);
}
@Test(expected = AssertionError.class)
@Test
public void isStringNoMatch() throws Exception {
new JsonPathResultMatchers("$.arr").isString().match(stubMvcResult);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.arr").isString().match(stubMvcResult));
}
@Test(expected = AssertionError.class)
@Test
public void valueWithJsonPrefixNotConfigured() throws Exception {
String jsonPrefix = "prefix";
StubMvcResult result = createPrefixedStubMvcResult(jsonPrefix);
new JsonPathResultMatchers("$.str").value("foo").match(result);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.str").value("foo").match(result));
}
@Test(expected = AssertionError.class)
@Test
public void valueWithJsonWrongPrefix() throws Exception {
String jsonPrefix = "prefix";
StubMvcResult result = createPrefixedStubMvcResult(jsonPrefix);
new JsonPathResultMatchers("$.str").prefix("wrong").value("foo").match(result);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.str").prefix("wrong").value("foo").match(result));
}
@Test
@@ -263,14 +281,15 @@ public class JsonPathResultMatchersTests {
new JsonPathResultMatchers("$.str").prefix(jsonPrefix).value("foo").match(result);
}
@Test(expected = AssertionError.class)
@Test
public void prefixWithPayloadNotLongEnough() throws Exception {
MockHttpServletResponse response = new MockHttpServletResponse();
response.addHeader("Content-Type", "application/json");
response.getWriter().print(new String("test".getBytes("ISO-8859-1")));
StubMvcResult result = new StubMvcResult(null, null, null, null, null, null, response);
new JsonPathResultMatchers("$.str").prefix("prefix").value("foo").match(result);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new JsonPathResultMatchers("$.str").prefix("prefix").value("foo").match(result));
}
private StubMvcResult createPrefixedStubMvcResult(String jsonPrefix) throws Exception {

View File

@@ -21,6 +21,7 @@ import org.junit.Test;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.StubMvcResult;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrlPattern;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrlTemplate;
@@ -51,9 +52,10 @@ public class MockMvcResultMatchersTests {
redirectedUrlPattern("/resource/*").match(getRedirectedUrlStubMvcResult("/resource/1"));
}
@Test(expected = AssertionError.class)
@Test
public void redirectWithNonMatchingPattern() throws Exception {
redirectedUrlPattern("/resource/").match(getRedirectedUrlStubMvcResult("/resource/1"));
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
redirectedUrlPattern("/resource/").match(getRedirectedUrlStubMvcResult("/resource/1")));
}
@Test
@@ -76,9 +78,10 @@ public class MockMvcResultMatchersTests {
forwardedUrlPattern("/api/**/?").match(getForwardedUrlStubMvcResult("/api/resource/1"));
}
@Test(expected = AssertionError.class)
@Test
public void forwardWithNonMatchingPattern() throws Exception {
forwardedUrlPattern("/resource/").match(getForwardedUrlStubMvcResult("/resource/1"));
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
forwardedUrlPattern("/resource/").match(getForwardedUrlStubMvcResult("/resource/1")));
}
private StubMvcResult getRedirectedUrlStubMvcResult(String redirectUrl) throws Exception {

View File

@@ -27,6 +27,7 @@ import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.ModelAndView;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.startsWith;
@@ -69,9 +70,10 @@ public class ModelResultMatchersTests {
this.matchers.attributeExists("good").match(this.mvcResult);
}
@Test(expected = AssertionError.class)
@Test
public void attributeExists_doesNotExist() throws Exception {
this.matchers.attributeExists("bad").match(this.mvcResult);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.matchers.attributeExists("bad").match(this.mvcResult));
}
@Test
@@ -79,9 +81,10 @@ public class ModelResultMatchersTests {
this.matchers.attributeDoesNotExist("bad").match(this.mvcResult);
}
@Test(expected = AssertionError.class)
@Test
public void attributeDoesNotExist_doesExist() throws Exception {
this.matchers.attributeDoesNotExist("good").match(this.mvcResultWithError);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.matchers.attributeDoesNotExist("good").match(this.mvcResultWithError));
}
@Test
@@ -89,9 +92,10 @@ public class ModelResultMatchersTests {
this.matchers.attribute("good", is("good")).match(this.mvcResult);
}
@Test(expected = AssertionError.class)
@Test
public void attribute_notEqual() throws Exception {
this.matchers.attribute("good", is("bad")).match(this.mvcResult);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.matchers.attribute("good", is("bad")).match(this.mvcResult));
}
@Test
@@ -99,9 +103,10 @@ public class ModelResultMatchersTests {
this.matchers.hasNoErrors().match(this.mvcResult);
}
@Test(expected = AssertionError.class)
@Test
public void hasNoErrors_withErrors() throws Exception {
this.matchers.hasNoErrors().match(this.mvcResultWithError);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.matchers.hasNoErrors().match(this.mvcResultWithError));
}
@Test
@@ -109,9 +114,10 @@ public class ModelResultMatchersTests {
this.matchers.attributeHasErrors("date").match(this.mvcResultWithError);
}
@Test(expected = AssertionError.class)
@Test
public void attributeHasErrors_withoutErrors() throws Exception {
this.matchers.attributeHasErrors("good").match(this.mvcResultWithError);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.matchers.attributeHasErrors("good").match(this.mvcResultWithError));
}
@Test
@@ -119,14 +125,16 @@ public class ModelResultMatchersTests {
this.matchers.attributeHasNoErrors("good").match(this.mvcResult);
}
@Test(expected = AssertionError.class)
@Test
public void attributeHasNoErrors_withoutAttribute() throws Exception {
this.matchers.attributeHasNoErrors("missing").match(this.mvcResultWithError);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.matchers.attributeHasNoErrors("missing").match(this.mvcResultWithError));
}
@Test(expected = AssertionError.class)
@Test
public void attributeHasNoErrors_withErrors() throws Exception {
this.matchers.attributeHasNoErrors("date").match(this.mvcResultWithError);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.matchers.attributeHasNoErrors("date").match(this.mvcResultWithError));
}
@Test
@@ -134,19 +142,22 @@ public class ModelResultMatchersTests {
this.matchers.attributeHasFieldErrors("date", "time").match(this.mvcResultWithError);
}
@Test(expected = AssertionError.class)
@Test
public void attributeHasFieldErrors_withoutAttribute() throws Exception {
this.matchers.attributeHasFieldErrors("missing", "bad").match(this.mvcResult);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.matchers.attributeHasFieldErrors("missing", "bad").match(this.mvcResult));
}
@Test(expected = AssertionError.class)
@Test
public void attributeHasFieldErrors_withoutErrorsForAttribute() throws Exception {
this.matchers.attributeHasFieldErrors("date", "time").match(this.mvcResult);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.matchers.attributeHasFieldErrors("date", "time").match(this.mvcResult));
}
@Test(expected = AssertionError.class)
@Test
public void attributeHasFieldErrors_withoutErrorsForField() throws Exception {
this.matchers.attributeHasFieldErrors("date", "good", "time").match(this.mvcResultWithError);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.matchers.attributeHasFieldErrors("date", "good", "time").match(this.mvcResultWithError));
}
@Test
@@ -154,9 +165,10 @@ public class ModelResultMatchersTests {
this.matchers.attributeHasFieldErrorCode("date", "time", "error").match(this.mvcResultWithError);
}
@Test(expected = AssertionError.class)
@Test
public void attributeHasFieldErrorCode_withoutErrorOnField() throws Exception {
this.matchers.attributeHasFieldErrorCode("date", "time", "incorrectError").match(this.mvcResultWithError);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.matchers.attributeHasFieldErrorCode("date", "time", "incorrectError").match(this.mvcResultWithError));
}
@Test
@@ -164,9 +176,10 @@ public class ModelResultMatchersTests {
this.matchers.attributeHasFieldErrorCode("date", "time", startsWith("err")).match(this.mvcResultWithError);
}
@Test(expected = AssertionError.class)
@Test
public void attributeHasFieldErrorCode_startsWith_withoutErrorOnField() throws Exception {
this.matchers.attributeHasFieldErrorCode("date", "time", startsWith("inc")).match(this.mvcResultWithError);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.matchers.attributeHasFieldErrorCode("date", "time", startsWith("inc")).match(this.mvcResultWithError));
}
private MvcResult getMvcResult(ModelAndView modelAndView) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,6 +25,8 @@ import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.StubMvcResult;
import org.springframework.util.StreamUtils;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link XpathResultMatchers}.
*
@@ -40,9 +42,10 @@ public class XpathResultMatchersTests {
new XpathResultMatchers("/foo/bar", null).node(Matchers.notNullValue()).match(getStubMvcResult());
}
@Test(expected = AssertionError.class)
@Test
public void nodeNoMatch() throws Exception {
new XpathResultMatchers("/foo/bar", null).node(Matchers.nullValue()).match(getStubMvcResult());
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new XpathResultMatchers("/foo/bar", null).node(Matchers.nullValue()).match(getStubMvcResult()));
}
@Test
@@ -50,9 +53,10 @@ public class XpathResultMatchersTests {
new XpathResultMatchers("/foo/bar", null).exists().match(getStubMvcResult());
}
@Test(expected = AssertionError.class)
@Test
public void existsNoMatch() throws Exception {
new XpathResultMatchers("/foo/Bar", null).exists().match(getStubMvcResult());
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new XpathResultMatchers("/foo/Bar", null).exists().match(getStubMvcResult()));
}
@Test
@@ -60,9 +64,10 @@ public class XpathResultMatchersTests {
new XpathResultMatchers("/foo/Bar", null).doesNotExist().match(getStubMvcResult());
}
@Test(expected = AssertionError.class)
@Test
public void doesNotExistNoMatch() throws Exception {
new XpathResultMatchers("/foo/bar", null).doesNotExist().match(getStubMvcResult());
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new XpathResultMatchers("/foo/bar", null).doesNotExist().match(getStubMvcResult()));
}
@Test
@@ -70,9 +75,10 @@ public class XpathResultMatchersTests {
new XpathResultMatchers("/foo/bar", null).nodeCount(2).match(getStubMvcResult());
}
@Test(expected = AssertionError.class)
@Test
public void nodeCountNoMatch() throws Exception {
new XpathResultMatchers("/foo/bar", null).nodeCount(1).match(getStubMvcResult());
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new XpathResultMatchers("/foo/bar", null).nodeCount(1).match(getStubMvcResult()));
}
@Test
@@ -80,9 +86,10 @@ public class XpathResultMatchersTests {
new XpathResultMatchers("/foo/bar[1]", null).string("111").match(getStubMvcResult());
}
@Test(expected = AssertionError.class)
@Test
public void stringNoMatch() throws Exception {
new XpathResultMatchers("/foo/bar[1]", null).string("112").match(getStubMvcResult());
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new XpathResultMatchers("/foo/bar[1]", null).string("112").match(getStubMvcResult()));
}
@Test
@@ -90,9 +97,10 @@ public class XpathResultMatchersTests {
new XpathResultMatchers("/foo/bar[1]", null).number(111.0).match(getStubMvcResult());
}
@Test(expected = AssertionError.class)
@Test
public void numberNoMatch() throws Exception {
new XpathResultMatchers("/foo/bar[1]", null).number(111.1).match(getStubMvcResult());
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new XpathResultMatchers("/foo/bar[1]", null).number(111.1).match(getStubMvcResult()));
}
@Test
@@ -100,9 +108,10 @@ public class XpathResultMatchersTests {
new XpathResultMatchers("/foo/bar[2]", null).booleanValue(true).match(getStubMvcResult());
}
@Test(expected = AssertionError.class)
@Test
public void booleanValueNoMatch() throws Exception {
new XpathResultMatchers("/foo/bar[2]", null).booleanValue(false).match(getStubMvcResult());
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new XpathResultMatchers("/foo/bar[2]", null).booleanValue(false).match(getStubMvcResult()));
}
@Test

View File

@@ -34,6 +34,7 @@ import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.WebRequest;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.hasItems;
@@ -158,9 +159,10 @@ public class HeaderAssertionTests {
this.mockMvc.perform(get("/persons/1")).andExpect(header().exists(LAST_MODIFIED));
}
@Test(expected = AssertionError.class)
@Test
public void existsFail() throws Exception {
this.mockMvc.perform(get("/persons/1")).andExpect(header().exists("X-Custom-Header"));
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.mockMvc.perform(get("/persons/1")).andExpect(header().exists("X-Custom-Header")));
}
@Test // SPR-10771
@@ -168,14 +170,16 @@ public class HeaderAssertionTests {
this.mockMvc.perform(get("/persons/1")).andExpect(header().doesNotExist("X-Custom-Header"));
}
@Test(expected = AssertionError.class) // SPR-10771
@Test // SPR-10771
public void doesNotExistFail() throws Exception {
this.mockMvc.perform(get("/persons/1")).andExpect(header().doesNotExist(LAST_MODIFIED));
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.mockMvc.perform(get("/persons/1")).andExpect(header().doesNotExist(LAST_MODIFIED)));
}
@Test(expected = AssertionError.class)
@Test
public void longValueWithIncorrectResponseHeaderValue() throws Exception {
this.mockMvc.perform(get("/persons/1")).andExpect(header().longValue("X-Rate-Limiting", 1));
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.mockMvc.perform(get("/persons/1")).andExpect(header().longValue("X-Rate-Limiting", 1)));
}
@Test

View File

@@ -38,6 +38,7 @@ import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
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;
@@ -92,28 +93,32 @@ public class StandaloneMockMvcBuilderTests {
assertEquals(wac, WebApplicationContextUtils.getRequiredWebApplicationContext(wac.getServletContext()));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void addFiltersFiltersNull() {
StandaloneMockMvcBuilder builder = MockMvcBuilders.standaloneSetup(new PersonController());
builder.addFilters((Filter[]) null);
assertThatIllegalArgumentException().isThrownBy(() ->
builder.addFilters((Filter[]) null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void addFiltersFiltersContainsNull() {
StandaloneMockMvcBuilder builder = MockMvcBuilders.standaloneSetup(new PersonController());
builder.addFilters(new ContinueFilter(), (Filter) null);
assertThatIllegalArgumentException().isThrownBy(() ->
builder.addFilters(new ContinueFilter(), (Filter) null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void addFilterPatternsNull() {
StandaloneMockMvcBuilder builder = MockMvcBuilders.standaloneSetup(new PersonController());
builder.addFilter(new ContinueFilter(), (String[]) null);
assertThatIllegalArgumentException().isThrownBy(() ->
builder.addFilter(new ContinueFilter(), (String[]) null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void addFilterPatternContainsNull() {
StandaloneMockMvcBuilder builder = MockMvcBuilders.standaloneSetup(new PersonController());
builder.addFilter(new ContinueFilter(), (String) null);
assertThatIllegalArgumentException().isThrownBy(() ->
builder.addFilter(new ContinueFilter(), (String) null));
}
@Test // SPR-13375