Commit 82bc8756 authored by Andy Wilkinson's avatar Andy Wilkinson

Use AssertJ’s exception assertions rather than fail

Closes gh-15761
parent 9357a925
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -28,7 +28,6 @@ import org.springframework.format.support.DefaultFormattingConversionService; ...@@ -28,7 +28,6 @@ import org.springframework.format.support.DefaultFormattingConversionService;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
...@@ -61,15 +60,14 @@ public class ConversionServiceParameterValueMapperTests { ...@@ -61,15 +60,14 @@ public class ConversionServiceParameterValueMapperTests {
given(conversionService.convert(any(), any())).willThrow(error); given(conversionService.convert(any(), any())).willThrow(error);
ConversionServiceParameterValueMapper mapper = new ConversionServiceParameterValueMapper( ConversionServiceParameterValueMapper mapper = new ConversionServiceParameterValueMapper(
conversionService); conversionService);
try { assertThatExceptionOfType(ParameterMappingException.class)
mapper.mapParameterValue(new TestOperationParameter(Integer.class), "123"); .isThrownBy(() -> mapper.mapParameterValue(
fail("Did not throw"); new TestOperationParameter(Integer.class), "123"))
} .satisfies((ex) -> {
catch (ParameterMappingException ex) { assertThat(ex.getValue()).isEqualTo("123");
assertThat(ex.getValue()).isEqualTo("123"); assertThat(ex.getParameter().getType()).isEqualTo(Integer.class);
assertThat(ex.getParameter().getType()).isEqualTo(Integer.class); assertThat(ex.getCause()).isEqualTo(error);
assertThat(ex.getCause()).isEqualTo(error); });
}
} }
@Test @Test
......
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -36,7 +36,7 @@ import org.springframework.mock.web.server.MockServerWebExchange; ...@@ -36,7 +36,7 @@ import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.web.server.ServerWebExchangeDecorator; import org.springframework.web.server.ServerWebExchangeDecorator;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
...@@ -123,19 +123,14 @@ public class HttpTraceWebFilterTests { ...@@ -123,19 +123,14 @@ public class HttpTraceWebFilterTests {
@Test @Test
public void statusIsAssumedToBe500WhenChainFails() public void statusIsAssumedToBe500WhenChainFails()
throws ServletException, IOException { throws ServletException, IOException {
try { assertThatExceptionOfType(Exception.class).isThrownBy(() -> this.filter
this.filter .filter(MockServerWebExchange
.filter(MockServerWebExchange .from(MockServerHttpRequest.get("https://api.example.com")),
.from(MockServerHttpRequest.get("https://api.example.com")), (exchange) -> Mono.error(new RuntimeException()))
(exchange) -> Mono.error(new RuntimeException())) .block(Duration.ofSeconds(30)));
.block(Duration.ofSeconds(30)); assertThat(this.repository.findAll()).hasSize(1);
fail(); assertThat(this.repository.findAll().get(0).getResponse().getStatus())
} .isEqualTo(500);
catch (Exception ex) {
assertThat(this.repository.findAll()).hasSize(1);
assertThat(this.repository.findAll().get(0).getResponse().getStatus())
.isEqualTo(500);
}
} }
} }
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -37,7 +37,7 @@ import org.springframework.mock.web.MockHttpServletRequest; ...@@ -37,7 +37,7 @@ import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockHttpServletResponse;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.assertj.core.api.Assertions.assertThatIOException;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
...@@ -106,25 +106,24 @@ public class HttpTraceFilterTests { ...@@ -106,25 +106,24 @@ public class HttpTraceFilterTests {
@Test @Test
public void statusIsAssumedToBe500WhenChainFails() public void statusIsAssumedToBe500WhenChainFails()
throws ServletException, IOException { throws ServletException, IOException {
try { assertThatIOException()
this.filter.doFilter(new MockHttpServletRequest(), .isThrownBy(() -> this.filter.doFilter(new MockHttpServletRequest(),
new MockHttpServletResponse(), new MockFilterChain(new HttpServlet() { new MockHttpServletResponse(),
new MockFilterChain(new HttpServlet() {
@Override
protected void service(HttpServletRequest req, @Override
HttpServletResponse resp) protected void service(HttpServletRequest req,
throws ServletException, IOException { HttpServletResponse resp)
throw new IOException(); throws ServletException, IOException {
} throw new IOException();
}
}));
fail("Filter swallowed IOException"); })))
} .satisfies((ex) -> {
catch (IOException ex) { assertThat(this.repository.findAll()).hasSize(1);
assertThat(this.repository.findAll()).hasSize(1); assertThat(this.repository.findAll().get(0).getResponse().getStatus())
assertThat(this.repository.findAll().get(0).getResponse().getStatus()) .isEqualTo(500);
.isEqualTo(500); });
}
} }
@Test @Test
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -31,7 +31,7 @@ import org.springframework.context.annotation.ImportSelector; ...@@ -31,7 +31,7 @@ import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata; import org.springframework.core.type.AnnotationMetadata;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests for {@link OnBeanCondition} when deduction of the bean's type fails * Tests for {@link OnBeanCondition} when deduction of the bean's type fails
...@@ -44,21 +44,20 @@ public class OnBeanConditionTypeDeductionFailureTests { ...@@ -44,21 +44,20 @@ public class OnBeanConditionTypeDeductionFailureTests {
@Test @Test
public void conditionalOnMissingBeanWithDeducedTypeThatIsPartiallyMissingFromClassPath() { public void conditionalOnMissingBeanWithDeducedTypeThatIsPartiallyMissingFromClassPath() {
try { assertThatExceptionOfType(Exception.class).isThrownBy(
new AnnotationConfigApplicationContext(ImportingConfiguration.class).close(); () -> new AnnotationConfigApplicationContext(ImportingConfiguration.class)
fail("Context refresh was successful"); .close())
} .satisfies((ex) -> {
catch (Exception ex) { Throwable beanTypeDeductionException = findNestedCause(ex,
Throwable beanTypeDeductionException = findNestedCause(ex, BeanTypeDeductionException.class);
BeanTypeDeductionException.class); assertThat(beanTypeDeductionException)
assertThat(beanTypeDeductionException) .hasMessage("Failed to deduce bean type for "
.hasMessage("Failed to deduce bean type for " + OnMissingBeanConfiguration.class.getName()
+ OnMissingBeanConfiguration.class.getName() + ".objectMapper");
+ ".objectMapper"); assertThat(findNestedCause(beanTypeDeductionException,
assertThat(findNestedCause(beanTypeDeductionException, NoClassDefFoundError.class)).isNotNull();
NoClassDefFoundError.class)).isNotNull();
});
}
} }
private Throwable findNestedCause(Throwable ex, Class<? extends Throwable> target) { private Throwable findNestedCause(Throwable ex, Class<? extends Throwable> target) {
......
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -47,7 +47,7 @@ import org.springframework.jdbc.core.JdbcTemplate; ...@@ -47,7 +47,7 @@ import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.ClassUtils; import org.springframework.util.ClassUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests for {@link DataSourceInitializerInvoker}. * Tests for {@link DataSourceInitializerInvoker}.
...@@ -178,16 +178,13 @@ public class DataSourceInitializerInvokerTests { ...@@ -178,16 +178,13 @@ public class DataSourceInitializerInvokerTests {
private void assertDataSourceNotInitialized(DataSource dataSource) { private void assertDataSourceNotInitialized(DataSource dataSource) {
JdbcOperations template = new JdbcTemplate(dataSource); JdbcOperations template = new JdbcTemplate(dataSource);
try { assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(
template.queryForObject("SELECT COUNT(*) from BAR", Integer.class); () -> template.queryForObject("SELECT COUNT(*) from BAR", Integer.class))
fail("Query should have failed as BAR table does not exist"); .satisfies((ex) -> {
} SQLException sqlException = ex.getSQLException();
catch (BadSqlGrammarException ex) { int expectedCode = -5501; // user lacks privilege or object not found
SQLException sqlException = ex.getSQLException(); assertThat(sqlException.getErrorCode()).isEqualTo(expectedCode);
int expectedCode = -5501; // user lacks privilege or object not });
// found
assertThat(sqlException.getErrorCode()).isEqualTo(expectedCode);
}
} }
@Test @Test
......
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -52,7 +52,7 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager; ...@@ -52,7 +52,7 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.PlatformTransactionManager;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests for {@link JooqAutoConfiguration}. * Tests for {@link JooqAutoConfiguration}.
...@@ -90,15 +90,10 @@ public class JooqAutoConfigurationTests { ...@@ -90,15 +90,10 @@ public class JooqAutoConfigurationTests {
"insert into jooqtest (name) values ('foo');")); "insert into jooqtest (name) values ('foo');"));
dsl.transaction(new AssertFetch(dsl, dsl.transaction(new AssertFetch(dsl,
"select count(*) as total from jooqtest;", "1")); "select count(*) as total from jooqtest;", "1"));
try { assertThatExceptionOfType(DataIntegrityViolationException.class)
dsl.transaction(new ExecuteSql(dsl, .isThrownBy(() -> dsl.transaction(new ExecuteSql(dsl,
"insert into jooqtest (name) values ('bar');", "insert into jooqtest (name) values ('bar');",
"insert into jooqtest (name) values ('foo');")); "insert into jooqtest (name) values ('foo');")));
fail("An DataIntegrityViolationException should have been thrown.");
}
catch (DataIntegrityViolationException ex) {
// Ignore
}
dsl.transaction(new AssertFetch(dsl, dsl.transaction(new AssertFetch(dsl,
"select count(*) as total from jooqtest;", "2")); "select count(*) as total from jooqtest;", "2"));
}); });
...@@ -120,19 +115,14 @@ public class JooqAutoConfigurationTests { ...@@ -120,19 +115,14 @@ public class JooqAutoConfigurationTests {
"insert into jooqtest_tx (name) values ('foo');")); "insert into jooqtest_tx (name) values ('foo');"));
dsl.transaction(new AssertFetch(dsl, dsl.transaction(new AssertFetch(dsl,
"select count(*) as total from jooqtest_tx;", "1")); "select count(*) as total from jooqtest_tx;", "1"));
try { assertThatExceptionOfType(DataIntegrityViolationException.class)
dsl.transaction(new ExecuteSql(dsl, .isThrownBy(() -> dsl.transaction(new ExecuteSql(dsl,
"insert into jooqtest (name) values ('bar');", "insert into jooqtest (name) values ('bar');",
"insert into jooqtest (name) values ('foo');")); "insert into jooqtest (name) values ('foo');")));
fail("A DataIntegrityViolationException should have been thrown.");
}
catch (DataIntegrityViolationException ex) {
// Ignore
}
dsl.transaction(new AssertFetch(dsl, dsl.transaction(new AssertFetch(dsl,
"select count(*) as total from jooqtest_tx;", "1")); "select count(*) as total from jooqtest_tx;", "1"));
}); });
} }
@Test @Test
......
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -42,8 +42,8 @@ import org.springframework.mock.web.MockServletContext; ...@@ -42,8 +42,8 @@ import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat; 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.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.fail;
/** /**
* Tests for {@link ConditionEvaluationReportLoggingListener}. * Tests for {@link ConditionEvaluationReportLoggingListener}.
...@@ -76,15 +76,10 @@ public class ConditionEvaluationReportLoggingListenerTests { ...@@ -76,15 +76,10 @@ public class ConditionEvaluationReportLoggingListenerTests {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
this.initializer.initialize(context); this.initializer.initialize(context);
context.register(ErrorConfig.class); context.register(ErrorConfig.class);
try { assertThatExceptionOfType(Exception.class).isThrownBy(context::refresh).satisfies(
context.refresh(); (ex) -> withDebugLogging(() -> this.initializer.onApplicationEvent(
fail("Did not error"); new ApplicationFailedEvent(new SpringApplication(), new String[0],
} context, ex))));
catch (Exception ex) {
withDebugLogging(
() -> this.initializer.onApplicationEvent(new ApplicationFailedEvent(
new SpringApplication(), new String[0], context, ex)));
}
assertThat(this.outputCapture.toString()) assertThat(this.outputCapture.toString())
.contains("CONDITIONS EVALUATION REPORT"); .contains("CONDITIONS EVALUATION REPORT");
} }
...@@ -94,14 +89,10 @@ public class ConditionEvaluationReportLoggingListenerTests { ...@@ -94,14 +89,10 @@ public class ConditionEvaluationReportLoggingListenerTests {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
this.initializer.initialize(context); this.initializer.initialize(context);
context.register(ErrorConfig.class); context.register(ErrorConfig.class);
try { assertThatExceptionOfType(Exception.class).isThrownBy(context::refresh)
context.refresh(); .satisfies((ex) -> this.initializer.onApplicationEvent(
fail("Did not error"); new ApplicationFailedEvent(new SpringApplication(), new String[0],
} context, ex)));
catch (Exception ex) {
this.initializer.onApplicationEvent(new ApplicationFailedEvent(
new SpringApplication(), new String[0], context, ex));
}
assertThat(this.outputCapture.toString()).contains("Error starting" assertThat(this.outputCapture.toString()).contains("Error starting"
+ " ApplicationContext. To display the conditions report re-run" + " ApplicationContext. To display the conditions report re-run"
+ " your application with 'debug' enabled."); + " your application with 'debug' enabled.");
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -27,7 +27,7 @@ import org.springframework.boot.cli.command.grab.GrabCommand; ...@@ -27,7 +27,7 @@ import org.springframework.boot.cli.command.grab.GrabCommand;
import org.springframework.util.FileSystemUtils; import org.springframework.util.FileSystemUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Integration tests for {@link GrabCommand} * Integration tests for {@link GrabCommand}
...@@ -64,14 +64,10 @@ public class GrabCommandIntegrationTests { ...@@ -64,14 +64,10 @@ public class GrabCommandIntegrationTests {
@Test @Test
public void duplicateDependencyManagementBomAnnotationsProducesAnError() { public void duplicateDependencyManagementBomAnnotationsProducesAnError() {
try { assertThatExceptionOfType(Exception.class)
this.cli.grab("duplicateDependencyManagementBom.groovy"); .isThrownBy(
fail(); () -> this.cli.grab("duplicateDependencyManagementBom.groovy"))
} .withMessageContaining("Duplicate @DependencyManagementBom annotation");
catch (Exception ex) {
assertThat(ex.getMessage())
.contains("Duplicate @DependencyManagementBom annotation");
}
} }
@Test @Test
......
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -28,7 +28,7 @@ import org.junit.Before; ...@@ -28,7 +28,7 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests for {@link SocketTargetServerConnection}. * Tests for {@link SocketTargetServerConnection}.
...@@ -75,16 +75,13 @@ public class SocketTargetServerConnectionTests { ...@@ -75,16 +75,13 @@ public class SocketTargetServerConnectionTests {
this.server.start(); this.server.start();
ByteChannel channel = this.connection.open(10); ByteChannel channel = this.connection.open(10);
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
try { assertThatExceptionOfType(SocketTimeoutException.class)
channel.read(ByteBuffer.allocate(5)); .isThrownBy(() -> channel.read(ByteBuffer.allocate(5)))
fail("No socket timeout thrown"); .satisfies((ex) -> {
} long runTime = System.currentTimeMillis() - startTime;
catch (SocketTimeoutException ex) { assertThat(runTime).isGreaterThanOrEqualTo(10L);
// Expected assertThat(runTime).isLessThan(10000L);
long runTime = System.currentTimeMillis() - startTime; });
assertThat(runTime).isGreaterThanOrEqualTo(10L);
assertThat(runTime).isLessThan(10000L);
}
} }
private static class MockServer { private static class MockServer {
...@@ -162,7 +159,7 @@ public class SocketTargetServerConnectionTests { ...@@ -162,7 +159,7 @@ public class SocketTargetServerConnectionTests {
channel.close(); channel.close();
} }
catch (Exception ex) { catch (Exception ex) {
fail(); throw new RuntimeException(ex);
} }
} }
......
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -31,7 +31,7 @@ import org.springframework.security.test.context.support.WithMockUser; ...@@ -31,7 +31,7 @@ import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests for {@link WebMvcTest} with {@link WebDriver}. * Tests for {@link WebMvcTest} with {@link WebDriver}.
...@@ -62,13 +62,8 @@ public class WebMvcTestWebDriverIntegrationTests { ...@@ -62,13 +62,8 @@ public class WebMvcTestWebDriverIntegrationTests {
this.webDriver.get("/html"); this.webDriver.get("/html");
WebElement element = this.webDriver.findElement(By.tagName("body")); WebElement element = this.webDriver.findElement(By.tagName("body"));
assertThat(element.getText()).isEqualTo("Hello"); assertThat(element.getText()).isEqualTo("Hello");
try { assertThatExceptionOfType(NoSuchWindowException.class)
previousWebDriver.getWindowHandle(); .isThrownBy(previousWebDriver::getWindowHandle);
fail("Did not call quit()");
}
catch (NoSuchWindowException ex) {
// Expected
}
assertThat(previousWebDriver).isNotNull().isNotSameAs(this.webDriver); assertThat(previousWebDriver).isNotNull().isNotSameAs(this.webDriver);
} }
......
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -37,8 +37,8 @@ import org.springframework.core.type.AnnotatedTypeMetadata; ...@@ -37,8 +37,8 @@ import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.ClassUtils; import org.springframework.util.ClassUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIOException; import static org.assertj.core.api.Assertions.assertThatIOException;
import static org.junit.Assert.fail;
/** /**
* Abstract tests for {@link AbstractApplicationContextRunner} implementations. * Abstract tests for {@link AbstractApplicationContextRunner} implementations.
...@@ -153,14 +153,11 @@ public abstract class AbstractApplicationContextRunnerTests<T extends AbstractAp ...@@ -153,14 +153,11 @@ public abstract class AbstractApplicationContextRunnerTests<T extends AbstractAp
public void runWithClassLoaderShouldSetClassLoaderOnContext() { public void runWithClassLoaderShouldSetClassLoaderOnContext() {
get().withClassLoader(new FilteredClassLoader(Gson.class.getPackage().getName())) get().withClassLoader(new FilteredClassLoader(Gson.class.getPackage().getName()))
.run((context) -> { .run((context) -> {
try { assertThatExceptionOfType(ClassNotFoundException.class)
ClassUtils.forName(Gson.class.getName(), .isThrownBy(() -> {
context.getClassLoader()); ClassUtils.forName(Gson.class.getName(),
fail("Should have thrown a ClassNotFoundException"); context.getClassLoader());
} });
catch (ClassNotFoundException ex) {
// expected
}
}); });
} }
......
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -107,7 +107,6 @@ import static org.assertj.core.api.Assertions.assertThat; ...@@ -107,7 +107,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.isA; import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.BDDMockito.willThrow; import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.atLeastOnce;
...@@ -770,17 +769,11 @@ public class SpringApplicationTests { ...@@ -770,17 +769,11 @@ public class SpringApplicationTests {
ExitStatusException failure = new ExitStatusException(); ExitStatusException failure = new ExitStatusException();
willThrow(failure).given(listener) willThrow(failure).given(listener)
.onApplicationEvent(isA(ApplicationReadyEvent.class)); .onApplicationEvent(isA(ApplicationReadyEvent.class));
try { assertThatExceptionOfType(RuntimeException.class).isThrownBy(application::run);
application.run(); verify(listener).onApplicationEvent(isA(ApplicationReadyEvent.class));
fail("Run should have failed with a RuntimeException"); verify(listener, never()).onApplicationEvent(isA(ApplicationFailedEvent.class));
} assertThat(exitCodeListener.getExitCode()).isEqualTo(11);
catch (RuntimeException ex) { assertThat(this.output.toString()).contains("Application run failed");
verify(listener).onApplicationEvent(isA(ApplicationReadyEvent.class));
verify(listener, never())
.onApplicationEvent(isA(ApplicationFailedEvent.class));
assertThat(exitCodeListener.getExitCode()).isEqualTo(11);
assertThat(this.output.toString()).contains("Application run failed");
}
} }
@Test @Test
...@@ -855,12 +848,7 @@ public class SpringApplicationTests { ...@@ -855,12 +848,7 @@ public class SpringApplicationTests {
ExitCodeListener listener = new ExitCodeListener(); ExitCodeListener listener = new ExitCodeListener();
application.addListeners(listener); application.addListeners(listener);
application.setWebApplicationType(WebApplicationType.NONE); application.setWebApplicationType(WebApplicationType.NONE);
try { assertThatIllegalStateException().isThrownBy(application::run);
application.run();
fail("Did not throw");
}
catch (IllegalStateException ex) {
}
verify(handler).registerExitCode(11); verify(handler).registerExitCode(11);
assertThat(listener.getExitCode()).isEqualTo(11); assertThat(listener.getExitCode()).isEqualTo(11);
} }
...@@ -880,12 +868,7 @@ public class SpringApplicationTests { ...@@ -880,12 +868,7 @@ public class SpringApplicationTests {
ExitCodeListener listener = new ExitCodeListener(); ExitCodeListener listener = new ExitCodeListener();
application.addListeners(listener); application.addListeners(listener);
application.setWebApplicationType(WebApplicationType.NONE); application.setWebApplicationType(WebApplicationType.NONE);
try { assertThatIllegalStateException().isThrownBy(application::run);
application.run();
fail("Did not throw");
}
catch (IllegalStateException ex) {
}
verify(handler).registerExitCode(11); verify(handler).registerExitCode(11);
assertThat(listener.getExitCode()).isEqualTo(11); assertThat(listener.getExitCode()).isEqualTo(11);
} }
...@@ -905,12 +888,7 @@ public class SpringApplicationTests { ...@@ -905,12 +888,7 @@ public class SpringApplicationTests {
ExitCodeListener listener = new ExitCodeListener(); ExitCodeListener listener = new ExitCodeListener();
application.addListeners(listener); application.addListeners(listener);
application.setWebApplicationType(WebApplicationType.NONE); application.setWebApplicationType(WebApplicationType.NONE);
try { assertThatExceptionOfType(RuntimeException.class).isThrownBy(application::run);
application.run();
fail("Did not throw");
}
catch (RuntimeException ex) {
}
ArgumentCaptor<RuntimeException> exceptionCaptor = ArgumentCaptor ArgumentCaptor<RuntimeException> exceptionCaptor = ArgumentCaptor
.forClass(RuntimeException.class); .forClass(RuntimeException.class);
verify(handler).registerLoggedException(exceptionCaptor.capture()); verify(handler).registerLoggedException(exceptionCaptor.capture());
...@@ -998,16 +976,12 @@ public class SpringApplicationTests { ...@@ -998,16 +976,12 @@ public class SpringApplicationTests {
ApplicationListener<ApplicationEvent> listener = mock(ApplicationListener.class); ApplicationListener<ApplicationEvent> listener = mock(ApplicationListener.class);
SpringApplication application = new SpringApplication(ExampleConfig.class); SpringApplication application = new SpringApplication(ExampleConfig.class);
application.addListeners(listener); application.addListeners(listener);
try { assertThatExceptionOfType(ApplicationContextException.class)
application.run(); .isThrownBy(application::run);
fail("Run should have failed with an ApplicationContextException"); verifyListenerEvents(listener, ApplicationStartingEvent.class,
} ApplicationEnvironmentPreparedEvent.class,
catch (ApplicationContextException ex) { ApplicationContextInitializedEvent.class, ApplicationPreparedEvent.class,
verifyListenerEvents(listener, ApplicationStartingEvent.class, ApplicationFailedEvent.class);
ApplicationEnvironmentPreparedEvent.class,
ApplicationContextInitializedEvent.class,
ApplicationPreparedEvent.class, ApplicationFailedEvent.class);
}
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
...@@ -1018,16 +992,12 @@ public class SpringApplicationTests { ...@@ -1018,16 +992,12 @@ public class SpringApplicationTests {
BrokenPostConstructConfig.class); BrokenPostConstructConfig.class);
application.setWebApplicationType(WebApplicationType.NONE); application.setWebApplicationType(WebApplicationType.NONE);
application.addListeners(listener); application.addListeners(listener);
try { assertThatExceptionOfType(BeanCreationException.class)
application.run(); .isThrownBy(application::run);
fail("Run should have failed with a BeanCreationException"); verifyListenerEvents(listener, ApplicationStartingEvent.class,
} ApplicationEnvironmentPreparedEvent.class,
catch (BeanCreationException ex) { ApplicationContextInitializedEvent.class, ApplicationPreparedEvent.class,
verifyListenerEvents(listener, ApplicationStartingEvent.class, ApplicationFailedEvent.class);
ApplicationEnvironmentPreparedEvent.class,
ApplicationContextInitializedEvent.class,
ApplicationPreparedEvent.class, ApplicationFailedEvent.class);
}
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
...@@ -1038,13 +1008,9 @@ public class SpringApplicationTests { ...@@ -1038,13 +1008,9 @@ public class SpringApplicationTests {
SpringApplication application = new SpringApplication(ExampleConfig.class); SpringApplication application = new SpringApplication(ExampleConfig.class);
application.addInitializers((applicationContext) -> applicationContext application.addInitializers((applicationContext) -> applicationContext
.addApplicationListener(listener)); .addApplicationListener(listener));
try { assertThatExceptionOfType(ApplicationContextException.class)
application.run(); .isThrownBy(application::run);
fail("Run should have failed with an ApplicationContextException"); verifyListenerEvents(listener, ApplicationFailedEvent.class);
}
catch (ApplicationContextException ex) {
verifyListenerEvents(listener, ApplicationFailedEvent.class);
}
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
...@@ -1056,13 +1022,9 @@ public class SpringApplicationTests { ...@@ -1056,13 +1022,9 @@ public class SpringApplicationTests {
application.setWebApplicationType(WebApplicationType.NONE); application.setWebApplicationType(WebApplicationType.NONE);
application.addInitializers((applicationContext) -> applicationContext application.addInitializers((applicationContext) -> applicationContext
.addApplicationListener(listener)); .addApplicationListener(listener));
try { assertThatExceptionOfType(BeanCreationException.class)
application.run(); .isThrownBy(application::run);
fail("Run should have failed with a BeanCreationException"); verifyListenerEvents(listener, ApplicationFailedEvent.class);
}
catch (BeanCreationException ex) {
verifyListenerEvents(listener, ApplicationFailedEvent.class);
}
} }
@Test @Test
......
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -82,7 +82,6 @@ import static org.assertj.core.api.Assertions.assertThat; ...@@ -82,7 +82,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.entry; import static org.assertj.core.api.Assertions.entry;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
...@@ -702,15 +701,13 @@ public class ConfigurationPropertiesTests { ...@@ -702,15 +701,13 @@ public class ConfigurationPropertiesTests {
@Test @Test
public void loadWhenHasConfigurationPropertiesValidatorShouldApplyValidator() { public void loadWhenHasConfigurationPropertiesValidatorShouldApplyValidator() {
try { assertThatExceptionOfType(Exception.class)
load(WithCustomValidatorConfiguration.class); .isThrownBy(() -> load(WithCustomValidatorConfiguration.class))
fail("Did not throw"); .satisfies((ex) -> {
} assertThat(ex).hasCauseInstanceOf(BindException.class);
catch (Exception ex) { assertThat(ex.getCause())
assertThat(ex).hasCauseInstanceOf(BindException.class); .hasCauseExactlyInstanceOf(BindValidationException.class);
assertThat(ex.getCause()) });
.hasCauseExactlyInstanceOf(BindValidationException.class);
}
} }
@Test @Test
...@@ -723,15 +720,12 @@ public class ConfigurationPropertiesTests { ...@@ -723,15 +720,12 @@ public class ConfigurationPropertiesTests {
@Test @Test
public void loadWhenConfigurationPropertiesIsAlsoValidatorShouldApplyValidator() { public void loadWhenConfigurationPropertiesIsAlsoValidatorShouldApplyValidator() {
try { assertThatExceptionOfType(Exception.class)
load(ValidatorProperties.class); .isThrownBy(() -> load(ValidatorProperties.class)).satisfies((ex) -> {
fail("Did not throw"); assertThat(ex).hasCauseInstanceOf(BindException.class);
} assertThat(ex.getCause())
catch (Exception ex) { .hasCauseExactlyInstanceOf(BindValidationException.class);
assertThat(ex).hasCauseInstanceOf(BindException.class); });
assertThat(ex.getCause())
.hasCauseExactlyInstanceOf(BindValidationException.class);
}
} }
@Test @Test
......
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -32,7 +32,7 @@ import org.springframework.boot.context.properties.source.MockConfigurationPrope ...@@ -32,7 +32,7 @@ import org.springframework.boot.context.properties.source.MockConfigurationPrope
import org.springframework.core.ResolvableType; import org.springframework.core.ResolvableType;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA; import static org.mockito.ArgumentMatchers.isA;
...@@ -145,18 +145,16 @@ public class ArrayBinderTests { ...@@ -145,18 +145,16 @@ public class ArrayBinderTests {
source.put("foo[1]", "1"); source.put("foo[1]", "1");
source.put("foo[3]", "3"); source.put("foo[3]", "3");
this.sources.add(source); this.sources.add(source);
try { assertThatExceptionOfType(BindException.class)
this.binder.bind("foo", INTEGER_ARRAY); .isThrownBy(() -> this.binder.bind("foo", INTEGER_ARRAY))
fail("No exception thrown"); .satisfies((ex) -> {
} Set<ConfigurationProperty> unbound = ((UnboundConfigurationPropertiesException) ex
catch (BindException ex) { .getCause()).getUnboundProperties();
Set<ConfigurationProperty> unbound = ((UnboundConfigurationPropertiesException) ex assertThat(unbound.size()).isEqualTo(1);
.getCause()).getUnboundProperties(); ConfigurationProperty property = unbound.iterator().next();
assertThat(unbound.size()).isEqualTo(1); assertThat(property.getName().toString()).isEqualTo("foo[3]");
ConfigurationProperty property = unbound.iterator().next(); assertThat(property.getValue()).isEqualTo("3");
assertThat(property.getName().toString()).isEqualTo("foo[3]"); });
assertThat(property.getValue()).isEqualTo("3");
}
} }
@Test @Test
......
...@@ -38,7 +38,7 @@ import org.springframework.core.env.StandardEnvironment; ...@@ -38,7 +38,7 @@ import org.springframework.core.env.StandardEnvironment;
import org.springframework.test.context.support.TestPropertySourceUtils; import org.springframework.test.context.support.TestPropertySourceUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests for {@link CollectionBinder}. * Tests for {@link CollectionBinder}.
...@@ -121,18 +121,16 @@ public class CollectionBinderTests { ...@@ -121,18 +121,16 @@ public class CollectionBinderTests {
source.put("foo[1]", "1"); source.put("foo[1]", "1");
source.put("foo[3]", "3"); source.put("foo[3]", "3");
this.sources.add(source); this.sources.add(source);
try { assertThatExceptionOfType(BindException.class)
this.binder.bind("foo", INTEGER_LIST); .isThrownBy(() -> this.binder.bind("foo", INTEGER_LIST))
fail("No exception thrown"); .satisfies((ex) -> {
} Set<ConfigurationProperty> unbound = ((UnboundConfigurationPropertiesException) ex
catch (BindException ex) { .getCause()).getUnboundProperties();
Set<ConfigurationProperty> unbound = ((UnboundConfigurationPropertiesException) ex assertThat(unbound).hasSize(1);
.getCause()).getUnboundProperties(); ConfigurationProperty property = unbound.iterator().next();
assertThat(unbound).hasSize(1); assertThat(property.getName().toString()).isEqualTo("foo[3]");
ConfigurationProperty property = unbound.iterator().next(); assertThat(property.getValue()).isEqualTo("3");
assertThat(property.getName().toString()).isEqualTo("foo[3]"); });
assertThat(property.getValue()).isEqualTo("3");
}
} }
@Test @Test
...@@ -142,19 +140,16 @@ public class CollectionBinderTests { ...@@ -142,19 +140,16 @@ public class CollectionBinderTests {
source.put("foo[1].value", "2"); source.put("foo[1].value", "2");
source.put("foo[4].value", "4"); source.put("foo[4].value", "4");
this.sources.add(source); this.sources.add(source);
try { Bindable<List<JavaBean>> target = Bindable.listOf(JavaBean.class);
Bindable<List<JavaBean>> target = Bindable.listOf(JavaBean.class); assertThatExceptionOfType(BindException.class)
this.binder.bind("foo", target); .isThrownBy(() -> this.binder.bind("foo", target)).satisfies((ex) -> {
fail("No exception thrown"); Set<ConfigurationProperty> unbound = ((UnboundConfigurationPropertiesException) ex
} .getCause()).getUnboundProperties();
catch (BindException ex) { assertThat(unbound).hasSize(1);
Set<ConfigurationProperty> unbound = ((UnboundConfigurationPropertiesException) ex ConfigurationProperty property = unbound.iterator().next();
.getCause()).getUnboundProperties(); assertThat(property.getName().toString()).isEqualTo("foo[4].value");
assertThat(unbound).hasSize(1); assertThat(property.getValue()).isEqualTo("4");
ConfigurationProperty property = unbound.iterator().next(); });
assertThat(property.getName().toString()).isEqualTo("foo[4].value");
assertThat(property.getValue()).isEqualTo("4");
}
} }
@Test @Test
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -30,7 +30,7 @@ import org.springframework.boot.context.properties.source.ConfigurationPropertyS ...@@ -30,7 +30,7 @@ import org.springframework.boot.context.properties.source.ConfigurationPropertyS
import org.springframework.boot.context.properties.source.MockConfigurationPropertySource; import org.springframework.boot.context.properties.source.MockConfigurationPropertySource;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests for {@link NoUnboundElementsBindHandler}. * Tests for {@link NoUnboundElementsBindHandler}.
...@@ -75,15 +75,11 @@ public class NoUnboundElementsBindHandlerTests { ...@@ -75,15 +75,11 @@ public class NoUnboundElementsBindHandlerTests {
source.put("example.baz", "bar"); source.put("example.baz", "bar");
this.sources.add(source); this.sources.add(source);
this.binder = new Binder(this.sources); this.binder = new Binder(this.sources);
try { assertThatExceptionOfType(BindException.class)
this.binder.bind("example", Bindable.of(Example.class), .isThrownBy(() -> this.binder.bind("example", Bindable.of(Example.class),
new NoUnboundElementsBindHandler()); new NoUnboundElementsBindHandler()))
fail("did not throw"); .satisfies((ex) -> assertThat(ex.getCause().getMessage())
} .contains("The elements [example.baz] were left unbound"));
catch (BindException ex) {
assertThat(ex.getCause().getMessage())
.contains("The elements [example.baz] were left unbound");
}
} }
@Test @Test
......
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -28,7 +28,6 @@ import org.springframework.boot.context.properties.source.ConfigurationPropertyN ...@@ -28,7 +28,6 @@ import org.springframework.boot.context.properties.source.ConfigurationPropertyN
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.fail;
/** /**
* Tests for {@link ConfigurationPropertyName}. * Tests for {@link ConfigurationPropertyName}.
...@@ -78,13 +77,9 @@ public class ConfigurationPropertyNameTests { ...@@ -78,13 +77,9 @@ public class ConfigurationPropertyNameTests {
public void ofNameShouldNotContainInvalidChars() { public void ofNameShouldNotContainInvalidChars() {
String invalid = "_@$%*+=':;"; String invalid = "_@$%*+=':;";
for (char c : invalid.toCharArray()) { for (char c : invalid.toCharArray()) {
try { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class)
ConfigurationPropertyName.of("foo" + c); .isThrownBy(() -> ConfigurationPropertyName.of("foo" + c)).satisfies(
fail("Did not throw for invalid char " + c); (ex) -> assertThat(ex.getMessage()).contains("is not valid"));
}
catch (InvalidConfigurationPropertyNameException ex) {
assertThat(ex.getMessage()).contains("is not valid");
}
} }
} }
......
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -23,7 +23,6 @@ import org.junit.Test; ...@@ -23,7 +23,6 @@ import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.fail;
/** /**
* Tests for {@link DurationStyle}. * Tests for {@link DurationStyle}.
...@@ -243,13 +242,10 @@ public class DurationStyleTests { ...@@ -243,13 +242,10 @@ public class DurationStyleTests {
@Test @Test
public void parseSimpleWhenUnknownUnitShouldThrowException() { public void parseSimpleWhenUnknownUnitShouldThrowException() {
try { assertThatIllegalArgumentException()
DurationStyle.SIMPLE.parse("10mb"); .isThrownBy(() -> DurationStyle.SIMPLE.parse("10mb"))
fail("Did not throw"); .satisfies((ex) -> assertThat(ex.getCause().getMessage())
} .isEqualTo("Unknown unit 'mb'"));
catch (IllegalArgumentException ex) {
assertThat(ex.getCause().getMessage()).isEqualTo("Unknown unit 'mb'");
}
} }
@Test @Test
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -28,7 +28,7 @@ import org.springframework.boot.web.server.PortInUseException; ...@@ -28,7 +28,7 @@ import org.springframework.boot.web.server.PortInUseException;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Integration tests for {@link FailureAnalyzers}. * Integration tests for {@link FailureAnalyzers}.
...@@ -42,15 +42,10 @@ public class FailureAnalyzersIntegrationTests { ...@@ -42,15 +42,10 @@ public class FailureAnalyzersIntegrationTests {
@Test @Test
public void analysisIsPerformed() { public void analysisIsPerformed() {
try { assertThatExceptionOfType(Exception.class)
new SpringApplicationBuilder(TestConfiguration.class) .isThrownBy(() -> new SpringApplicationBuilder(TestConfiguration.class)
.web(WebApplicationType.NONE).run(); .web(WebApplicationType.NONE).run());
fail("Application started successfully"); assertThat(this.outputCapture.toString()).contains("APPLICATION FAILED TO START");
}
catch (Exception ex) {
assertThat(this.outputCapture.toString())
.contains("APPLICATION FAILED TO START");
}
} }
@Configuration @Configuration
......
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -21,14 +21,13 @@ import org.junit.runner.RunWith; ...@@ -21,14 +21,13 @@ import org.junit.runner.RunWith;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.diagnostics.FailureAnalysis;
import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions;
import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests for {@link ValidationExceptionFailureAnalyzer} * Tests for {@link ValidationExceptionFailureAnalyzer}
...@@ -41,15 +40,12 @@ public class ValidationExceptionFailureAnalyzerTests { ...@@ -41,15 +40,12 @@ public class ValidationExceptionFailureAnalyzerTests {
@Test @Test
public void validatedPropertiesTest() { public void validatedPropertiesTest() {
try { assertThatExceptionOfType(Exception.class)
new AnnotationConfigApplicationContext(TestConfiguration.class).close(); .isThrownBy(() -> new AnnotationConfigApplicationContext(
fail("Expected failure did not occur"); TestConfiguration.class).close())
} .satisfies((ex) -> assertThat(
catch (Exception ex) { new ValidationExceptionFailureAnalyzer().analyze(ex))
FailureAnalysis analysis = new ValidationExceptionFailureAnalyzer() .isNotNull());
.analyze(ex);
assertThat(analysis).isNotNull();
}
} }
@Test @Test
......
...@@ -34,6 +34,7 @@ import org.springframework.boot.web.server.Ssl; ...@@ -34,6 +34,7 @@ import org.springframework.boot.web.server.Ssl;
import org.springframework.boot.web.server.WebServerException; import org.springframework.boot.web.server.WebServerException;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests for {@link SslServerCustomizer}. * Tests for {@link SslServerCustomizer}.
...@@ -85,13 +86,14 @@ public class SslServerCustomizerTests { ...@@ -85,13 +86,14 @@ public class SslServerCustomizerTests {
throws Exception { throws Exception {
Ssl ssl = new Ssl(); Ssl ssl = new Ssl();
SslServerCustomizer customizer = new SslServerCustomizer(null, ssl, null, null); SslServerCustomizer customizer = new SslServerCustomizer(null, ssl, null, null);
try { assertThatExceptionOfType(Exception.class)
customizer.configureSsl(new SslContextFactory(), ssl, null); .isThrownBy(
} () -> customizer.configureSsl(new SslContextFactory(), ssl, null))
catch (Exception ex) { .satisfies((ex) -> {
assertThat(ex).isInstanceOf(WebServerException.class); assertThat(ex).isInstanceOf(WebServerException.class);
assertThat(ex).hasMessageContaining("Could not load key store 'null'"); assertThat(ex)
} .hasMessageContaining("Could not load key store 'null'");
});
} }
private Server createCustomizedServer() { private Server createCustomizedServer() {
......
...@@ -23,8 +23,7 @@ import org.junit.Test; ...@@ -23,8 +23,7 @@ import org.junit.Test;
import org.springframework.boot.web.server.Ssl; import org.springframework.boot.web.server.Ssl;
import org.springframework.boot.web.server.WebServerException; import org.springframework.boot.web.server.WebServerException;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.fail;
/** /**
* Tests for {@link SslServerCustomizer}. * Tests for {@link SslServerCustomizer}.
...@@ -41,15 +40,10 @@ public class SslServerCustomizerTests { ...@@ -41,15 +40,10 @@ public class SslServerCustomizerTests {
ssl.setKeyStore("src/test/resources/test.jks"); ssl.setKeyStore("src/test/resources/test.jks");
ssl.setKeyStoreProvider("com.example.KeyStoreProvider"); ssl.setKeyStoreProvider("com.example.KeyStoreProvider");
SslServerCustomizer customizer = new SslServerCustomizer(ssl, null, null); SslServerCustomizer customizer = new SslServerCustomizer(ssl, null, null);
try { assertThatIllegalStateException()
customizer.getKeyManagerFactory(ssl, null); .isThrownBy(() -> customizer.getKeyManagerFactory(ssl, null))
fail(); .withCauseInstanceOf(NoSuchProviderException.class)
} .withMessageContaining("com.example.KeyStoreProvider");
catch (IllegalStateException ex) {
Throwable cause = ex.getCause();
assertThat(cause).isInstanceOf(NoSuchProviderException.class);
assertThat(cause).hasMessageContaining("com.example.KeyStoreProvider");
}
} }
@Test @Test
...@@ -59,15 +53,10 @@ public class SslServerCustomizerTests { ...@@ -59,15 +53,10 @@ public class SslServerCustomizerTests {
ssl.setTrustStore("src/test/resources/test.jks"); ssl.setTrustStore("src/test/resources/test.jks");
ssl.setTrustStoreProvider("com.example.TrustStoreProvider"); ssl.setTrustStoreProvider("com.example.TrustStoreProvider");
SslServerCustomizer customizer = new SslServerCustomizer(ssl, null, null); SslServerCustomizer customizer = new SslServerCustomizer(ssl, null, null);
try { assertThatIllegalStateException()
customizer.getTrustManagerFactory(ssl, null); .isThrownBy(() -> customizer.getTrustManagerFactory(ssl, null))
fail(); .withCauseInstanceOf(NoSuchProviderException.class)
} .withMessageContaining("com.example.TrustStoreProvider");
catch (IllegalStateException ex) {
Throwable cause = ex.getCause();
assertThat(cause).isInstanceOf(NoSuchProviderException.class);
assertThat(cause).hasMessageContaining("com.example.TrustStoreProvider");
}
} }
@Test @Test
...@@ -75,15 +64,10 @@ public class SslServerCustomizerTests { ...@@ -75,15 +64,10 @@ public class SslServerCustomizerTests {
throws Exception { throws Exception {
Ssl ssl = new Ssl(); Ssl ssl = new Ssl();
SslServerCustomizer customizer = new SslServerCustomizer(ssl, null, null); SslServerCustomizer customizer = new SslServerCustomizer(ssl, null, null);
try { assertThatIllegalStateException()
customizer.getKeyManagerFactory(ssl, null); .isThrownBy(() -> customizer.getKeyManagerFactory(ssl, null))
fail(); .withCauseInstanceOf(WebServerException.class)
} .withMessageContaining("Could not load key store 'null'");
catch (IllegalStateException ex) {
Throwable cause = ex.getCause();
assertThat(cause).isInstanceOf(WebServerException.class);
assertThat(cause).hasMessageContaining("Could not load key store 'null'");
}
} }
} }
...@@ -43,7 +43,7 @@ import org.springframework.core.io.Resource; ...@@ -43,7 +43,7 @@ import org.springframework.core.io.Resource;
import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
...@@ -193,15 +193,10 @@ public class SslConnectorCustomizerTests { ...@@ -193,15 +193,10 @@ public class SslConnectorCustomizerTests {
@Test @Test
public void customizeWhenSslIsEnabledWithNoKeyStoreThrowsWebServerException() { public void customizeWhenSslIsEnabledWithNoKeyStoreThrowsWebServerException() {
try { assertThatExceptionOfType(WebServerException.class)
new SslConnectorCustomizer(new Ssl(), null) .isThrownBy(() -> new SslConnectorCustomizer(new Ssl(), null)
.customize(this.tomcat.getConnector()); .customize(this.tomcat.getConnector()))
fail(); .withMessageContaining("Could not load key store 'null'");
}
catch (Exception ex) {
assertThat(ex).isInstanceOf(WebServerException.class);
assertThat(ex).hasMessageContaining("Could not load key store 'null'");
}
} }
private KeyStore loadStore() throws KeyStoreException, IOException, private KeyStore loadStore() throws KeyStoreException, IOException,
......
...@@ -65,7 +65,6 @@ import org.springframework.test.util.ReflectionTestUtils; ...@@ -65,7 +65,6 @@ import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
...@@ -277,19 +276,14 @@ public class TomcatServletWebServerFactoryTests ...@@ -277,19 +276,14 @@ public class TomcatServletWebServerFactoryTests
} }
@Test @Test
public void primaryConnectorPortClashThrowsIllegalStateException() public void primaryConnectorPortClashThrowsWebServerException() throws IOException {
throws IOException {
doWithBlockedPort((port) -> { doWithBlockedPort((port) -> {
TomcatServletWebServerFactory factory = getFactory(); TomcatServletWebServerFactory factory = getFactory();
factory.setPort(port); factory.setPort(port);
try { assertThatExceptionOfType(WebServerException.class).isThrownBy(() -> {
this.webServer = factory.getWebServer(); this.webServer = factory.getWebServer();
this.webServer.start(); this.webServer.start();
fail(); });
}
catch (WebServerException ex) {
// Ignore
}
}); });
} }
......
...@@ -28,7 +28,7 @@ import org.springframework.boot.web.server.WebServerException; ...@@ -28,7 +28,7 @@ import org.springframework.boot.web.server.WebServerException;
import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/** /**
* Tests for {@link SslBuilderCustomizer} * Tests for {@link SslBuilderCustomizer}
...@@ -60,15 +60,11 @@ public class SslBuilderCustomizerTests { ...@@ -60,15 +60,11 @@ public class SslBuilderCustomizerTests {
ssl.setKeyStoreProvider("com.example.KeyStoreProvider"); ssl.setKeyStoreProvider("com.example.KeyStoreProvider");
SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080, SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080,
InetAddress.getLocalHost(), ssl, null); InetAddress.getLocalHost(), ssl, null);
try { assertThatIllegalStateException()
ReflectionTestUtils.invokeMethod(customizer, "getKeyManagers", ssl, null); .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer,
fail(); "getKeyManagers", ssl, null))
} .withCauseInstanceOf(NoSuchProviderException.class)
catch (IllegalStateException ex) { .withMessageContaining("com.example.KeyStoreProvider");
Throwable cause = ex.getCause();
assertThat(cause).isInstanceOf(NoSuchProviderException.class);
assertThat(cause).hasMessageContaining("com.example.KeyStoreProvider");
}
} }
@Test @Test
...@@ -79,15 +75,11 @@ public class SslBuilderCustomizerTests { ...@@ -79,15 +75,11 @@ public class SslBuilderCustomizerTests {
ssl.setTrustStoreProvider("com.example.TrustStoreProvider"); ssl.setTrustStoreProvider("com.example.TrustStoreProvider");
SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080, SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080,
InetAddress.getLocalHost(), ssl, null); InetAddress.getLocalHost(), ssl, null);
try { assertThatIllegalStateException()
ReflectionTestUtils.invokeMethod(customizer, "getTrustManagers", ssl, null); .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer,
fail(); "getTrustManagers", ssl, null))
} .withCauseInstanceOf(NoSuchProviderException.class)
catch (IllegalStateException ex) { .withMessageContaining("com.example.TrustStoreProvider");
Throwable cause = ex.getCause();
assertThat(cause).isInstanceOf(NoSuchProviderException.class);
assertThat(cause).hasMessageContaining("com.example.TrustStoreProvider");
}
} }
@Test @Test
...@@ -96,15 +88,11 @@ public class SslBuilderCustomizerTests { ...@@ -96,15 +88,11 @@ public class SslBuilderCustomizerTests {
Ssl ssl = new Ssl(); Ssl ssl = new Ssl();
SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080, SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080,
InetAddress.getLocalHost(), ssl, null); InetAddress.getLocalHost(), ssl, null);
try { assertThatIllegalStateException()
ReflectionTestUtils.invokeMethod(customizer, "getKeyManagers", ssl, null); .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer,
fail(); "getKeyManagers", ssl, null))
} .withCauseInstanceOf(WebServerException.class)
catch (IllegalStateException ex) { .withMessageContaining("Could not load key store 'null'");
Throwable cause = ex.getCause();
assertThat(cause).isInstanceOf(WebServerException.class);
assertThat(cause).hasMessageContaining("Could not load key store 'null'");
}
} }
} }
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -911,17 +911,13 @@ public abstract class AbstractServletWebServerFactoryTests { ...@@ -911,17 +911,13 @@ public abstract class AbstractServletWebServerFactoryTests {
public void portClashOfPrimaryConnectorResultsInPortInUseException() public void portClashOfPrimaryConnectorResultsInPortInUseException()
throws IOException { throws IOException {
doWithBlockedPort((port) -> { doWithBlockedPort((port) -> {
try { assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> {
AbstractServletWebServerFactory factory = getFactory(); AbstractServletWebServerFactory factory = getFactory();
factory.setPort(port); factory.setPort(port);
AbstractServletWebServerFactoryTests.this.webServer = factory AbstractServletWebServerFactoryTests.this.webServer = factory
.getWebServer(); .getWebServer();
AbstractServletWebServerFactoryTests.this.webServer.start(); AbstractServletWebServerFactoryTests.this.webServer.start();
fail(); }).satisfies((ex) -> handleExceptionCausedByBlockedPort(ex, port));
}
catch (RuntimeException ex) {
handleExceptionCausedByBlockedPort(ex, port);
}
}); });
} }
...@@ -929,17 +925,13 @@ public abstract class AbstractServletWebServerFactoryTests { ...@@ -929,17 +925,13 @@ public abstract class AbstractServletWebServerFactoryTests {
public void portClashOfSecondaryConnectorResultsInPortInUseException() public void portClashOfSecondaryConnectorResultsInPortInUseException()
throws IOException { throws IOException {
doWithBlockedPort((port) -> { doWithBlockedPort((port) -> {
try { assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> {
AbstractServletWebServerFactory factory = getFactory(); AbstractServletWebServerFactory factory = getFactory();
addConnector(port, factory); addConnector(port, factory);
AbstractServletWebServerFactoryTests.this.webServer = factory AbstractServletWebServerFactoryTests.this.webServer = factory
.getWebServer(); .getWebServer();
AbstractServletWebServerFactoryTests.this.webServer.start(); AbstractServletWebServerFactoryTests.this.webServer.start();
fail(); }).satisfies((ex) -> handleExceptionCausedByBlockedPort(ex, port));
}
catch (RuntimeException ex) {
handleExceptionCausedByBlockedPort(ex, port);
}
}); });
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment