Move tests to JUnit 5 wherever possible

This commit is contained in:
Andy Wilkinson
2019-05-24 11:24:29 +01:00
parent 36f56d034a
commit b18fffaf14
1320 changed files with 13424 additions and 14185 deletions

View File

@@ -17,8 +17,8 @@
package org.springframework.boot.devtools;
import ch.qos.logback.classic.Logger;
import org.junit.After;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
@@ -34,41 +34,41 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
*
* @author Phillip Webb
*/
public class RemoteUrlPropertyExtractorTests {
class RemoteUrlPropertyExtractorTests {
@After
@AfterEach
public void preventRunFailuresFromPollutingLoggerContext() {
((Logger) LoggerFactory.getLogger(RemoteUrlPropertyExtractorTests.class)).getLoggerContext()
.getTurboFilterList().clear();
}
@Test
public void missingUrl() {
void missingUrl() {
assertThatIllegalStateException().isThrownBy(this::doTest).withMessageContaining("No remote URL specified");
}
@Test
public void malformedUrl() {
void malformedUrl() {
assertThatIllegalStateException().isThrownBy(() -> doTest("::://wibble"))
.withMessageContaining("Malformed URL '::://wibble'");
}
@Test
public void multipleUrls() {
void multipleUrls() {
assertThatIllegalStateException().isThrownBy(() -> doTest("http://localhost:8080", "http://localhost:9090"))
.withMessageContaining("Multiple URLs specified");
}
@Test
public void validUrl() {
void validUrl() {
ApplicationContext context = doTest("http://localhost:8080");
assertThat(context.getEnvironment().getProperty("remoteUrl")).isEqualTo("http://localhost:8080");
assertThat(context.getEnvironment().getProperty("spring.thymeleaf.cache")).isNull();
}
@Test
public void cleanValidUrl() {
void cleanValidUrl() {
ApplicationContext context = doTest("http://localhost:8080/");
assertThat(context.getEnvironment().getProperty("remoteUrl")).isEqualTo("http://localhost:8080");
}

View File

@@ -25,7 +25,7 @@ import java.util.function.Supplier;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition;
@@ -48,10 +48,10 @@ import static org.mockito.Mockito.verify;
*
* @author Andy Wilkinson
*/
public abstract class AbstractDevToolsDataSourceAutoConfigurationTests {
abstract class AbstractDevToolsDataSourceAutoConfigurationTests {
@Test
public void singleManuallyConfiguredDataSourceIsNotClosed() throws Exception {
void singleManuallyConfiguredDataSourceIsNotClosed() throws Exception {
ConfigurableApplicationContext context = getContext(() -> createContext(SingleDataSourceConfiguration.class));
DataSource dataSource = context.getBean(DataSource.class);
Statement statement = configureDataSourceBehavior(dataSource);
@@ -59,7 +59,7 @@ public abstract class AbstractDevToolsDataSourceAutoConfigurationTests {
}
@Test
public void multipleDataSourcesAreIgnored() throws Exception {
void multipleDataSourcesAreIgnored() throws Exception {
ConfigurableApplicationContext context = getContext(
() -> createContext(MultipleDataSourcesConfiguration.class));
Collection<DataSource> dataSources = context.getBeansOfType(DataSource.class).values();
@@ -70,7 +70,7 @@ public abstract class AbstractDevToolsDataSourceAutoConfigurationTests {
}
@Test
public void emptyFactoryMethodMetadataIgnored() {
void emptyFactoryMethodMetadataIgnored() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
DataSource dataSource = mock(DataSource.class);
AnnotatedGenericBeanDefinition beanDefinition = new AnnotatedGenericBeanDefinition(dataSource.getClass());

View File

@@ -16,16 +16,16 @@
package org.springframework.boot.devtools.autoconfigure;
import java.io.File;
import java.io.IOException;
import java.sql.Statement;
import javax.sql.DataSource;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
@@ -39,23 +39,20 @@ import static org.mockito.Mockito.verify;
*
* @author Andy Wilkinson
*/
public class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevToolsDataSourceAutoConfigurationTests {
class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevToolsDataSourceAutoConfigurationTests {
@Rule
public final TemporaryFolder temp = new TemporaryFolder();
@Before
public void before() throws IOException {
System.setProperty("derby.stream.error.file", this.temp.newFile("derby.log").getAbsolutePath());
@BeforeEach
public void before(@TempDir File tempDir) throws IOException {
System.setProperty("derby.stream.error.file", new File(tempDir, "derby.log").getAbsolutePath());
}
@After
@AfterEach
public void after() {
System.clearProperty("derby.stream.error.file");
}
@Test
public void autoConfiguredInMemoryDataSourceIsShutdown() throws Exception {
void autoConfiguredInMemoryDataSourceIsShutdown() throws Exception {
ConfigurableApplicationContext context = getContext(
() -> createContext(DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class));
Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class));
@@ -64,7 +61,7 @@ public class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevT
}
@Test
public void autoConfiguredExternalDataSourceIsNotShutdown() throws Exception {
void autoConfiguredExternalDataSourceIsNotShutdown() throws Exception {
ConfigurableApplicationContext context = getContext(() -> createContext("org.postgresql.Driver",
DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class));
Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class));
@@ -73,7 +70,7 @@ public class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevT
}
@Test
public void h2ServerIsNotShutdown() throws Exception {
void h2ServerIsNotShutdown() throws Exception {
ConfigurableApplicationContext context = getContext(() -> createContext("org.h2.Driver",
"jdbc:h2:hsql://localhost", DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class));
Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class));
@@ -82,7 +79,7 @@ public class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevT
}
@Test
public void inMemoryH2IsShutdown() throws Exception {
void inMemoryH2IsShutdown() throws Exception {
ConfigurableApplicationContext context = getContext(() -> createContext("org.h2.Driver", "jdbc:h2:mem:test",
DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class));
Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class));
@@ -91,7 +88,7 @@ public class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevT
}
@Test
public void hsqlServerIsNotShutdown() throws Exception {
void hsqlServerIsNotShutdown() throws Exception {
ConfigurableApplicationContext context = getContext(() -> createContext("org.hsqldb.jdbcDriver",
"jdbc:hsqldb:hsql://localhost", DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class));
Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class));
@@ -100,7 +97,7 @@ public class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevT
}
@Test
public void inMemoryHsqlIsShutdown() throws Exception {
void inMemoryHsqlIsShutdown() throws Exception {
ConfigurableApplicationContext context = getContext(() -> createContext("org.hsqldb.jdbcDriver",
"jdbc:hsqldb:mem:test", DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class));
Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class));
@@ -109,7 +106,7 @@ public class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevT
}
@Test
public void derbyClientIsNotShutdown() throws Exception {
void derbyClientIsNotShutdown() throws Exception {
ConfigurableApplicationContext context = getContext(() -> createContext("org.apache.derby.jdbc.ClientDriver",
"jdbc:derby://localhost", DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class));
Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class));
@@ -118,7 +115,7 @@ public class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevT
}
@Test
public void inMemoryDerbyIsShutdown() throws Exception {
void inMemoryDerbyIsShutdown() throws Exception {
ConfigurableApplicationContext configurableApplicationContext = getContext(
() -> createContext("org.apache.derby.jdbc.EmbeddedDriver", "jdbc:derby:memory:test",
DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class));

View File

@@ -16,7 +16,7 @@
package org.springframework.boot.devtools.autoconfigure;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
@@ -25,12 +25,12 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Stephane Nicoll
*/
public class DevToolsPropertiesTests {
class DevToolsPropertiesTests {
private final DevToolsProperties devToolsProperties = new DevToolsProperties();
@Test
public void additionalExcludeKeepsDefaults() {
void additionalExcludeKeepsDefaults() {
DevToolsProperties.Restart restart = this.devToolsProperties.getRestart();
restart.setAdditionalExclude("foo/**,bar/**");
assertThat(restart.getAllExclude()).containsOnly("META-INF/maven/**", "META-INF/resources/**", "resources/**",
@@ -39,7 +39,7 @@ public class DevToolsPropertiesTests {
}
@Test
public void additionalExcludeNoDefault() {
void additionalExcludeNoDefault() {
DevToolsProperties.Restart restart = this.devToolsProperties.getRestart();
restart.setExclude("");
restart.setAdditionalExclude("foo/**,bar/**");
@@ -47,7 +47,7 @@ public class DevToolsPropertiesTests {
}
@Test
public void additionalExcludeCustomDefault() {
void additionalExcludeCustomDefault() {
DevToolsProperties.Restart restart = this.devToolsProperties.getRestart();
restart.setExclude("biz/**");
restart.setAdditionalExclude("foo/**,bar/**");

View File

@@ -27,9 +27,9 @@ import java.util.function.Supplier;
import org.apache.catalina.Container;
import org.apache.catalina.core.StandardWrapper;
import org.apache.jasper.EmbeddedServletOptions;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
@@ -71,14 +71,12 @@ import static org.mockito.Mockito.verify;
* @author Andy Wilkinson
* @author Vladimir Tsanev
*/
public class LocalDevToolsAutoConfigurationTests {
@Rule
public MockRestarter mockRestarter = new MockRestarter();
@ExtendWith(MockRestarter.class)
class LocalDevToolsAutoConfigurationTests {
private ConfigurableApplicationContext context;
@After
@AfterEach
public void cleanup() {
if (this.context != null) {
this.context.close();
@@ -86,21 +84,21 @@ public class LocalDevToolsAutoConfigurationTests {
}
@Test
public void thymeleafCacheIsFalse() throws Exception {
void thymeleafCacheIsFalse() throws Exception {
this.context = getContext(() -> initializeAndRun(Config.class));
SpringResourceTemplateResolver resolver = this.context.getBean(SpringResourceTemplateResolver.class);
assertThat(resolver.isCacheable()).isFalse();
}
@Test
public void defaultPropertyCanBeOverriddenFromCommandLine() throws Exception {
void defaultPropertyCanBeOverriddenFromCommandLine() throws Exception {
this.context = getContext(() -> initializeAndRun(Config.class, "--spring.thymeleaf.cache=true"));
SpringResourceTemplateResolver resolver = this.context.getBean(SpringResourceTemplateResolver.class);
assertThat(resolver.isCacheable()).isTrue();
}
@Test
public void defaultPropertyCanBeOverriddenFromUserHomeProperties() throws Exception {
void defaultPropertyCanBeOverriddenFromUserHomeProperties() throws Exception {
String userHome = System.getProperty("user.home");
System.setProperty("user.home", new File("src/test/resources/user-home").getAbsolutePath());
try {
@@ -114,21 +112,21 @@ public class LocalDevToolsAutoConfigurationTests {
}
@Test
public void resourceCachePeriodIsZero() throws Exception {
void resourceCachePeriodIsZero() throws Exception {
this.context = getContext(() -> initializeAndRun(WebResourcesConfig.class));
ResourceProperties properties = this.context.getBean(ResourceProperties.class);
assertThat(properties.getCache().getPeriod()).isEqualTo(Duration.ZERO);
}
@Test
public void liveReloadServer() throws Exception {
void liveReloadServer() throws Exception {
this.context = getContext(() -> initializeAndRun(Config.class));
LiveReloadServer server = this.context.getBean(LiveReloadServer.class);
assertThat(server.isStarted()).isTrue();
}
@Test
public void liveReloadTriggeredOnContextRefresh() throws Exception {
void liveReloadTriggeredOnContextRefresh() throws Exception {
this.context = getContext(() -> initializeAndRun(ConfigWithMockLiveReload.class));
LiveReloadServer server = this.context.getBean(LiveReloadServer.class);
reset(server);
@@ -137,7 +135,7 @@ public class LocalDevToolsAutoConfigurationTests {
}
@Test
public void liveReloadTriggeredOnClassPathChangeWithoutRestart() throws Exception {
void liveReloadTriggeredOnClassPathChangeWithoutRestart() throws Exception {
this.context = getContext(() -> initializeAndRun(ConfigWithMockLiveReload.class));
LiveReloadServer server = this.context.getBean(LiveReloadServer.class);
reset(server);
@@ -147,7 +145,7 @@ public class LocalDevToolsAutoConfigurationTests {
}
@Test
public void liveReloadNotTriggeredOnClassPathChangeWithRestart() throws Exception {
void liveReloadNotTriggeredOnClassPathChangeWithRestart() throws Exception {
this.context = getContext(() -> initializeAndRun(ConfigWithMockLiveReload.class));
LiveReloadServer server = this.context.getBean(LiveReloadServer.class);
reset(server);
@@ -157,7 +155,7 @@ public class LocalDevToolsAutoConfigurationTests {
}
@Test
public void liveReloadDisabled() throws Exception {
void liveReloadDisabled() throws Exception {
Map<String, Object> properties = new HashMap<>();
properties.put("spring.devtools.livereload.enabled", false);
this.context = getContext(() -> initializeAndRun(Config.class, properties));
@@ -166,30 +164,30 @@ public class LocalDevToolsAutoConfigurationTests {
}
@Test
public void restartTriggeredOnClassPathChangeWithRestart() throws Exception {
void restartTriggeredOnClassPathChangeWithRestart(Restarter restarter) throws Exception {
this.context = getContext(() -> initializeAndRun(Config.class));
ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, Collections.emptySet(), true);
this.context.publishEvent(event);
verify(this.mockRestarter.getMock()).restart(any(FailureHandler.class));
verify(restarter).restart(any(FailureHandler.class));
}
@Test
public void restartNotTriggeredOnClassPathChangeWithRestart() throws Exception {
void restartNotTriggeredOnClassPathChangeWithRestart(Restarter restarter) throws Exception {
this.context = getContext(() -> initializeAndRun(Config.class));
ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, Collections.emptySet(), false);
this.context.publishEvent(event);
verify(this.mockRestarter.getMock(), never()).restart();
verify(restarter, never()).restart();
}
@Test
public void restartWatchingClassPath() throws Exception {
void restartWatchingClassPath() throws Exception {
this.context = getContext(() -> initializeAndRun(Config.class));
ClassPathFileSystemWatcher watcher = this.context.getBean(ClassPathFileSystemWatcher.class);
assertThat(watcher).isNotNull();
}
@Test
public void restartDisabled() throws Exception {
void restartDisabled() throws Exception {
Map<String, Object> properties = new HashMap<>();
properties.put("spring.devtools.restart.enabled", false);
this.context = getContext(() -> initializeAndRun(Config.class, properties));
@@ -198,7 +196,7 @@ public class LocalDevToolsAutoConfigurationTests {
}
@Test
public void restartWithTriggerFile() throws Exception {
void restartWithTriggerFile() throws Exception {
Map<String, Object> properties = new HashMap<>();
properties.put("spring.devtools.restart.trigger-file", "somefile.txt");
this.context = getContext(() -> initializeAndRun(Config.class, properties));
@@ -209,7 +207,7 @@ public class LocalDevToolsAutoConfigurationTests {
}
@Test
public void watchingAdditionalPaths() throws Exception {
void watchingAdditionalPaths() throws Exception {
Map<String, Object> properties = new HashMap<>();
properties.put("spring.devtools.restart.additional-paths", "src/main/java,src/test/java");
this.context = getContext(() -> initializeAndRun(Config.class, properties));
@@ -222,7 +220,7 @@ public class LocalDevToolsAutoConfigurationTests {
}
@Test
public void devToolsSwitchesJspServletToDevelopmentMode() throws Exception {
void devToolsSwitchesJspServletToDevelopmentMode() throws Exception {
this.context = getContext(() -> initializeAndRun(Config.class));
TomcatWebServer tomcatContainer = (TomcatWebServer) ((ServletWebServerApplicationContext) this.context)
.getWebServer();

View File

@@ -18,8 +18,8 @@ package org.springframework.boot.devtools.autoconfigure;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
@@ -33,18 +33,18 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Madhura Bhave
*/
public class OnEnabledDevToolsConditionTests {
class OnEnabledDevToolsConditionTests {
private AnnotationConfigApplicationContext context;
@Before
@BeforeEach
public void setup() {
this.context = new AnnotationConfigApplicationContext();
this.context.register(TestConfiguration.class);
}
@Test
public void outcomeWhenDevtoolsShouldBeEnabledIsTrueShouldMatch() throws Exception {
void outcomeWhenDevtoolsShouldBeEnabledIsTrueShouldMatch() throws Exception {
AtomicBoolean containsBean = new AtomicBoolean();
Thread thread = new Thread(() -> {
OnEnabledDevToolsConditionTests.this.context.refresh();
@@ -56,7 +56,7 @@ public class OnEnabledDevToolsConditionTests {
}
@Test
public void outcomeWhenDevtoolsShouldBeEnabledIsFalseShouldNotMatch() {
void outcomeWhenDevtoolsShouldBeEnabledIsFalseShouldNotMatch() {
OnEnabledDevToolsConditionTests.this.context.refresh();
assertThat(OnEnabledDevToolsConditionTests.this.context.containsBean("test")).isFalse();
}

View File

@@ -16,7 +16,7 @@
package org.springframework.boot.devtools.autoconfigure;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.devtools.livereload.LiveReloadServer;
@@ -30,17 +30,17 @@ import static org.mockito.Mockito.verify;
*
* @author Phillip Webb
*/
public class OptionalLiveReloadServerTests {
class OptionalLiveReloadServerTests {
@Test
public void nullServer() throws Exception {
void nullServer() throws Exception {
OptionalLiveReloadServer server = new OptionalLiveReloadServer(null);
server.startServer();
server.triggerReload();
}
@Test
public void serverWontStart() throws Exception {
void serverWontStart() throws Exception {
LiveReloadServer delegate = mock(LiveReloadServer.class);
OptionalLiveReloadServer server = new OptionalLiveReloadServer(delegate);
willThrow(new RuntimeException("Error")).given(delegate).start();

View File

@@ -19,10 +19,10 @@ package org.springframework.boot.devtools.autoconfigure;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
@@ -52,15 +52,13 @@ import static org.mockito.Mockito.mock;
* @author Rob Winch
* @author Phillip Webb
*/
public class RemoteDevToolsAutoConfigurationTests {
@ExtendWith(MockRestarter.class)
class RemoteDevToolsAutoConfigurationTests {
private static final String DEFAULT_CONTEXT_PATH = RemoteDevToolsProperties.DEFAULT_CONTEXT_PATH;
private static final String DEFAULT_SECRET_HEADER_NAME = RemoteDevToolsProperties.DEFAULT_SECRET_HEADER_NAME;
@Rule
public MockRestarter mockRestarter = new MockRestarter();
private AnnotationConfigServletWebApplicationContext context;
private MockHttpServletRequest request;
@@ -69,14 +67,14 @@ public class RemoteDevToolsAutoConfigurationTests {
private MockFilterChain chain;
@Before
@BeforeEach
public void setup() {
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
this.chain = new MockFilterChain();
}
@After
@AfterEach
public void close() {
if (this.context != null) {
this.context.close();
@@ -84,14 +82,14 @@ public class RemoteDevToolsAutoConfigurationTests {
}
@Test
public void disabledIfRemoteSecretIsMissing() throws Exception {
void disabledIfRemoteSecretIsMissing() throws Exception {
this.context = getContext(() -> loadContext("a:b"));
assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
.isThrownBy(() -> this.context.getBean(DispatcherFilter.class));
}
@Test
public void ignoresUnmappedUrl() throws Exception {
void ignoresUnmappedUrl() throws Exception {
this.context = getContext(() -> loadContext("spring.devtools.remote.secret:supersecret"));
DispatcherFilter filter = this.context.getBean(DispatcherFilter.class);
this.request.setRequestURI("/restart");
@@ -101,7 +99,7 @@ public class RemoteDevToolsAutoConfigurationTests {
}
@Test
public void ignoresIfMissingSecretFromRequest() throws Exception {
void ignoresIfMissingSecretFromRequest() throws Exception {
this.context = getContext(() -> loadContext("spring.devtools.remote.secret:supersecret"));
DispatcherFilter filter = this.context.getBean(DispatcherFilter.class);
this.request.setRequestURI(DEFAULT_CONTEXT_PATH + "/restart");
@@ -110,7 +108,7 @@ public class RemoteDevToolsAutoConfigurationTests {
}
@Test
public void ignoresInvalidSecretInRequest() throws Exception {
void ignoresInvalidSecretInRequest() throws Exception {
this.context = getContext(() -> loadContext("spring.devtools.remote.secret:supersecret"));
DispatcherFilter filter = this.context.getBean(DispatcherFilter.class);
this.request.setRequestURI(DEFAULT_CONTEXT_PATH + "/restart");
@@ -120,7 +118,7 @@ public class RemoteDevToolsAutoConfigurationTests {
}
@Test
public void invokeRestartWithDefaultSetup() throws Exception {
void invokeRestartWithDefaultSetup() throws Exception {
this.context = getContext(() -> loadContext("spring.devtools.remote.secret:supersecret"));
DispatcherFilter filter = this.context.getBean(DispatcherFilter.class);
this.request.setRequestURI(DEFAULT_CONTEXT_PATH + "/restart");
@@ -130,7 +128,7 @@ public class RemoteDevToolsAutoConfigurationTests {
}
@Test
public void invokeRestartWithCustomServerContextPath() throws Exception {
void invokeRestartWithCustomServerContextPath() throws Exception {
this.context = getContext(
() -> loadContext("spring.devtools.remote.secret:supersecret", "server.servlet.context-path:/test"));
DispatcherFilter filter = this.context.getBean(DispatcherFilter.class);
@@ -141,7 +139,7 @@ public class RemoteDevToolsAutoConfigurationTests {
}
@Test
public void disableRestart() throws Exception {
void disableRestart() throws Exception {
this.context = getContext(() -> loadContext("spring.devtools.remote.secret:supersecret",
"spring.devtools.remote.restart.enabled:false"));
assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
@@ -149,7 +147,7 @@ public class RemoteDevToolsAutoConfigurationTests {
}
@Test
public void devToolsHealthReturns200() throws Exception {
void devToolsHealthReturns200() throws Exception {
this.context = getContext(() -> loadContext("spring.devtools.remote.secret:supersecret"));
DispatcherFilter filter = this.context.getBean(DispatcherFilter.class);
this.request.setRequestURI(DEFAULT_CONTEXT_PATH);
@@ -160,7 +158,7 @@ public class RemoteDevToolsAutoConfigurationTests {
}
@Test
public void devToolsHealthWithCustomServerContextPathReturns200() throws Exception {
void devToolsHealthWithCustomServerContextPathReturns200() throws Exception {
this.context = getContext(
() -> loadContext("spring.devtools.remote.secret:supersecret", "server.servlet.context-path:/test"));
DispatcherFilter filter = this.context.getBean(DispatcherFilter.class);

View File

@@ -18,9 +18,8 @@ package org.springframework.boot.devtools.autoconfigure;
import java.io.File;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
@@ -30,32 +29,35 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
*
* @author Phillip Webb
*/
public class TriggerFileFilterTests {
class TriggerFileFilterTests {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@TempDir
File tempDir;
@Test
public void nameMustNotBeNull() {
void nameMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new TriggerFileFilter(null))
.withMessageContaining("Name must not be null");
}
@Test
public void acceptNameMatch() throws Exception {
File file = this.temp.newFile("thefile.txt");
void acceptNameMatch() throws Exception {
File file = new File(this.tempDir, "thefile.txt");
file.createNewFile();
assertThat(new TriggerFileFilter("thefile.txt").accept(file)).isTrue();
}
@Test
public void doesNotAcceptNameMismatch() throws Exception {
File file = this.temp.newFile("notthefile.txt");
void doesNotAcceptNameMismatch() throws Exception {
File file = new File(this.tempDir, "notthefile.txt");
file.createNewFile();
assertThat(new TriggerFileFilter("thefile.txt").accept(file)).isFalse();
}
@Test
public void testName() throws Exception {
File file = this.temp.newFile(".triggerfile").getAbsoluteFile();
void testName() throws Exception {
File file = new File(this.tempDir, ".triggerfile");
file.createNewFile();
assertThat(new TriggerFileFilter(".triggerfile").accept(file)).isTrue();
}

View File

@@ -19,7 +19,7 @@ package org.springframework.boot.devtools.classpath;
import java.util.LinkedHashSet;
import java.util.Set;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.devtools.filewatch.ChangedFiles;
@@ -31,25 +31,25 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
*
* @author Phillip Webb
*/
public class ClassPathChangedEventTests {
class ClassPathChangedEventTests {
private Object source = new Object();
@Test
public void changeSetMustNotBeNull() {
void changeSetMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new ClassPathChangedEvent(this.source, null, false))
.withMessageContaining("ChangeSet must not be null");
}
@Test
public void getChangeSet() {
void getChangeSet() {
Set<ChangedFiles> changeSet = new LinkedHashSet<>();
ClassPathChangedEvent event = new ClassPathChangedEvent(this.source, changeSet, false);
assertThat(event.getChangeSet()).isSameAs(changeSet);
}
@Test
public void getRestartRequired() {
void getRestartRequired() {
Set<ChangedFiles> changeSet = new LinkedHashSet<>();
ClassPathChangedEvent event;
event = new ClassPathChangedEvent(this.source, changeSet, false);

View File

@@ -21,8 +21,8 @@ import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
@@ -45,7 +45,7 @@ import static org.mockito.Mockito.verify;
*
* @author Phillip Webb
*/
public class ClassPathFileChangeListenerTests {
class ClassPathFileChangeListenerTests {
@Mock
private ApplicationEventPublisher eventPublisher;
@@ -59,33 +59,33 @@ public class ClassPathFileChangeListenerTests {
@Captor
private ArgumentCaptor<ApplicationEvent> eventCaptor;
@Before
@BeforeEach
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void eventPublisherMustNotBeNull() {
void eventPublisherMustNotBeNull() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new ClassPathFileChangeListener(null, this.restartStrategy, this.fileSystemWatcher))
.withMessageContaining("EventPublisher must not be null");
}
@Test
public void restartStrategyMustNotBeNull() {
void restartStrategyMustNotBeNull() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new ClassPathFileChangeListener(this.eventPublisher, null, this.fileSystemWatcher))
.withMessageContaining("RestartStrategy must not be null");
}
@Test
public void sendsEventWithoutRestart() {
void sendsEventWithoutRestart() {
testSendsEvent(false);
verify(this.fileSystemWatcher, never()).stop();
}
@Test
public void sendsEventWithRestart() {
void sendsEventWithRestart() {
testSendsEvent(true);
verify(this.fileSystemWatcher).stop();
}

View File

@@ -24,9 +24,8 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.devtools.filewatch.FileSystemWatcher;
import org.springframework.boot.devtools.filewatch.FileSystemWatcherFactory;
@@ -47,13 +46,10 @@ import static org.mockito.Mockito.mock;
*
* @author Phillip Webb
*/
public class ClassPathFileSystemWatcherTests {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
class ClassPathFileSystemWatcherTests {
@Test
public void urlsMustNotBeNull() {
void urlsMustNotBeNull() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new ClassPathFileSystemWatcher(mock(FileSystemWatcherFactory.class),
mock(ClassPathRestartStrategy.class), (URL[]) null))
@@ -61,10 +57,9 @@ public class ClassPathFileSystemWatcherTests {
}
@Test
public void configuredWithRestartStrategy() throws Exception {
void configuredWithRestartStrategy(@TempDir File folder) throws Exception {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
Map<String, Object> properties = new HashMap<>();
File folder = this.temp.newFolder();
List<URL> urls = new ArrayList<>();
urls.add(new URL("https://spring.io"));
urls.add(folder.toURI().toURL());

View File

@@ -18,7 +18,7 @@ package org.springframework.boot.devtools.classpath;
import java.io.File;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.devtools.filewatch.ChangedFile;
import org.springframework.boot.devtools.filewatch.ChangedFile.Type;
@@ -31,22 +31,22 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Phillip Webb
* @author Andrew Landsverk
*/
public class PatternClassPathRestartStrategyTests {
class PatternClassPathRestartStrategyTests {
@Test
public void nullPattern() {
void nullPattern() {
ClassPathRestartStrategy strategy = createStrategy(null);
assertRestartRequired(strategy, "a/b.txt", true);
}
@Test
public void emptyPattern() {
void emptyPattern() {
ClassPathRestartStrategy strategy = createStrategy("");
assertRestartRequired(strategy, "a/b.txt", true);
}
@Test
public void singlePattern() {
void singlePattern() {
ClassPathRestartStrategy strategy = createStrategy("static/**");
assertRestartRequired(strategy, "static/file.txt", false);
assertRestartRequired(strategy, "static/folder/file.txt", false);
@@ -55,7 +55,7 @@ public class PatternClassPathRestartStrategyTests {
}
@Test
public void multiplePatterns() {
void multiplePatterns() {
ClassPathRestartStrategy strategy = createStrategy("static/**,public/**");
assertRestartRequired(strategy, "static/file.txt", false);
assertRestartRequired(strategy, "static/folder/file.txt", false);
@@ -66,7 +66,7 @@ public class PatternClassPathRestartStrategyTests {
}
@Test
public void pomChange() {
void pomChange() {
ClassPathRestartStrategy strategy = createStrategy("META-INF/maven/**");
assertRestartRequired(strategy, "pom.xml", true);
String mavenFolder = "META-INF/maven/org.springframework.boot/spring-boot-devtools";
@@ -75,7 +75,7 @@ public class PatternClassPathRestartStrategyTests {
}
@Test
public void testChange() {
void testChange() {
ClassPathRestartStrategy strategy = createStrategy("**/*Test.class,**/*Tests.class");
assertRestartRequired(strategy, "com/example/ExampleTests.class", false);
assertRestartRequired(strategy, "com/example/ExampleTest.class", false);

View File

@@ -21,9 +21,9 @@ import java.util.Collections;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.boot.SpringApplication;
@@ -45,16 +45,16 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
*
* @author Andy Wilkinson
*/
public class DevToolPropertiesIntegrationTests {
class DevToolPropertiesIntegrationTests {
private ConfigurableApplicationContext context;
@Before
@BeforeEach
public void setup() {
Restarter.initialize(new String[] {}, false, new MockInitializer(), false);
}
@After
@AfterEach
public void cleanup() {
if (this.context != null) {
this.context.close();
@@ -63,7 +63,7 @@ public class DevToolPropertiesIntegrationTests {
}
@Test
public void classPropertyConditionIsAffectedByDevToolProperties() throws Exception {
void classPropertyConditionIsAffectedByDevToolProperties() throws Exception {
SpringApplication application = new SpringApplication(ClassConditionConfiguration.class);
application.setWebApplicationType(WebApplicationType.NONE);
this.context = getContext(application::run);
@@ -71,7 +71,7 @@ public class DevToolPropertiesIntegrationTests {
}
@Test
public void beanMethodPropertyConditionIsAffectedByDevToolProperties() throws Exception {
void beanMethodPropertyConditionIsAffectedByDevToolProperties() throws Exception {
SpringApplication application = new SpringApplication(BeanConditionConfiguration.class);
application.setWebApplicationType(WebApplicationType.NONE);
this.context = getContext(application::run);
@@ -79,7 +79,7 @@ public class DevToolPropertiesIntegrationTests {
}
@Test
public void postProcessWhenRestarterDisabledAndRemoteSecretNotSetShouldNotAddPropertySource() throws Exception {
void postProcessWhenRestarterDisabledAndRemoteSecretNotSetShouldNotAddPropertySource() throws Exception {
Restarter.clearInstance();
Restarter.disable();
SpringApplication application = new SpringApplication(BeanConditionConfiguration.class);
@@ -90,7 +90,7 @@ public class DevToolPropertiesIntegrationTests {
}
@Test
public void postProcessWhenRestarterDisabledAndRemoteSecretSetShouldAddPropertySource() throws Exception {
void postProcessWhenRestarterDisabledAndRemoteSecretSetShouldAddPropertySource() throws Exception {
Restarter.clearInstance();
Restarter.disable();
SpringApplication application = new SpringApplication(BeanConditionConfiguration.class);
@@ -101,7 +101,7 @@ public class DevToolPropertiesIntegrationTests {
}
@Test
public void postProcessEnablesIncludeStackTraceProperty() throws Exception {
void postProcessEnablesIncludeStackTraceProperty() throws Exception {
SpringApplication application = new SpringApplication(TestConfiguration.class);
application.setWebApplicationType(WebApplicationType.NONE);
this.context = getContext(application::run);

View File

@@ -22,10 +22,9 @@ import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.mock.env.MockEnvironment;
@@ -38,20 +37,17 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Phillip Webb
* @author Andy Wilkinson
*/
public class DevToolsHomePropertiesPostProcessorTests {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
class DevToolsHomePropertiesPostProcessorTests {
private File home;
@Before
public void setup() throws IOException {
this.home = this.temp.newFolder();
@BeforeEach
public void setup(@TempDir File tempDir) throws IOException {
this.home = tempDir;
}
@Test
public void loadsHomeProperties() throws Exception {
void loadsHomeProperties() throws Exception {
Properties properties = new Properties();
properties.put("abc", "def");
OutputStream out = new FileOutputStream(new File(this.home, ".spring-boot-devtools.properties"));
@@ -64,7 +60,7 @@ public class DevToolsHomePropertiesPostProcessorTests {
}
@Test
public void ignoresMissingHomeProperties() throws Exception {
void ignoresMissingHomeProperties() throws Exception {
ConfigurableEnvironment environment = new MockEnvironment();
MockDevToolHomePropertiesPostProcessor postProcessor = new MockDevToolHomePropertiesPostProcessor();
runPostProcessor(() -> postProcessor.postProcessEnvironment(environment, null));

View File

@@ -18,9 +18,8 @@ package org.springframework.boot.devtools.filewatch;
import java.io.File;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.devtools.filewatch.ChangedFile.Type;
@@ -32,49 +31,52 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
*
* @author Phillip Webb
*/
public class ChangedFileTests {
class ChangedFileTests {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@TempDir
File tempDir;
@Test
public void sourceFolderMustNotBeNull() throws Exception {
assertThatIllegalArgumentException().isThrownBy(() -> new ChangedFile(null, this.temp.newFile(), Type.ADD))
void sourceFolderMustNotBeNull() throws Exception {
assertThatIllegalArgumentException()
.isThrownBy(() -> new ChangedFile(null, new File(this.tempDir, "file"), Type.ADD))
.withMessageContaining("SourceFolder must not be null");
}
@Test
public void fileMustNotBeNull() throws Exception {
assertThatIllegalArgumentException().isThrownBy(() -> new ChangedFile(this.temp.newFolder(), null, Type.ADD))
void fileMustNotBeNull() throws Exception {
assertThatIllegalArgumentException()
.isThrownBy(() -> new ChangedFile(new File(this.tempDir, "folder"), null, Type.ADD))
.withMessageContaining("File must not be null");
}
@Test
public void typeMustNotBeNull() throws Exception {
void typeMustNotBeNull() throws Exception {
assertThatIllegalArgumentException()
.isThrownBy(() -> new ChangedFile(this.temp.newFile(), this.temp.newFolder(), null))
.isThrownBy(
() -> new ChangedFile(new File(this.tempDir, "file"), new File(this.tempDir, "folder"), null))
.withMessageContaining("Type must not be null");
}
@Test
public void getFile() throws Exception {
File file = this.temp.newFile();
ChangedFile changedFile = new ChangedFile(this.temp.newFolder(), file, Type.ADD);
void getFile() throws Exception {
File file = new File(this.tempDir, "file");
ChangedFile changedFile = new ChangedFile(new File(this.tempDir, "folder"), file, Type.ADD);
assertThat(changedFile.getFile()).isEqualTo(file);
}
@Test
public void getType() throws Exception {
ChangedFile changedFile = new ChangedFile(this.temp.newFolder(), this.temp.newFile(), Type.DELETE);
void getType() throws Exception {
ChangedFile changedFile = new ChangedFile(new File(this.tempDir, "folder"), new File(this.tempDir, "file"),
Type.DELETE);
assertThat(changedFile.getType()).isEqualTo(Type.DELETE);
}
@Test
public void getRelativeName() throws Exception {
File folder = this.temp.newFolder();
File subFolder = new File(folder, "A");
void getRelativeName() throws Exception {
File subFolder = new File(this.tempDir, "A");
File file = new File(subFolder, "B.txt");
ChangedFile changedFile = new ChangedFile(folder, file, Type.ADD);
ChangedFile changedFile = new ChangedFile(this.tempDir, file, Type.ADD);
assertThat(changedFile.getRelativeName()).isEqualTo("A/B.txt");
}

View File

@@ -19,11 +19,11 @@ package org.springframework.boot.devtools.filewatch;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.util.FileCopyUtils;
@@ -35,29 +35,31 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
*
* @author Phillip Webb
*/
public class FileSnapshotTests {
class FileSnapshotTests {
private static final long TWO_MINS = TimeUnit.MINUTES.toMillis(2);
private static final long MODIFIED = new Date().getTime() - TimeUnit.DAYS.toMillis(10);
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@TempDir
File tempDir;
@Test
public void fileMustNotBeNull() {
void fileMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new FileSnapshot(null))
.withMessageContaining("File must not be null");
}
@Test
public void fileMustNotBeAFolder() throws Exception {
assertThatIllegalArgumentException().isThrownBy(() -> new FileSnapshot(this.temporaryFolder.newFolder()))
void fileMustNotBeAFolder() throws Exception {
File file = new File(this.tempDir, "file");
file.mkdir();
assertThatIllegalArgumentException().isThrownBy(() -> new FileSnapshot(file))
.withMessageContaining("File must not be a folder");
}
@Test
public void equalsIfTheSame() throws Exception {
void equalsIfTheSame() throws Exception {
File file = createNewFile("abc", MODIFIED);
File fileCopy = new File(file, "x").getParentFile();
FileSnapshot snapshot1 = new FileSnapshot(file);
@@ -67,7 +69,7 @@ public class FileSnapshotTests {
}
@Test
public void notEqualsIfDeleted() throws Exception {
void notEqualsIfDeleted() throws Exception {
File file = createNewFile("abc", MODIFIED);
FileSnapshot snapshot1 = new FileSnapshot(file);
file.delete();
@@ -75,7 +77,7 @@ public class FileSnapshotTests {
}
@Test
public void notEqualsIfLengthChanges() throws Exception {
void notEqualsIfLengthChanges() throws Exception {
File file = createNewFile("abc", MODIFIED);
FileSnapshot snapshot1 = new FileSnapshot(file);
setupFile(file, "abcd", MODIFIED);
@@ -83,7 +85,7 @@ public class FileSnapshotTests {
}
@Test
public void notEqualsIfLastModifiedChanges() throws Exception {
void notEqualsIfLastModifiedChanges() throws Exception {
File file = createNewFile("abc", MODIFIED);
FileSnapshot snapshot1 = new FileSnapshot(file);
setupFile(file, "abc", MODIFIED + TWO_MINS);
@@ -91,7 +93,7 @@ public class FileSnapshotTests {
}
private File createNewFile(String content, long lastModified) throws IOException {
File file = this.temporaryFolder.newFile();
File file = new File(this.tempDir, UUID.randomUUID().toString());
setupFile(file, content, lastModified);
return file;
}

View File

@@ -26,11 +26,11 @@ import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.devtools.filewatch.ChangedFile.Type;
import org.springframework.util.FileCopyUtils;
@@ -45,62 +45,62 @@ import static org.mockito.Mockito.mock;
*
* @author Phillip Webb
*/
public class FileSystemWatcherTests {
class FileSystemWatcherTests {
private FileSystemWatcher watcher;
private List<Set<ChangedFiles>> changes = Collections.synchronizedList(new ArrayList<>());
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@TempDir
File tempDir;
@Before
@BeforeEach
public void setup() {
setupWatcher(20, 10);
}
@Test
public void pollIntervalMustBePositive() {
void pollIntervalMustBePositive() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new FileSystemWatcher(true, Duration.ofMillis(0), Duration.ofMillis(1)))
.withMessageContaining("PollInterval must be positive");
}
@Test
public void quietPeriodMustBePositive() {
void quietPeriodMustBePositive() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new FileSystemWatcher(true, Duration.ofMillis(1), Duration.ofMillis(0)))
.withMessageContaining("QuietPeriod must be positive");
}
@Test
public void pollIntervalMustBeGreaterThanQuietPeriod() {
void pollIntervalMustBeGreaterThanQuietPeriod() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new FileSystemWatcher(true, Duration.ofMillis(1), Duration.ofMillis(1)))
.withMessageContaining("PollInterval must be greater than QuietPeriod");
}
@Test
public void listenerMustNotBeNull() {
void listenerMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.watcher.addListener(null))
.withMessageContaining("FileChangeListener must not be null");
}
@Test
public void cannotAddListenerToStartedListener() {
void cannotAddListenerToStartedListener() {
this.watcher.start();
assertThatIllegalStateException().isThrownBy(() -> this.watcher.addListener(mock(FileChangeListener.class)))
.withMessageContaining("FileSystemWatcher already started");
}
@Test
public void sourceFolderMustNotBeNull() {
void sourceFolderMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.watcher.addSourceFolder(null))
.withMessageContaining("Folder must not be null");
}
@Test
public void sourceFolderMustNotBeAFile() {
void sourceFolderMustNotBeAFile() {
File folder = new File("pom.xml");
assertThat(folder.isFile()).isTrue();
assertThatIllegalArgumentException().isThrownBy(() -> this.watcher.addSourceFolder(new File("pom.xml")))
@@ -108,14 +108,14 @@ public class FileSystemWatcherTests {
}
@Test
public void cannotAddSourceFolderToStartedListener() throws Exception {
void cannotAddSourceFolderToStartedListener() throws Exception {
this.watcher.start();
assertThatIllegalStateException().isThrownBy(() -> this.watcher.addSourceFolder(this.temp.newFolder()))
assertThatIllegalStateException().isThrownBy(() -> this.watcher.addSourceFolder(this.tempDir))
.withMessageContaining("FileSystemWatcher already started");
}
@Test
public void addFile() throws Exception {
void addFile() throws Exception {
File folder = startWithNewFolder();
File file = touch(new File(folder, "test.txt"));
this.watcher.stopAfter(1);
@@ -125,7 +125,7 @@ public class FileSystemWatcherTests {
}
@Test
public void addNestedFile() throws Exception {
void addNestedFile() throws Exception {
File folder = startWithNewFolder();
File file = touch(new File(new File(folder, "sub"), "text.txt"));
this.watcher.stopAfter(1);
@@ -135,8 +135,8 @@ public class FileSystemWatcherTests {
}
@Test
public void createSourceFolderAndAddFile() throws IOException {
File folder = new File(this.temp.getRoot(), "does/not/exist");
void createSourceFolderAndAddFile() throws IOException {
File folder = new File(this.tempDir, "does/not/exist");
assertThat(folder.exists()).isFalse();
this.watcher.addSourceFolder(folder);
this.watcher.start();
@@ -149,7 +149,7 @@ public class FileSystemWatcherTests {
}
@Test
public void waitsForPollingInterval() throws Exception {
void waitsForPollingInterval() throws Exception {
setupWatcher(10, 1);
File folder = startWithNewFolder();
touch(new File(folder, "test1.txt"));
@@ -162,7 +162,7 @@ public class FileSystemWatcherTests {
}
@Test
public void waitsForQuietPeriod() throws Exception {
void waitsForQuietPeriod() throws Exception {
setupWatcher(300, 200);
File folder = startWithNewFolder();
for (int i = 0; i < 10; i++) {
@@ -175,8 +175,9 @@ public class FileSystemWatcherTests {
}
@Test
public void withExistingFiles() throws Exception {
File folder = this.temp.newFolder();
void withExistingFiles() throws Exception {
File folder = new File(this.tempDir, UUID.randomUUID().toString());
folder.mkdir();
touch(new File(folder, "test.txt"));
this.watcher.addSourceFolder(folder);
this.watcher.start();
@@ -188,9 +189,11 @@ public class FileSystemWatcherTests {
}
@Test
public void multipleSources() throws Exception {
File folder1 = this.temp.newFolder();
File folder2 = this.temp.newFolder();
void multipleSources() throws Exception {
File folder1 = new File(this.tempDir, UUID.randomUUID().toString());
folder1.mkdir();
File folder2 = new File(this.tempDir, UUID.randomUUID().toString());
folder2.mkdir();
this.watcher.addSourceFolder(folder1);
this.watcher.addSourceFolder(folder2);
this.watcher.start();
@@ -212,8 +215,9 @@ public class FileSystemWatcherTests {
}
@Test
public void multipleListeners() throws Exception {
File folder = this.temp.newFolder();
void multipleListeners() throws Exception {
File folder = new File(this.tempDir, UUID.randomUUID().toString());
folder.mkdir();
final Set<ChangedFiles> listener2Changes = new LinkedHashSet<>();
this.watcher.addSourceFolder(folder);
this.watcher.addListener(listener2Changes::addAll);
@@ -227,8 +231,9 @@ public class FileSystemWatcherTests {
}
@Test
public void modifyDeleteAndAdd() throws Exception {
File folder = this.temp.newFolder();
void modifyDeleteAndAdd() throws Exception {
File folder = new File(this.tempDir, UUID.randomUUID().toString());
folder.mkdir();
File modify = touch(new File(folder, "modify.txt"));
File delete = touch(new File(folder, "delete.txt"));
this.watcher.addSourceFolder(folder);
@@ -247,8 +252,9 @@ public class FileSystemWatcherTests {
}
@Test
public void withTriggerFilter() throws Exception {
File folder = this.temp.newFolder();
void withTriggerFilter() throws Exception {
File folder = new File(this.tempDir, UUID.randomUUID().toString());
folder.mkdir();
File file = touch(new File(folder, "file.txt"));
File trigger = touch(new File(folder, "trigger.txt"));
this.watcher.addSourceFolder(folder);
@@ -272,7 +278,8 @@ public class FileSystemWatcherTests {
}
private File startWithNewFolder() throws IOException {
File folder = this.temp.newFolder();
File folder = new File(this.tempDir, UUID.randomUUID().toString());
folder.mkdir();
this.watcher.addSourceFolder(folder);
this.watcher.start();
return folder;

View File

@@ -18,11 +18,11 @@ package org.springframework.boot.devtools.filewatch;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.devtools.filewatch.ChangedFile.Type;
import org.springframework.util.FileCopyUtils;
@@ -35,64 +35,65 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
*
* @author Phillip Webb
*/
public class FolderSnapshotTests {
class FolderSnapshotTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@TempDir
File tempDir;
private File folder;
private FolderSnapshot initialSnapshot;
@Before
@BeforeEach
public void setup() throws Exception {
this.folder = createTestFolderStructure();
this.initialSnapshot = new FolderSnapshot(this.folder);
}
@Test
public void folderMustNotBeNull() {
void folderMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new FolderSnapshot(null))
.withMessageContaining("Folder must not be null");
}
@Test
public void folderMustNotBeFile() throws Exception {
File file = this.temporaryFolder.newFile();
void folderMustNotBeFile() throws Exception {
File file = new File(this.tempDir, "file");
file.createNewFile();
assertThatIllegalArgumentException().isThrownBy(() -> new FolderSnapshot(file))
.withMessageContaining("Folder '" + file + "' must not be a file");
}
@Test
public void folderDoesNotHaveToExist() throws Exception {
File file = new File(this.temporaryFolder.getRoot(), "does/not/exist");
void folderDoesNotHaveToExist() throws Exception {
File file = new File(this.tempDir, "does/not/exist");
FolderSnapshot snapshot = new FolderSnapshot(file);
assertThat(snapshot).isEqualTo(new FolderSnapshot(file));
}
@Test
public void equalsWhenNothingHasChanged() {
void equalsWhenNothingHasChanged() {
FolderSnapshot updatedSnapshot = new FolderSnapshot(this.folder);
assertThat(this.initialSnapshot).isEqualTo(updatedSnapshot);
assertThat(this.initialSnapshot.hashCode()).isEqualTo(updatedSnapshot.hashCode());
}
@Test
public void notEqualsWhenAFileIsAdded() throws Exception {
void notEqualsWhenAFileIsAdded() throws Exception {
new File(new File(this.folder, "folder1"), "newfile").createNewFile();
FolderSnapshot updatedSnapshot = new FolderSnapshot(this.folder);
assertThat(this.initialSnapshot).isNotEqualTo(updatedSnapshot);
}
@Test
public void notEqualsWhenAFileIsDeleted() {
void notEqualsWhenAFileIsDeleted() {
new File(new File(this.folder, "folder1"), "file1").delete();
FolderSnapshot updatedSnapshot = new FolderSnapshot(this.folder);
assertThat(this.initialSnapshot).isNotEqualTo(updatedSnapshot);
}
@Test
public void notEqualsWhenAFileIsModified() throws Exception {
void notEqualsWhenAFileIsModified() throws Exception {
File file1 = new File(new File(this.folder, "folder1"), "file1");
FileCopyUtils.copy("updatedcontent".getBytes(), file1);
FolderSnapshot updatedSnapshot = new FolderSnapshot(this.folder);
@@ -100,26 +101,26 @@ public class FolderSnapshotTests {
}
@Test
public void getChangedFilesSnapshotMustNotBeNull() {
void getChangedFilesSnapshotMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.initialSnapshot.getChangedFiles(null, null))
.withMessageContaining("Snapshot must not be null");
}
@Test
public void getChangedFilesSnapshotMustBeTheSameSourceFolder() throws Exception {
void getChangedFilesSnapshotMustBeTheSameSourceFolder() throws Exception {
assertThatIllegalArgumentException().isThrownBy(
() -> this.initialSnapshot.getChangedFiles(new FolderSnapshot(createTestFolderStructure()), null))
.withMessageContaining("Snapshot source folder must be '" + this.folder + "'");
}
@Test
public void getChangedFilesWhenNothingHasChanged() {
void getChangedFilesWhenNothingHasChanged() {
FolderSnapshot updatedSnapshot = new FolderSnapshot(this.folder);
this.initialSnapshot.getChangedFiles(updatedSnapshot, null);
}
@Test
public void getChangedFilesWhenAFileIsAddedAndDeletedAndChanged() throws Exception {
void getChangedFilesWhenAFileIsAddedAndDeletedAndChanged() throws Exception {
File folder1 = new File(this.folder, "folder1");
File file1 = new File(folder1, "file1");
File file2 = new File(folder1, "file2");
@@ -145,7 +146,7 @@ public class FolderSnapshotTests {
}
private File createTestFolderStructure() throws IOException {
File root = this.temporaryFolder.newFolder();
File root = new File(this.tempDir, UUID.randomUUID().toString());
File folder1 = new File(root, "folder1");
folder1.mkdirs();
FileCopyUtils.copy("abc".getBytes(), new File(folder1, "file1"));

View File

@@ -20,7 +20,7 @@ import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.devtools.integrationtest.HttpTunnelIntegrationTests.TunnelConfiguration.TestTunnelClient;
@@ -59,10 +59,10 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Phillip Webb
*/
public class HttpTunnelIntegrationTests {
class HttpTunnelIntegrationTests {
@Test
public void httpServerDirect() {
void httpServerDirect() {
AnnotationConfigServletWebServerApplicationContext context = new AnnotationConfigServletWebServerApplicationContext();
context.register(ServerConfiguration.class);
context.refresh();
@@ -74,7 +74,7 @@ public class HttpTunnelIntegrationTests {
}
@Test
public void viaTunnel() {
void viaTunnel() {
AnnotationConfigServletWebServerApplicationContext serverContext = new AnnotationConfigServletWebServerApplicationContext();
serverContext.register(ServerConfiguration.class);
serverContext.refresh();

View File

@@ -21,7 +21,7 @@ import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIOException;
@@ -32,12 +32,12 @@ import static org.assertj.core.api.Assertions.assertThatIOException;
* @author Phillip Webb
*/
@SuppressWarnings("resource")
public class ConnectionInputStreamTests {
class ConnectionInputStreamTests {
private static final byte[] NO_BYTES = {};
@Test
public void readHeader() throws Exception {
void readHeader() throws Exception {
String header = "";
for (int i = 0; i < 100; i++) {
header += "x-something-" + i + ": xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
@@ -48,7 +48,7 @@ public class ConnectionInputStreamTests {
}
@Test
public void readFully() throws Exception {
void readFully() throws Exception {
byte[] bytes = "the data that we want to read fully".getBytes();
LimitedInputStream source = new LimitedInputStream(new ByteArrayInputStream(bytes), 2);
ConnectionInputStream inputStream = new ConnectionInputStream(source);
@@ -58,13 +58,13 @@ public class ConnectionInputStreamTests {
}
@Test
public void checkedRead() throws Exception {
void checkedRead() throws Exception {
ConnectionInputStream inputStream = new ConnectionInputStream(new ByteArrayInputStream(NO_BYTES));
assertThatIOException().isThrownBy(inputStream::checkedRead).withMessageContaining("End of stream");
}
@Test
public void checkedReadArray() throws Exception {
void checkedReadArray() throws Exception {
byte[] buffer = new byte[100];
ConnectionInputStream inputStream = new ConnectionInputStream(new ByteArrayInputStream(NO_BYTES));
assertThatIOException().isThrownBy(() -> inputStream.checkedRead(buffer, 0, buffer.length))

View File

@@ -20,7 +20,7 @@ import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
@@ -32,10 +32,10 @@ import static org.mockito.Mockito.verify;
* @author Phillip Webb
*/
@SuppressWarnings("resource")
public class ConnectionOutputStreamTests {
class ConnectionOutputStreamTests {
@Test
public void write() throws Exception {
void write() throws Exception {
OutputStream out = mock(OutputStream.class);
ConnectionOutputStream outputStream = new ConnectionOutputStream(out);
byte[] b = new byte[100];
@@ -44,7 +44,7 @@ public class ConnectionOutputStreamTests {
}
@Test
public void writeHttp() throws Exception {
void writeHttp() throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ConnectionOutputStream outputStream = new ConnectionOutputStream(out);
outputStream.writeHttp(new ByteArrayInputStream("hi".getBytes()), "x-type");
@@ -58,7 +58,7 @@ public class ConnectionOutputStreamTests {
}
@Test
public void writeHeaders() throws Exception {
void writeHeaders() throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ConnectionOutputStream outputStream = new ConnectionOutputStream(out);
outputStream.writeHeaders("A: a", "B: b");

View File

@@ -20,7 +20,7 @@ import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
@@ -31,36 +31,36 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
*
* @author Phillip Webb
*/
public class FrameTests {
class FrameTests {
@Test
public void payloadMustNotBeNull() {
void payloadMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new Frame((String) null))
.withMessageContaining("Payload must not be null");
}
@Test
public void typeMustNotBeNull() {
void typeMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new Frame((Frame.Type) null))
.withMessageContaining("Type must not be null");
}
@Test
public void textPayload() {
void textPayload() {
Frame frame = new Frame("abc");
assertThat(frame.getType()).isEqualTo(Frame.Type.TEXT);
assertThat(frame.getPayload()).isEqualTo("abc".getBytes());
}
@Test
public void typedPayload() {
void typedPayload() {
Frame frame = new Frame(Frame.Type.CLOSE);
assertThat(frame.getType()).isEqualTo(Frame.Type.CLOSE);
assertThat(frame.getPayload()).isEqualTo(new byte[] {});
}
@Test
public void writeSmallPayload() throws Exception {
void writeSmallPayload() throws Exception {
String payload = createString(1);
Frame frame = new Frame(payload);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
@@ -69,7 +69,7 @@ public class FrameTests {
}
@Test
public void writeLargePayload() throws Exception {
void writeLargePayload() throws Exception {
String payload = createString(126);
Frame frame = new Frame(payload);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
@@ -85,21 +85,21 @@ public class FrameTests {
}
@Test
public void readFragmentedNotSupported() throws Exception {
void readFragmentedNotSupported() throws Exception {
byte[] bytes = new byte[] { 0x0F };
assertThatIllegalStateException().isThrownBy(() -> Frame.read(newConnectionInputStream(bytes)))
.withMessageContaining("Fragmented frames are not supported");
}
@Test
public void readLargeFramesNotSupported() throws Exception {
void readLargeFramesNotSupported() throws Exception {
byte[] bytes = new byte[] { (byte) 0x80, (byte) 0xFF };
assertThatIllegalStateException().isThrownBy(() -> Frame.read(newConnectionInputStream(bytes)))
.withMessageContaining("Large frames are not supported");
}
@Test
public void readSmallTextFrame() throws Exception {
void readSmallTextFrame() throws Exception {
byte[] bytes = new byte[] { (byte) 0x81, (byte) 0x02, 0x41, 0x41 };
Frame frame = Frame.read(newConnectionInputStream(bytes));
assertThat(frame.getType()).isEqualTo(Frame.Type.TEXT);
@@ -107,7 +107,7 @@ public class FrameTests {
}
@Test
public void readMaskedTextFrame() throws Exception {
void readMaskedTextFrame() throws Exception {
byte[] bytes = new byte[] { (byte) 0x81, (byte) 0x82, 0x0F, 0x0F, 0x0F, 0x0F, 0x4E, 0x4E };
Frame frame = Frame.read(newConnectionInputStream(bytes));
assertThat(frame.getType()).isEqualTo(Frame.Type.TEXT);
@@ -115,7 +115,7 @@ public class FrameTests {
}
@Test
public void readLargeTextFrame() throws Exception {
void readLargeTextFrame() throws Exception {
byte[] bytes = new byte[134];
Arrays.fill(bytes, (byte) 0x4E);
bytes[0] = (byte) 0x81;
@@ -132,35 +132,35 @@ public class FrameTests {
}
@Test
public void readContinuation() throws Exception {
void readContinuation() throws Exception {
byte[] bytes = new byte[] { (byte) 0x80, (byte) 0x00 };
Frame frame = Frame.read(newConnectionInputStream(bytes));
assertThat(frame.getType()).isEqualTo(Frame.Type.CONTINUATION);
}
@Test
public void readBinary() throws Exception {
void readBinary() throws Exception {
byte[] bytes = new byte[] { (byte) 0x82, (byte) 0x00 };
Frame frame = Frame.read(newConnectionInputStream(bytes));
assertThat(frame.getType()).isEqualTo(Frame.Type.BINARY);
}
@Test
public void readClose() throws Exception {
void readClose() throws Exception {
byte[] bytes = new byte[] { (byte) 0x88, (byte) 0x00 };
Frame frame = Frame.read(newConnectionInputStream(bytes));
assertThat(frame.getType()).isEqualTo(Frame.Type.CLOSE);
}
@Test
public void readPing() throws Exception {
void readPing() throws Exception {
byte[] bytes = new byte[] { (byte) 0x89, (byte) 0x00 };
Frame frame = Frame.read(newConnectionInputStream(bytes));
assertThat(frame.getType()).isEqualTo(Frame.Type.PING);
}
@Test
public void readPong() throws Exception {
void readPong() throws Exception {
byte[] bytes = new byte[] { (byte) 0x8A, (byte) 0x00 };
Frame frame = Frame.read(newConnectionInputStream(bytes));
assertThat(frame.getType()).isEqualTo(Frame.Type.PONG);

View File

@@ -26,10 +26,10 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.tomcat.websocket.WsWebSocketContainer;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.socket.CloseStatus;
@@ -50,7 +50,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Phillip Webb
* @author Andy Wilkinson
*/
public class LiveReloadServerTests {
class LiveReloadServerTests {
private static final String HANDSHAKE = "{command: 'hello', "
+ "protocols: ['http://livereload.com/protocols/official-7']}";
@@ -59,20 +59,20 @@ public class LiveReloadServerTests {
private MonitoredLiveReloadServer server;
@Before
@BeforeEach
public void setUp() throws Exception {
this.server = new MonitoredLiveReloadServer(0);
this.port = this.server.start();
}
@After
@AfterEach
public void tearDown() throws Exception {
this.server.stop();
}
@Test
@Ignore
public void servesLivereloadJs() throws Exception {
@Disabled
void servesLivereloadJs() throws Exception {
RestTemplate template = new RestTemplate();
URI uri = new URI("http://localhost:" + this.port + "/livereload.js");
String script = template.getForObject(uri, String.class);
@@ -80,7 +80,7 @@ public class LiveReloadServerTests {
}
@Test
public void triggerReload() throws Exception {
void triggerReload() throws Exception {
LiveReloadWebSocketHandler handler = connect();
this.server.triggerReload();
Thread.sleep(200);
@@ -90,7 +90,7 @@ public class LiveReloadServerTests {
}
@Test
public void pingPong() throws Exception {
void pingPong() throws Exception {
LiveReloadWebSocketHandler handler = connect();
handler.sendMessage(new PingMessage());
Thread.sleep(200);
@@ -99,7 +99,7 @@ public class LiveReloadServerTests {
}
@Test
public void clientClose() throws Exception {
void clientClose() throws Exception {
LiveReloadWebSocketHandler handler = connect();
handler.close();
awaitClosedException();
@@ -114,7 +114,7 @@ public class LiveReloadServerTests {
}
@Test
public void serverClose() throws Exception {
void serverClose() throws Exception {
LiveReloadWebSocketHandler handler = connect();
this.server.stop();
Thread.sleep(200);

View File

@@ -26,10 +26,9 @@ import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.devtools.classpath.ClassPathChangedEvent;
import org.springframework.boot.devtools.filewatch.ChangedFile;
@@ -53,50 +52,46 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
* @author Phillip Webb
* @author Andy Wilkinson
*/
public class ClassPathChangeUploaderTests {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
class ClassPathChangeUploaderTests {
private MockClientHttpRequestFactory requestFactory;
private ClassPathChangeUploader uploader;
@Before
@BeforeEach
public void setup() {
this.requestFactory = new MockClientHttpRequestFactory();
this.uploader = new ClassPathChangeUploader("http://localhost/upload", this.requestFactory);
}
@Test
public void urlMustNotBeNull() {
void urlMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new ClassPathChangeUploader(null, this.requestFactory))
.withMessageContaining("URL must not be empty");
}
@Test
public void urlMustNotBeEmpty() {
void urlMustNotBeEmpty() {
assertThatIllegalArgumentException().isThrownBy(() -> new ClassPathChangeUploader("", this.requestFactory))
.withMessageContaining("URL must not be empty");
}
@Test
public void requestFactoryMustNotBeNull() {
void requestFactoryMustNotBeNull() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new ClassPathChangeUploader("http://localhost:8080", null))
.withMessageContaining("RequestFactory must not be null");
}
@Test
public void urlMustNotBeMalformed() {
void urlMustNotBeMalformed() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new ClassPathChangeUploader("htttttp:///ttest", this.requestFactory))
.withMessageContaining("Malformed URL 'htttttp:///ttest'");
}
@Test
public void sendsClassLoaderFiles() throws Exception {
File sourceFolder = this.temp.newFolder();
void sendsClassLoaderFiles(@TempDir File sourceFolder) throws Exception {
ClassPathChangedEvent event = createClassPathChangedEvent(sourceFolder);
this.requestFactory.willRespond(HttpStatus.OK);
this.uploader.onApplicationEvent(event);
@@ -106,8 +101,7 @@ public class ClassPathChangeUploaderTests {
}
@Test
public void retriesOnSocketException() throws Exception {
File sourceFolder = this.temp.newFolder();
void retriesOnSocketException(@TempDir File sourceFolder) throws Exception {
ClassPathChangedEvent event = createClassPathChangedEvent(sourceFolder);
this.requestFactory.willRespond(new SocketException());
this.requestFactory.willRespond(HttpStatus.OK);

View File

@@ -19,8 +19,8 @@ package org.springframework.boot.devtools.remote.client;
import java.io.IOException;
import java.net.URI;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
@@ -42,7 +42,7 @@ import static org.mockito.Mockito.verify;
*
* @author Phillip Webb
*/
public class DelayedLiveReloadTriggerTests {
class DelayedLiveReloadTriggerTests {
private static final String URL = "http://localhost:8080";
@@ -66,7 +66,7 @@ public class DelayedLiveReloadTriggerTests {
private DelayedLiveReloadTrigger trigger;
@Before
@BeforeEach
public void setup() throws IOException {
MockitoAnnotations.initMocks(this);
given(this.errorRequest.execute()).willReturn(this.errorResponse);
@@ -77,35 +77,35 @@ public class DelayedLiveReloadTriggerTests {
}
@Test
public void liveReloadServerMustNotBeNull() {
void liveReloadServerMustNotBeNull() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new DelayedLiveReloadTrigger(null, this.requestFactory, URL))
.withMessageContaining("LiveReloadServer must not be null");
}
@Test
public void requestFactoryMustNotBeNull() {
void requestFactoryMustNotBeNull() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new DelayedLiveReloadTrigger(this.liveReloadServer, null, URL))
.withMessageContaining("RequestFactory must not be null");
}
@Test
public void urlMustNotBeNull() {
void urlMustNotBeNull() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new DelayedLiveReloadTrigger(this.liveReloadServer, this.requestFactory, null))
.withMessageContaining("URL must not be empty");
}
@Test
public void urlMustNotBeEmpty() {
void urlMustNotBeEmpty() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new DelayedLiveReloadTrigger(this.liveReloadServer, this.requestFactory, ""))
.withMessageContaining("URL must not be empty");
}
@Test
public void triggerReloadOnStatus() throws Exception {
void triggerReloadOnStatus() throws Exception {
given(this.requestFactory.createRequest(new URI(URL), HttpMethod.GET)).willThrow(new IOException())
.willReturn(this.errorRequest, this.okRequest);
long startTime = System.currentTimeMillis();
@@ -116,7 +116,7 @@ public class DelayedLiveReloadTriggerTests {
}
@Test
public void timeout() throws Exception {
void timeout() throws Exception {
given(this.requestFactory.createRequest(new URI(URL), HttpMethod.GET)).willThrow(new IOException());
this.trigger.setTimings(10, 0, 10);
this.trigger.run();

View File

@@ -18,8 +18,8 @@ package org.springframework.boot.devtools.remote.client;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
@@ -39,7 +39,7 @@ import static org.mockito.BDDMockito.given;
* @author Rob Winch
* @since 1.3.0
*/
public class HttpHeaderInterceptorTests {
class HttpHeaderInterceptorTests {
private String name;
@@ -59,7 +59,7 @@ public class HttpHeaderInterceptorTests {
private MockHttpServletRequest httpRequest;
@Before
@BeforeEach
public void setup() throws Exception {
MockitoAnnotations.initMocks(this);
this.body = new byte[] {};
@@ -72,31 +72,31 @@ public class HttpHeaderInterceptorTests {
}
@Test
public void constructorNullHeaderName() {
void constructorNullHeaderName() {
assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderInterceptor(null, this.value))
.withMessageContaining("Name must not be empty");
}
@Test
public void constructorEmptyHeaderName() {
void constructorEmptyHeaderName() {
assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderInterceptor("", this.value))
.withMessageContaining("Name must not be empty");
}
@Test
public void constructorNullHeaderValue() {
void constructorNullHeaderValue() {
assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderInterceptor(this.name, null))
.withMessageContaining("Value must not be empty");
}
@Test
public void constructorEmptyHeaderValue() {
void constructorEmptyHeaderValue() {
assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderInterceptor(this.name, ""))
.withMessageContaining("Value must not be empty");
}
@Test
public void intercept() throws IOException {
void intercept() throws IOException {
ClientHttpResponse result = this.interceptor.intercept(this.request, this.body, this.execution);
assertThat(this.request.getHeaders().getFirst(this.name)).isEqualTo(this.value);
assertThat(result).isEqualTo(this.response);

View File

@@ -21,9 +21,9 @@ import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
@@ -37,7 +37,8 @@ import org.springframework.boot.devtools.remote.server.Dispatcher;
import org.springframework.boot.devtools.remote.server.DispatcherFilter;
import org.springframework.boot.devtools.restart.MockRestarter;
import org.springframework.boot.devtools.restart.RestartScopeInitializer;
import org.springframework.boot.test.system.OutputCaptureRule;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;
@@ -59,19 +60,14 @@ import static org.mockito.Mockito.verify;
*
* @author Phillip Webb
*/
public class RemoteClientConfigurationTests {
@Rule
public MockRestarter restarter = new MockRestarter();
@Rule
public OutputCaptureRule output = new OutputCaptureRule();
@ExtendWith({ OutputCaptureExtension.class, MockRestarter.class })
class RemoteClientConfigurationTests {
private AnnotationConfigServletWebServerApplicationContext context;
private AnnotationConfigApplicationContext clientContext;
@After
@AfterEach
public void cleanup() {
if (this.context != null) {
this.context.close();
@@ -82,31 +78,31 @@ public class RemoteClientConfigurationTests {
}
@Test
public void warnIfRestartDisabled() {
void warnIfRestartDisabled(CapturedOutput capturedOutput) {
configure("spring.devtools.remote.restart.enabled:false");
assertThat(this.output.toString()).contains("Remote restart is disabled");
assertThat(capturedOutput).contains("Remote restart is disabled");
}
@Test
public void warnIfNotHttps() {
void warnIfNotHttps(CapturedOutput capturedOutput) {
configure("http://localhost", true);
assertThat(this.output.toString()).contains("is insecure");
assertThat(capturedOutput).contains("is insecure");
}
@Test
public void doesntWarnIfUsingHttps() {
void doesntWarnIfUsingHttps(CapturedOutput capturedOutput) {
configure("https://localhost", true);
assertThat(this.output.toString()).doesNotContain("is insecure");
assertThat(capturedOutput).doesNotContain("is insecure");
}
@Test
public void failIfNoSecret() {
void failIfNoSecret() {
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> configure("http://localhost", false))
.withMessageContaining("required to secure your connection");
}
@Test
public void liveReloadOnClassPathChanged() throws Exception {
void liveReloadOnClassPathChanged() throws Exception {
configure();
Set<ChangedFiles> changeSet = new HashSet<>();
ClassPathChangedEvent event = new ClassPathChangedEvent(this, changeSet, false);
@@ -119,14 +115,14 @@ public class RemoteClientConfigurationTests {
}
@Test
public void liveReloadDisabled() {
void liveReloadDisabled() {
configure("spring.devtools.livereload.enabled:false");
assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
.isThrownBy(() -> this.context.getBean(OptionalLiveReloadServer.class));
}
@Test
public void remoteRestartDisabled() {
void remoteRestartDisabled() {
configure("spring.devtools.remote.restart.enabled:false");
assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
.isThrownBy(() -> this.context.getBean(ClassPathFileSystemWatcher.class));

View File

@@ -22,8 +22,8 @@ import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
@@ -49,7 +49,7 @@ import static org.mockito.Mockito.verifyZeroInteractions;
*
* @author Phillip Webb
*/
public class DispatcherFilterTests {
class DispatcherFilterTests {
@Mock
private Dispatcher dispatcher;
@@ -65,20 +65,20 @@ public class DispatcherFilterTests {
private DispatcherFilter filter;
@Before
@BeforeEach
public void setup() {
MockitoAnnotations.initMocks(this);
this.filter = new DispatcherFilter(this.dispatcher);
}
@Test
public void dispatcherMustNotBeNull() {
void dispatcherMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new DispatcherFilter(null))
.withMessageContaining("Dispatcher must not be null");
}
@Test
public void ignoresNotServletRequests() throws Exception {
void ignoresNotServletRequests() throws Exception {
ServletRequest request = mock(ServletRequest.class);
ServletResponse response = mock(ServletResponse.class);
this.filter.doFilter(request, response, this.chain);
@@ -87,7 +87,7 @@ public class DispatcherFilterTests {
}
@Test
public void ignoredByDispatcher() throws Exception {
void ignoredByDispatcher() throws Exception {
HttpServletRequest request = new MockHttpServletRequest("GET", "/hello");
HttpServletResponse response = new MockHttpServletResponse();
this.filter.doFilter(request, response, this.chain);
@@ -95,7 +95,7 @@ public class DispatcherFilterTests {
}
@Test
public void handledByDispatcher() throws Exception {
void handledByDispatcher() throws Exception {
HttpServletRequest request = new MockHttpServletRequest("GET", "/hello");
HttpServletResponse response = new MockHttpServletResponse();
willReturn(true).given(this.dispatcher).handle(any(ServerHttpRequest.class), any(ServerHttpResponse.class));

View File

@@ -20,8 +20,8 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
@@ -49,7 +49,7 @@ import static org.mockito.Mockito.withSettings;
*
* @author Phillip Webb
*/
public class DispatcherTests {
class DispatcherTests {
@Mock
private AccessManager accessManager;
@@ -62,7 +62,7 @@ public class DispatcherTests {
private ServerHttpResponse serverResponse;
@Before
@BeforeEach
public void setup() {
MockitoAnnotations.initMocks(this);
this.request = new MockHttpServletRequest();
@@ -72,19 +72,19 @@ public class DispatcherTests {
}
@Test
public void accessManagerMustNotBeNull() {
void accessManagerMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new Dispatcher(null, Collections.emptyList()))
.withMessageContaining("AccessManager must not be null");
}
@Test
public void mappersMustNotBeNull() {
void mappersMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new Dispatcher(this.accessManager, null))
.withMessageContaining("Mappers must not be null");
}
@Test
public void accessManagerVetoRequest() throws Exception {
void accessManagerVetoRequest() throws Exception {
given(this.accessManager.isAllowed(any(ServerHttpRequest.class))).willReturn(false);
HandlerMapper mapper = mock(HandlerMapper.class);
Handler handler = mock(Handler.class);
@@ -96,7 +96,7 @@ public class DispatcherTests {
}
@Test
public void accessManagerAllowRequest() throws Exception {
void accessManagerAllowRequest() throws Exception {
given(this.accessManager.isAllowed(any(ServerHttpRequest.class))).willReturn(true);
HandlerMapper mapper = mock(HandlerMapper.class);
Handler handler = mock(Handler.class);
@@ -107,7 +107,7 @@ public class DispatcherTests {
}
@Test
public void ordersMappers() throws Exception {
void ordersMappers() throws Exception {
HandlerMapper mapper1 = mock(HandlerMapper.class, withSettings().extraInterfaces(Ordered.class));
HandlerMapper mapper2 = mock(HandlerMapper.class, withSettings().extraInterfaces(Ordered.class));
given(((Ordered) mapper1).getOrder()).willReturn(1);

View File

@@ -16,8 +16,8 @@
package org.springframework.boot.devtools.remote.server;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServletServerHttpRequest;
@@ -32,7 +32,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
* @author Rob Winch
* @author Phillip Webb
*/
public class HttpHeaderAccessManagerTests {
class HttpHeaderAccessManagerTests {
private static final String HEADER = "X-AUTH_TOKEN";
@@ -44,7 +44,7 @@ public class HttpHeaderAccessManagerTests {
private HttpHeaderAccessManager manager;
@Before
@BeforeEach
public void setup() {
this.request = new MockHttpServletRequest("GET", "/");
this.serverRequest = new ServletServerHttpRequest(this.request);
@@ -52,48 +52,48 @@ public class HttpHeaderAccessManagerTests {
}
@Test
public void headerNameMustNotBeNull() {
void headerNameMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderAccessManager(null, SECRET))
.withMessageContaining("HeaderName must not be empty");
}
@Test
public void headerNameMustNotBeEmpty() {
void headerNameMustNotBeEmpty() {
assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderAccessManager("", SECRET))
.withMessageContaining("HeaderName must not be empty");
}
@Test
public void expectedSecretMustNotBeNull() {
void expectedSecretMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderAccessManager(HEADER, null))
.withMessageContaining("ExpectedSecret must not be empty");
}
@Test
public void expectedSecretMustNotBeEmpty() {
void expectedSecretMustNotBeEmpty() {
assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderAccessManager(HEADER, ""))
.withMessageContaining("ExpectedSecret must not be empty");
}
@Test
public void allowsMatching() {
void allowsMatching() {
this.request.addHeader(HEADER, SECRET);
assertThat(this.manager.isAllowed(this.serverRequest)).isTrue();
}
@Test
public void disallowsWrongSecret() {
void disallowsWrongSecret() {
this.request.addHeader(HEADER, "wrong");
assertThat(this.manager.isAllowed(this.serverRequest)).isFalse();
}
@Test
public void disallowsNoSecret() {
void disallowsNoSecret() {
assertThat(this.manager.isAllowed(this.serverRequest)).isFalse();
}
@Test
public void disallowsWrongHeader() {
void disallowsWrongHeader() {
this.request.addHeader("X-WRONG", SECRET);
assertThat(this.manager.isAllowed(this.serverRequest)).isFalse();
}

View File

@@ -1,5 +1,5 @@
/*
* 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");
* you may not use this file except in compliance with the License.
@@ -16,8 +16,8 @@
package org.springframework.boot.devtools.remote.server;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServerHttpRequest;
@@ -35,7 +35,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
*
* @author Phillip Webb
*/
public class HttpStatusHandlerTests {
class HttpStatusHandlerTests {
private MockHttpServletRequest servletRequest;
@@ -45,7 +45,7 @@ public class HttpStatusHandlerTests {
private ServerHttpRequest request;
@Before
@BeforeEach
public void setup() {
this.servletRequest = new MockHttpServletRequest();
this.servletResponse = new MockHttpServletResponse();
@@ -54,20 +54,20 @@ public class HttpStatusHandlerTests {
}
@Test
public void statusMustNotBeNull() {
void statusMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new HttpStatusHandler(null))
.withMessageContaining("Status must not be null");
}
@Test
public void respondsOk() throws Exception {
void respondsOk() throws Exception {
HttpStatusHandler handler = new HttpStatusHandler();
handler.handle(this.request, this.response);
assertThat(this.servletResponse.getStatus()).isEqualTo(200);
}
@Test
public void respondsWithStatus() throws Exception {
void respondsWithStatus() throws Exception {
HttpStatusHandler handler = new HttpStatusHandler(HttpStatus.I_AM_A_TEAPOT);
handler.handle(this.request, this.response);
assertThat(this.servletResponse.getStatus()).isEqualTo(418);

View File

@@ -18,7 +18,7 @@ package org.springframework.boot.devtools.remote.server;
import javax.servlet.http.HttpServletRequest;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServletServerHttpRequest;
@@ -34,30 +34,30 @@ import static org.mockito.Mockito.mock;
* @author Rob Winch
* @author Phillip Webb
*/
public class UrlHandlerMapperTests {
class UrlHandlerMapperTests {
private Handler handler = mock(Handler.class);
@Test
public void requestUriMustNotBeNull() {
void requestUriMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new UrlHandlerMapper(null, this.handler))
.withMessageContaining("URL must not be empty");
}
@Test
public void requestUriMustNotBeEmpty() {
void requestUriMustNotBeEmpty() {
assertThatIllegalArgumentException().isThrownBy(() -> new UrlHandlerMapper("", this.handler))
.withMessageContaining("URL must not be empty");
}
@Test
public void requestUrlMustStartWithSlash() {
void requestUrlMustStartWithSlash() {
assertThatIllegalArgumentException().isThrownBy(() -> new UrlHandlerMapper("tunnel", this.handler))
.withMessageContaining("URL must start with '/'");
}
@Test
public void handlesMatchedUrl() {
void handlesMatchedUrl() {
UrlHandlerMapper mapper = new UrlHandlerMapper("/tunnel", this.handler);
HttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/tunnel");
ServerHttpRequest request = new ServletServerHttpRequest(servletRequest);
@@ -65,7 +65,7 @@ public class UrlHandlerMapperTests {
}
@Test
public void ignoresDifferentUrl() {
void ignoresDifferentUrl() {
UrlHandlerMapper mapper = new UrlHandlerMapper("/tunnel", this.handler);
HttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/tunnel/other");
ServerHttpRequest request = new ServletServerHttpRequest(servletRequest);

View File

@@ -21,14 +21,14 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.UUID;
import java.util.jar.Attributes;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipOutputStream;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.util.StringUtils;
@@ -40,37 +40,39 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Phillip Webb
* @author Andy Wilkinson
*/
public class ChangeableUrlsTests {
class ChangeableUrlsTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@TempDir
File tempDir;
@Test
public void folderUrl() throws Exception {
void folderUrl() throws Exception {
URL url = makeUrl("myproject");
assertThat(ChangeableUrls.fromUrls(url).size()).isEqualTo(1);
}
@Test
public void fileUrl() throws Exception {
URL url = this.temporaryFolder.newFile().toURI().toURL();
void fileUrl() throws Exception {
File file = new File(this.tempDir, "file");
file.createNewFile();
URL url = file.toURI().toURL();
assertThat(ChangeableUrls.fromUrls(url)).isEmpty();
}
@Test
public void httpUrl() throws Exception {
void httpUrl() throws Exception {
URL url = new URL("https://spring.io");
assertThat(ChangeableUrls.fromUrls(url)).isEmpty();
}
@Test
public void httpsUrl() throws Exception {
void httpsUrl() throws Exception {
URL url = new URL("https://spring.io");
assertThat(ChangeableUrls.fromUrls(url)).isEmpty();
}
@Test
public void skipsUrls() throws Exception {
void skipsUrls() throws Exception {
ChangeableUrls urls = ChangeableUrls.fromUrls(makeUrl("spring-boot"), makeUrl("spring-boot-autoconfigure"),
makeUrl("spring-boot-actuator"), makeUrl("spring-boot-starter"),
makeUrl("spring-boot-starter-some-thing"));
@@ -78,9 +80,12 @@ public class ChangeableUrlsTests {
}
@Test
public void urlsFromJarClassPathAreConsidered() throws Exception {
File relative = this.temporaryFolder.newFolder();
URL absoluteUrl = this.temporaryFolder.newFolder().toURI().toURL();
void urlsFromJarClassPathAreConsidered() throws Exception {
File relative = new File(this.tempDir, UUID.randomUUID().toString());
relative.mkdir();
File absolute = new File(this.tempDir, UUID.randomUUID().toString());
absolute.mkdirs();
URL absoluteUrl = absolute.toURI().toURL();
File jarWithClassPath = makeJarFileWithUrlsInManifestClassPath("project-core/target/classes/",
"project-web/target/classes/", "does-not-exist/target/classes", relative.getName() + "/", absoluteUrl);
new File(jarWithClassPath.getParentFile(), "project-core/target/classes").mkdirs();
@@ -94,7 +99,7 @@ public class ChangeableUrlsTests {
}
private URL makeUrl(String name) throws IOException {
File file = this.temporaryFolder.newFolder();
File file = new File(this.tempDir, UUID.randomUUID().toString());
file = new File(file, name);
file = new File(file, "target");
file = new File(file, "classes");
@@ -103,7 +108,7 @@ public class ChangeableUrlsTests {
}
private File makeJarFileWithUrlsInManifestClassPath(Object... urls) throws Exception {
File classpathJar = this.temporaryFolder.newFile("classpath.jar");
File classpathJar = new File(this.tempDir, "classpath.jar");
Manifest manifest = new Manifest();
manifest.getMainAttributes().putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0");
manifest.getMainAttributes().putValue(Attributes.Name.CLASS_PATH.toString(),
@@ -113,7 +118,7 @@ public class ChangeableUrlsTests {
}
private URL makeJarFileWithNoManifest() throws Exception {
File classpathJar = this.temporaryFolder.newFile("no-manifest.jar");
File classpathJar = new File(this.tempDir, "no-manifest.jar");
new ZipOutputStream(new FileOutputStream(classpathJar)).close();
return classpathJar.toURI().toURL();
}

View File

@@ -19,10 +19,9 @@ package org.springframework.boot.devtools.restart;
import java.io.File;
import java.io.IOException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.devtools.restart.ClassLoaderFilesResourcePatternResolver.DeletedClassLoaderFileResource;
import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile;
@@ -52,34 +51,31 @@ import static org.mockito.Mockito.verify;
* @author Andy Wilkinson
* @author Stephane Nicoll
*/
public class ClassLoaderFilesResourcePatternResolverTests {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
class ClassLoaderFilesResourcePatternResolverTests {
private ClassLoaderFiles files;
private ClassLoaderFilesResourcePatternResolver resolver;
@Before
@BeforeEach
public void setup() {
this.files = new ClassLoaderFiles();
this.resolver = new ClassLoaderFilesResourcePatternResolver(new GenericApplicationContext(), this.files);
}
@Test
public void getClassLoaderShouldReturnClassLoader() {
void getClassLoaderShouldReturnClassLoader() {
assertThat(this.resolver.getClassLoader()).isNotNull();
}
@Test
public void getResourceShouldReturnResource() {
void getResourceShouldReturnResource() {
Resource resource = this.resolver.getResource("index.html");
assertThat(resource).isNotNull().isInstanceOf(ClassPathResource.class);
}
@Test
public void getResourceWhenHasServletContextShouldReturnServletResource() {
void getResourceWhenHasServletContextShouldReturnServletResource() {
GenericWebApplicationContext context = new GenericWebApplicationContext(new MockServletContext());
this.resolver = new ClassLoaderFilesResourcePatternResolver(context, this.files);
Resource resource = this.resolver.getResource("index.html");
@@ -87,8 +83,7 @@ public class ClassLoaderFilesResourcePatternResolverTests {
}
@Test
public void getResourceWhenDeletedShouldReturnDeletedResource() throws Exception {
File folder = this.temp.newFolder();
void getResourceWhenDeletedShouldReturnDeletedResource(@TempDir File folder) throws Exception {
File file = createFile(folder, "name.class");
this.files.addFile(folder.getName(), "name.class", new ClassLoaderFile(Kind.DELETED, null));
Resource resource = this.resolver.getResource("file:" + file.getAbsolutePath());
@@ -96,16 +91,14 @@ public class ClassLoaderFilesResourcePatternResolverTests {
}
@Test
public void getResourcesShouldReturnResources() throws Exception {
File folder = this.temp.newFolder();
void getResourcesShouldReturnResources(@TempDir File folder) throws Exception {
createFile(folder, "name.class");
Resource[] resources = this.resolver.getResources("file:" + folder.getAbsolutePath() + "/**");
assertThat(resources).isNotEmpty();
}
@Test
public void getResourcesWhenDeletedShouldFilterDeleted() throws Exception {
File folder = this.temp.newFolder();
void getResourcesWhenDeletedShouldFilterDeleted(@TempDir File folder) throws Exception {
createFile(folder, "name.class");
this.files.addFile(folder.getName(), "name.class", new ClassLoaderFile(Kind.DELETED, null));
Resource[] resources = this.resolver.getResources("file:" + folder.getAbsolutePath() + "/**");
@@ -113,7 +106,7 @@ public class ClassLoaderFilesResourcePatternResolverTests {
}
@Test
public void customResourceLoaderIsUsedInNonWebApplication() {
void customResourceLoaderIsUsedInNonWebApplication() {
GenericApplicationContext context = new GenericApplicationContext();
ResourceLoader resourceLoader = mock(ResourceLoader.class);
context.setResourceLoader(resourceLoader);
@@ -123,7 +116,7 @@ public class ClassLoaderFilesResourcePatternResolverTests {
}
@Test
public void customProtocolResolverIsUsedInNonWebApplication() {
void customProtocolResolverIsUsedInNonWebApplication() {
GenericApplicationContext context = new GenericApplicationContext();
Resource resource = mock(Resource.class);
ProtocolResolver resolver = mockProtocolResolver("foo:some-file.txt", resource);
@@ -135,7 +128,7 @@ public class ClassLoaderFilesResourcePatternResolverTests {
}
@Test
public void customResourceLoaderIsUsedInWebApplication() {
void customResourceLoaderIsUsedInWebApplication() {
GenericWebApplicationContext context = new GenericWebApplicationContext(new MockServletContext());
ResourceLoader resourceLoader = mock(ResourceLoader.class);
context.setResourceLoader(resourceLoader);
@@ -145,7 +138,7 @@ public class ClassLoaderFilesResourcePatternResolverTests {
}
@Test
public void customProtocolResolverIsUsedInWebApplication() {
void customProtocolResolverIsUsedInWebApplication() {
GenericWebApplicationContext context = new GenericWebApplicationContext(new MockServletContext());
Resource resource = mock(Resource.class);
ProtocolResolver resolver = mockProtocolResolver("foo:some-file.txt", resource);

View File

@@ -16,7 +16,7 @@
package org.springframework.boot.devtools.restart;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
@@ -29,30 +29,30 @@ import static org.mockito.Mockito.mock;
* @author Andy Wilkinson
* @author Madhura Bhave
*/
public class DefaultRestartInitializerTests {
class DefaultRestartInitializerTests {
@Test
public void jUnitStackShouldReturnNull() {
void jUnitStackShouldReturnNull() {
testSkippedStacks("org.junit.runners.Something");
}
@Test
public void jUnit5StackShouldReturnNull() {
void jUnit5StackShouldReturnNull() {
testSkippedStacks("org.junit.platform.Something");
}
@Test
public void springTestStackShouldReturnNull() {
void springTestStackShouldReturnNull() {
testSkippedStacks("org.springframework.boot.test.Something");
}
@Test
public void cucumberStackShouldReturnNull() {
void cucumberStackShouldReturnNull() {
testSkippedStacks("cucumber.runtime.Runtime.run");
}
@Test
public void validMainThreadShouldReturnUrls() {
void validMainThreadShouldReturnUrls() {
DefaultRestartInitializer initializer = new DefaultRestartInitializer();
ClassLoader classLoader = new MockAppClassLoader(getClass().getClassLoader());
Thread thread = new Thread();
@@ -62,7 +62,7 @@ public class DefaultRestartInitializerTests {
}
@Test
public void threadNotNamedMainShouldReturnNull() {
void threadNotNamedMainShouldReturnNull() {
DefaultRestartInitializer initializer = new DefaultRestartInitializer();
ClassLoader classLoader = new MockAppClassLoader(getClass().getClassLoader());
Thread thread = new Thread();
@@ -72,7 +72,7 @@ public class DefaultRestartInitializerTests {
}
@Test
public void threadNotUsingAppClassLoader() {
void threadNotUsingAppClassLoader() {
DefaultRestartInitializer initializer = new DefaultRestartInitializer();
ClassLoader classLoader = new MockLauncherClassLoader(getClass().getClassLoader());
Thread thread = new Thread();
@@ -82,7 +82,7 @@ public class DefaultRestartInitializerTests {
}
@Test
public void urlsCanBeRetrieved() {
void urlsCanBeRetrieved() {
assertThat(new DefaultRestartInitializer().getUrls(Thread.currentThread())).isNotEmpty();
}

View File

@@ -18,8 +18,8 @@ package org.springframework.boot.devtools.restart;
import java.lang.reflect.Method;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.util.ReflectionUtils;
@@ -32,38 +32,38 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
*
* @author Phillip Webb
*/
public class MainMethodTests {
class MainMethodTests {
private static ThreadLocal<MainMethod> mainMethod = new ThreadLocal<>();
private Method actualMain;
@Before
@BeforeEach
public void setup() throws Exception {
this.actualMain = Valid.class.getMethod("main", String[].class);
}
@Test
public void threadMustNotBeNull() {
void threadMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new MainMethod(null))
.withMessageContaining("Thread must not be null");
}
@Test
public void validMainMethod() throws Exception {
void validMainMethod() throws Exception {
MainMethod method = new TestThread(Valid::main).test();
assertThat(method.getMethod()).isEqualTo(this.actualMain);
assertThat(method.getDeclaringClassName()).isEqualTo(this.actualMain.getDeclaringClass().getName());
}
@Test
public void missingArgsMainMethod() throws Exception {
void missingArgsMainMethod() throws Exception {
assertThatIllegalStateException().isThrownBy(() -> new TestThread(MissingArgs::main).test())
.withMessageContaining("Unable to find main method");
}
@Test
public void nonStatic() throws Exception {
void nonStatic() throws Exception {
assertThatIllegalStateException().isThrownBy(() -> new TestThread(() -> new NonStaticMain().main()).test())
.withMessageContaining("Unable to find main method");
}

View File

@@ -20,9 +20,12 @@ import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
import org.springframework.beans.factory.ObjectFactory;
@@ -36,33 +39,29 @@ import static org.mockito.Mockito.mock;
*
* @author Phillip Webb
*/
public class MockRestarter implements TestRule {
public class MockRestarter implements BeforeEachCallback, AfterEachCallback, ParameterResolver {
private Map<String, Object> attributes = new HashMap<>();
private Restarter mock = mock(Restarter.class);
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
setup();
base.evaluate();
cleanup();
}
};
public Restarter getMock() {
return this.mock;
}
@SuppressWarnings("rawtypes")
private void setup() {
@Override
public void afterEach(ExtensionContext context) throws Exception {
this.attributes.clear();
Restarter.clearInstance();
}
@Override
public void beforeEach(ExtensionContext context) throws Exception {
Restarter.setInstance(this.mock);
given(this.mock.getInitialUrls()).willReturn(new URL[] {});
given(this.mock.getOrAddAttribute(anyString(), any(ObjectFactory.class))).willAnswer((invocation) -> {
String name = invocation.getArgument(0);
ObjectFactory factory = invocation.getArgument(1);
ObjectFactory<?> factory = invocation.getArgument(1);
Object attribute = MockRestarter.this.attributes.get(name);
if (attribute == null) {
attribute = factory.getObject();
@@ -73,12 +72,15 @@ public class MockRestarter implements TestRule {
given(this.mock.getThreadFactory()).willReturn(Thread::new);
}
private void cleanup() {
this.attributes.clear();
Restarter.clearInstance();
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
throws ParameterResolutionException {
return parameterContext.getParameter().getType().equals(Restarter.class);
}
public Restarter getMock() {
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
throws ParameterResolutionException {
return this.mock;
}

View File

@@ -18,9 +18,9 @@ package org.springframework.boot.devtools.restart;
import java.net.URL;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
@@ -37,18 +37,18 @@ import static org.mockito.Mockito.mock;
*
* @author Phillip Webb
*/
public class OnInitializedRestarterConditionTests {
class OnInitializedRestarterConditionTests {
private static Object wait = new Object();
@Before
@After
@BeforeEach
@AfterEach
public void cleanup() {
Restarter.clearInstance();
}
@Test
public void noInstance() {
void noInstance() {
Restarter.clearInstance();
ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
assertThat(context.containsBean("bean")).isFalse();
@@ -56,7 +56,7 @@ public class OnInitializedRestarterConditionTests {
}
@Test
public void noInitialization() {
void noInitialization() {
Restarter.initialize(new String[0], false, RestartInitializer.NONE);
ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
assertThat(context.containsBean("bean")).isFalse();
@@ -64,7 +64,7 @@ public class OnInitializedRestarterConditionTests {
}
@Test
public void initialized() throws Exception {
void initialized() throws Exception {
Thread thread = new Thread(TestInitialized::main);
thread.start();
synchronized (wait) {

View File

@@ -18,17 +18,18 @@ package org.springframework.boot.devtools.restart;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.event.ApplicationFailedEvent;
import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.context.event.ApplicationStartingEvent;
import org.springframework.boot.test.system.OutputCaptureRule;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.test.util.ReflectionTestUtils;
@@ -43,29 +44,27 @@ import static org.mockito.Mockito.mock;
* @author Phillip Webb
* @author Andy Wilkinson
*/
public class RestartApplicationListenerTests {
@ExtendWith(OutputCaptureExtension.class)
class RestartApplicationListenerTests {
private static final String ENABLED_PROPERTY = "spring.devtools.restart.enabled";
private static final String[] ARGS = new String[] { "a", "b", "c" };
@Rule
public final OutputCaptureRule output = new OutputCaptureRule();
@Before
@After
@BeforeEach
@AfterEach
public void cleanup() {
Restarter.clearInstance();
System.clearProperty(ENABLED_PROPERTY);
}
@Test
public void isHighestPriority() {
void isHighestPriority() {
assertThat(new RestartApplicationListener().getOrder()).isEqualTo(Ordered.HIGHEST_PRECEDENCE);
}
@Test
public void initializeWithReady() {
void initializeWithReady() {
testInitialize(false);
assertThat(Restarter.getInstance()).hasFieldOrPropertyWithValue("args", ARGS);
assertThat(Restarter.getInstance().isFinished()).isTrue();
@@ -73,7 +72,7 @@ public class RestartApplicationListenerTests {
}
@Test
public void initializeWithFail() {
void initializeWithFail() {
testInitialize(true);
assertThat(Restarter.getInstance()).hasFieldOrPropertyWithValue("args", ARGS);
assertThat(Restarter.getInstance().isFinished()).isTrue();
@@ -81,11 +80,11 @@ public class RestartApplicationListenerTests {
}
@Test
public void disableWithSystemProperty() {
void disableWithSystemProperty(CapturedOutput capturedOutput) {
System.setProperty(ENABLED_PROPERTY, "false");
testInitialize(false);
assertThat(Restarter.getInstance()).hasFieldOrPropertyWithValue("enabled", false);
assertThat(this.output.toString()).contains("Restart disabled due to System property");
assertThat(capturedOutput).contains("Restart disabled due to System property");
}
private void testInitialize(boolean failed) {

View File

@@ -18,7 +18,7 @@ package org.springframework.boot.devtools.restart;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
@@ -35,14 +35,14 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Phillip Webb
*/
public class RestartScopeInitializerTests {
class RestartScopeInitializerTests {
private static AtomicInteger createCount;
private static AtomicInteger refreshCount;
@Test
public void restartScope() {
void restartScope() {
createCount = new AtomicInteger();
refreshCount = new AtomicInteger();
ConfigurableApplicationContext context = runApplication();

View File

@@ -22,16 +22,17 @@ import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.ThreadFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile;
import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile.Kind;
import org.springframework.boot.devtools.restart.classloader.ClassLoaderFiles;
import org.springframework.boot.test.system.OutputCaptureRule;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.event.ContextClosedEvent;
@@ -54,35 +55,33 @@ import static org.mockito.Mockito.verifyZeroInteractions;
* @author Phillip Webb
* @author Andy Wilkinson
*/
public class RestarterTests {
@ExtendWith(OutputCaptureExtension.class)
class RestarterTests {
@Rule
public OutputCaptureRule out = new OutputCaptureRule();
@Before
@BeforeEach
public void setup() {
RestarterInitializer.setRestarterInstance();
}
@After
@AfterEach
public void cleanup() {
Restarter.clearInstance();
}
@Test
public void cantGetInstanceBeforeInitialize() {
void cantGetInstanceBeforeInitialize() {
Restarter.clearInstance();
assertThatIllegalStateException().isThrownBy(Restarter::getInstance)
.withMessageContaining("Restarter has not been initialized");
}
@Test
public void testRestart() throws Exception {
void testRestart(CapturedOutput capturedOutput) throws Exception {
Restarter.clearInstance();
Thread thread = new Thread(SampleApplication::main);
thread.start();
Thread.sleep(2600);
String output = this.out.toString();
String output = capturedOutput.toString();
assertThat(StringUtils.countOccurrencesOf(output, "Tick 0")).isGreaterThan(1);
assertThat(StringUtils.countOccurrencesOf(output, "Tick 1")).isGreaterThan(1);
assertThat(CloseCountingApplicationListener.closed).isGreaterThan(0);
@@ -90,7 +89,7 @@ public class RestarterTests {
@Test
@SuppressWarnings("rawtypes")
public void getOrAddAttributeWithNewAttribute() {
void getOrAddAttributeWithNewAttribute() {
ObjectFactory objectFactory = mock(ObjectFactory.class);
given(objectFactory.getObject()).willReturn("abc");
Object attribute = Restarter.getInstance().getOrAddAttribute("x", objectFactory);
@@ -98,13 +97,13 @@ public class RestarterTests {
}
@Test
public void addUrlsMustNotBeNull() {
void addUrlsMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> Restarter.getInstance().addUrls(null))
.withMessageContaining("Urls must not be null");
}
@Test
public void addUrls() throws Exception {
void addUrls() throws Exception {
URL url = new URL("file:/proj/module-a.jar!/");
Collection<URL> urls = Collections.singleton(url);
Restarter restarter = Restarter.getInstance();
@@ -115,13 +114,13 @@ public class RestarterTests {
}
@Test
public void addClassLoaderFilesMustNotBeNull() {
void addClassLoaderFilesMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> Restarter.getInstance().addClassLoaderFiles(null))
.withMessageContaining("ClassLoaderFiles must not be null");
}
@Test
public void addClassLoaderFiles() {
void addClassLoaderFiles() {
ClassLoaderFiles classLoaderFiles = new ClassLoaderFiles();
classLoaderFiles.addFile("f", new ClassLoaderFile(Kind.ADDED, "abc".getBytes()));
Restarter restarter = Restarter.getInstance();
@@ -133,7 +132,7 @@ public class RestarterTests {
@Test
@SuppressWarnings("rawtypes")
public void getOrAddAttributeWithExistingAttribute() {
void getOrAddAttributeWithExistingAttribute() {
Restarter.getInstance().getOrAddAttribute("x", () -> "abc");
ObjectFactory objectFactory = mock(ObjectFactory.class);
Object attribute = Restarter.getInstance().getOrAddAttribute("x", objectFactory);
@@ -142,7 +141,7 @@ public class RestarterTests {
}
@Test
public void getThreadFactory() throws Exception {
void getThreadFactory() throws Exception {
final ClassLoader parentLoader = Thread.currentThread().getContextClassLoader();
final ClassLoader contextClassLoader = new URLClassLoader(new URL[0]);
Thread thread = new Thread(() -> {
@@ -161,7 +160,7 @@ public class RestarterTests {
}
@Test
public void getInitialUrls() throws Exception {
void getInitialUrls() throws Exception {
Restarter.clearInstance();
RestartInitializer initializer = mock(RestartInitializer.class);
URL[] urls = new URL[] { new URL("file:/proj/module-a.jar!/") };

View File

@@ -18,10 +18,10 @@ package org.springframework.boot.devtools.restart;
import java.util.concurrent.CountDownLatch;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Tests for {@link SilentExitExceptionHandler}.
@@ -29,10 +29,10 @@ import static org.junit.Assert.fail;
* @author Phillip Webb
* @author Andy Wilkinson
*/
public class SilentExitExceptionHandlerTests {
class SilentExitExceptionHandlerTests {
@Test
public void setupAndExit() throws Exception {
void setupAndExit() throws Exception {
TestThread testThread = new TestThread() {
@Override
public void run() {
@@ -46,7 +46,7 @@ public class SilentExitExceptionHandlerTests {
}
@Test
public void doesntInterfereWithOtherExceptions() throws Exception {
void doesntInterfereWithOtherExceptions() throws Exception {
TestThread testThread = new TestThread() {
@Override
public void run() {
@@ -59,7 +59,7 @@ public class SilentExitExceptionHandlerTests {
}
@Test
public void preventsNonZeroExitCodeWhenAllOtherThreadsAreDaemonThreads() {
void preventsNonZeroExitCodeWhenAllOtherThreadsAreDaemonThreads() {
try {
SilentExitExceptionHandler.exitCurrentThread();
}

View File

@@ -16,7 +16,7 @@
package org.springframework.boot.devtools.restart.classloader;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile.Kind;
@@ -28,50 +28,50 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
*
* @author Phillip Webb
*/
public class ClassLoaderFileTests {
class ClassLoaderFileTests {
public static final byte[] BYTES = "ABC".getBytes();
@Test
public void kindMustNotBeNull() {
void kindMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFile(null, null))
.withMessageContaining("Kind must not be null");
}
@Test
public void addedContentsMustNotBeNull() {
void addedContentsMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFile(Kind.ADDED, null))
.withMessageContaining("Contents must not be null");
}
@Test
public void modifiedContentsMustNotBeNull() {
void modifiedContentsMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFile(Kind.MODIFIED, null))
.withMessageContaining("Contents must not be null");
}
@Test
public void deletedContentsMustBeNull() {
void deletedContentsMustBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFile(Kind.DELETED, new byte[10]))
.withMessageContaining("Contents must be null");
}
@Test
public void added() {
void added() {
ClassLoaderFile file = new ClassLoaderFile(Kind.ADDED, BYTES);
assertThat(file.getKind()).isEqualTo(ClassLoaderFile.Kind.ADDED);
assertThat(file.getContents()).isEqualTo(BYTES);
}
@Test
public void modified() {
void modified() {
ClassLoaderFile file = new ClassLoaderFile(Kind.MODIFIED, BYTES);
assertThat(file.getKind()).isEqualTo(ClassLoaderFile.Kind.MODIFIED);
assertThat(file.getContents()).isEqualTo(BYTES);
}
@Test
public void deleted() {
void deleted() {
ClassLoaderFile file = new ClassLoaderFile(Kind.DELETED, null);
assertThat(file.getKind()).isEqualTo(ClassLoaderFile.Kind.DELETED);
assertThat(file.getContents()).isNull();

View File

@@ -22,7 +22,7 @@ import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Iterator;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile.Kind;
import org.springframework.boot.devtools.restart.classloader.ClassLoaderFiles.SourceFolder;
@@ -36,41 +36,41 @@ import static org.mockito.Mockito.mock;
*
* @author Phillip Webb
*/
public class ClassLoaderFilesTests {
class ClassLoaderFilesTests {
private ClassLoaderFiles files = new ClassLoaderFiles();
@Test
public void addFileNameMustNotBeNull() {
void addFileNameMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.files.addFile(null, mock(ClassLoaderFile.class)))
.withMessageContaining("Name must not be null");
}
@Test
public void addFileFileMustNotBeNull() {
void addFileFileMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.files.addFile("test", null))
.withMessageContaining("File must not be null");
}
@Test
public void getFileWithNullName() {
void getFileWithNullName() {
assertThat(this.files.getFile(null)).isNull();
}
@Test
public void addAndGet() {
void addAndGet() {
ClassLoaderFile file = new ClassLoaderFile(Kind.ADDED, new byte[10]);
this.files.addFile("myfile", file);
assertThat(this.files.getFile("myfile")).isEqualTo(file);
}
@Test
public void getMissing() {
void getMissing() {
assertThat(this.files.getFile("missing")).isNull();
}
@Test
public void addTwice() {
void addTwice() {
ClassLoaderFile file1 = new ClassLoaderFile(Kind.ADDED, new byte[10]);
ClassLoaderFile file2 = new ClassLoaderFile(Kind.MODIFIED, new byte[10]);
this.files.addFile("myfile", file1);
@@ -79,7 +79,7 @@ public class ClassLoaderFilesTests {
}
@Test
public void addTwiceInDifferentSourceFolders() {
void addTwiceInDifferentSourceFolders() {
ClassLoaderFile file1 = new ClassLoaderFile(Kind.ADDED, new byte[10]);
ClassLoaderFile file2 = new ClassLoaderFile(Kind.MODIFIED, new byte[10]);
this.files.addFile("a", "myfile", file1);
@@ -90,7 +90,7 @@ public class ClassLoaderFilesTests {
}
@Test
public void getSourceFolders() {
void getSourceFolders() {
ClassLoaderFile file1 = new ClassLoaderFile(Kind.ADDED, new byte[10]);
ClassLoaderFile file2 = new ClassLoaderFile(Kind.MODIFIED, new byte[10]);
ClassLoaderFile file3 = new ClassLoaderFile(Kind.MODIFIED, new byte[10]);
@@ -110,7 +110,7 @@ public class ClassLoaderFilesTests {
}
@Test
public void serialize() throws Exception {
void serialize() throws Exception {
ClassLoaderFile file = new ClassLoaderFile(Kind.ADDED, new byte[10]);
this.files.addFile("myfile", file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
@@ -123,7 +123,7 @@ public class ClassLoaderFilesTests {
}
@Test
public void addAll() {
void addAll() {
ClassLoaderFile file1 = new ClassLoaderFile(Kind.ADDED, new byte[10]);
this.files.addFile("a", "myfile1", file1);
ClassLoaderFiles toAdd = new ClassLoaderFiles();
@@ -142,7 +142,7 @@ public class ClassLoaderFilesTests {
}
@Test
public void getSize() {
void getSize() {
this.files.addFile("s1", "n1", mock(ClassLoaderFile.class));
this.files.addFile("s1", "n2", mock(ClassLoaderFile.class));
this.files.addFile("s2", "n3", mock(ClassLoaderFile.class));
@@ -151,13 +151,13 @@ public class ClassLoaderFilesTests {
}
@Test
public void classLoaderFilesMustNotBeNull() {
void classLoaderFilesMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFiles(null))
.withMessageContaining("ClassLoaderFiles must not be null");
}
@Test
public void constructFromExistingSet() {
void constructFromExistingSet() {
this.files.addFile("s1", "n1", mock(ClassLoaderFile.class));
this.files.addFile("s1", "n2", mock(ClassLoaderFile.class));
ClassLoaderFiles copy = new ClassLoaderFiles(this.files);

View File

@@ -29,10 +29,9 @@ import java.util.List;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile.Kind;
import org.springframework.util.FileCopyUtils;
@@ -48,15 +47,12 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
* @author Phillip Webb
*/
@SuppressWarnings("resource")
public class RestartClassLoaderTests {
class RestartClassLoaderTests {
private static final String PACKAGE = RestartClassLoaderTests.class.getPackage().getName();
private static final String PACKAGE_PATH = PACKAGE.replace('.', '/');
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private File sampleJarFile;
private URLClassLoader parentClassLoader;
@@ -65,9 +61,9 @@ public class RestartClassLoaderTests {
private RestartClassLoader reloadClassLoader;
@Before
public void setup() throws Exception {
this.sampleJarFile = createSampleJarFile();
@BeforeEach
public void setup(@TempDir File tempDir) throws Exception {
this.sampleJarFile = createSampleJarFile(tempDir);
URL url = this.sampleJarFile.toURI().toURL();
ClassLoader classLoader = getClass().getClassLoader();
URL[] urls = new URL[] { url };
@@ -76,8 +72,8 @@ public class RestartClassLoaderTests {
this.reloadClassLoader = new RestartClassLoader(this.parentClassLoader, urls, this.updatedFiles);
}
private File createSampleJarFile() throws IOException {
File file = this.temp.newFile("sample.jar");
private File createSampleJarFile(File tempDir) throws IOException {
File file = new File(tempDir, "sample.jar");
JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(file));
jarOutputStream.putNextEntry(new ZipEntry(PACKAGE_PATH + "/Sample.class"));
StreamUtils.copy(getClass().getResourceAsStream("Sample.class"), jarOutputStream);
@@ -90,64 +86,64 @@ public class RestartClassLoaderTests {
}
@Test
public void parentMustNotBeNull() {
void parentMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new RestartClassLoader(null, new URL[] {}))
.withMessageContaining("Parent must not be null");
}
@Test
public void updatedFilesMustNotBeNull() {
void updatedFilesMustNotBeNull() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new RestartClassLoader(this.parentClassLoader, new URL[] {}, null))
.withMessageContaining("UpdatedFiles must not be null");
}
@Test
public void getResourceFromReloadableUrl() throws Exception {
void getResourceFromReloadableUrl() throws Exception {
String content = readString(this.reloadClassLoader.getResourceAsStream(PACKAGE_PATH + "/Sample.txt"));
assertThat(content).startsWith("fromchild");
}
@Test
public void getResourceFromParent() throws Exception {
void getResourceFromParent() throws Exception {
String content = readString(this.reloadClassLoader.getResourceAsStream(PACKAGE_PATH + "/Parent.txt"));
assertThat(content).startsWith("fromparent");
}
@Test
public void getResourcesFiltersDuplicates() throws Exception {
void getResourcesFiltersDuplicates() throws Exception {
List<URL> resources = toList(this.reloadClassLoader.getResources(PACKAGE_PATH + "/Sample.txt"));
assertThat(resources.size()).isEqualTo(1);
}
@Test
public void loadClassFromReloadableUrl() throws Exception {
void loadClassFromReloadableUrl() throws Exception {
Class<?> loaded = this.reloadClassLoader.loadClass(PACKAGE + ".Sample");
assertThat(loaded.getClassLoader()).isEqualTo(this.reloadClassLoader);
}
@Test
public void loadClassFromParent() throws Exception {
void loadClassFromParent() throws Exception {
Class<?> loaded = this.reloadClassLoader.loadClass(PACKAGE + ".SampleParent");
assertThat(loaded.getClassLoader()).isEqualTo(getClass().getClassLoader());
}
@Test
public void getDeletedResource() {
void getDeletedResource() {
String name = PACKAGE_PATH + "/Sample.txt";
this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.DELETED, null));
assertThat(this.reloadClassLoader.getResource(name)).isNull();
}
@Test
public void getDeletedResourceAsStream() {
void getDeletedResourceAsStream() {
String name = PACKAGE_PATH + "/Sample.txt";
this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.DELETED, null));
assertThat(this.reloadClassLoader.getResourceAsStream(name)).isNull();
}
@Test
public void getUpdatedResource() throws Exception {
void getUpdatedResource() throws Exception {
String name = PACKAGE_PATH + "/Sample.txt";
byte[] bytes = "abc".getBytes();
this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.MODIFIED, bytes));
@@ -156,7 +152,7 @@ public class RestartClassLoaderTests {
}
@Test
public void getResourcesWithDeleted() throws Exception {
void getResourcesWithDeleted() throws Exception {
String name = PACKAGE_PATH + "/Sample.txt";
this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.DELETED, null));
List<URL> resources = toList(this.reloadClassLoader.getResources(name));
@@ -164,7 +160,7 @@ public class RestartClassLoaderTests {
}
@Test
public void getResourcesWithUpdated() throws Exception {
void getResourcesWithUpdated() throws Exception {
String name = PACKAGE_PATH + "/Sample.txt";
byte[] bytes = "abc".getBytes();
this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.MODIFIED, bytes));
@@ -173,7 +169,7 @@ public class RestartClassLoaderTests {
}
@Test
public void getDeletedClass() throws Exception {
void getDeletedClass() throws Exception {
String name = PACKAGE_PATH + "/Sample.class";
this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.DELETED, null));
assertThatExceptionOfType(ClassNotFoundException.class)
@@ -181,7 +177,7 @@ public class RestartClassLoaderTests {
}
@Test
public void getUpdatedClass() throws Exception {
void getUpdatedClass() throws Exception {
String name = PACKAGE_PATH + "/Sample.class";
this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.MODIFIED, new byte[10]));
assertThatExceptionOfType(ClassFormatError.class)
@@ -189,7 +185,7 @@ public class RestartClassLoaderTests {
}
@Test
public void getAddedClass() throws Exception {
void getAddedClass() throws Exception {
String name = PACKAGE_PATH + "/SampleParent.class";
byte[] bytes = FileCopyUtils.copyToByteArray(getClass().getResourceAsStream("SampleParent.class"));
this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.ADDED, bytes));

View File

@@ -22,7 +22,7 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
@@ -31,7 +31,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Phillip Webb
*/
public class DefaultSourceFolderUrlFilterTests {
class DefaultSourceFolderUrlFilterTests {
private static final String SOURCE_ROOT = "/Users/me/code/some-root/";
@@ -55,22 +55,22 @@ public class DefaultSourceFolderUrlFilterTests {
private DefaultSourceFolderUrlFilter filter = new DefaultSourceFolderUrlFilter();
@Test
public void mavenSourceFolder() throws Exception {
void mavenSourceFolder() throws Exception {
doTest("my-module/target/classes/");
}
@Test
public void gradleEclipseSourceFolder() throws Exception {
void gradleEclipseSourceFolder() throws Exception {
doTest("my-module/bin/");
}
@Test
public void unusualSourceFolder() throws Exception {
void unusualSourceFolder() throws Exception {
doTest("my-module/something/quite/quite/mad/");
}
@Test
public void skippedProjects() throws Exception {
void skippedProjects() throws Exception {
String sourceFolder = "/Users/me/code/spring-boot-samples/" + "spring-boot-sample-devtools";
URL jarUrl = new URL("jar:file:/Users/me/tmp/" + "spring-boot-sample-devtools-1.3.0.BUILD-SNAPSHOT.jar!/");
assertThat(this.filter.isMatch(sourceFolder, jarUrl)).isTrue();

View File

@@ -16,7 +16,7 @@
package org.springframework.boot.devtools.restart.server;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
@@ -30,16 +30,16 @@ import static org.mockito.Mockito.verify;
*
* @author Phillip Webb
*/
public class HttpRestartServerHandlerTests {
class HttpRestartServerHandlerTests {
@Test
public void serverMustNotBeNull() {
void serverMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new HttpRestartServerHandler(null))
.withMessageContaining("Server must not be null");
}
@Test
public void handleDelegatesToServer() throws Exception {
void handleDelegatesToServer() throws Exception {
HttpRestartServer server = mock(HttpRestartServer.class);
HttpRestartServerHandler handler = new HttpRestartServerHandler(server);
ServerHttpRequest request = mock(ServerHttpRequest.class);

View File

@@ -20,8 +20,8 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
@@ -45,7 +45,7 @@ import static org.mockito.Mockito.verifyZeroInteractions;
*
* @author Phillip Webb
*/
public class HttpRestartServerTests {
class HttpRestartServerTests {
@Mock
private RestartServer delegate;
@@ -55,26 +55,26 @@ public class HttpRestartServerTests {
@Captor
private ArgumentCaptor<ClassLoaderFiles> filesCaptor;
@Before
@BeforeEach
public void setup() {
MockitoAnnotations.initMocks(this);
this.server = new HttpRestartServer(this.delegate);
}
@Test
public void sourceFolderUrlFilterMustNotBeNull() {
void sourceFolderUrlFilterMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new HttpRestartServer((SourceFolderUrlFilter) null))
.withMessageContaining("SourceFolderUrlFilter must not be null");
}
@Test
public void restartServerMustNotBeNull() {
void restartServerMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new HttpRestartServer((RestartServer) null))
.withMessageContaining("RestartServer must not be null");
}
@Test
public void sendClassLoaderFiles() throws Exception {
void sendClassLoaderFiles() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
ClassLoaderFiles files = new ClassLoaderFiles();
@@ -88,7 +88,7 @@ public class HttpRestartServerTests {
}
@Test
public void sendNoContent() throws Exception {
void sendNoContent() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
this.server.handle(new ServletServerHttpRequest(request), new ServletServerHttpResponse(response));
@@ -98,7 +98,7 @@ public class HttpRestartServerTests {
}
@Test
public void sendBadData() throws Exception {
void sendBadData() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setContent(new byte[] { 0, 0, 0 });

View File

@@ -24,9 +24,8 @@ import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile;
import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile.Kind;
@@ -41,19 +40,16 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
*
* @author Phillip Webb
*/
public class RestartServerTests {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
class RestartServerTests {
@Test
public void sourceFolderUrlFilterMustNotBeNull() {
void sourceFolderUrlFilterMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new RestartServer((SourceFolderUrlFilter) null))
.withMessageContaining("SourceFolderUrlFilter must not be null");
}
@Test
public void updateAndRestart() throws Exception {
void updateAndRestart() throws Exception {
URL url1 = new URL("file:/proj/module-a.jar!/");
URL url2 = new URL("file:/proj/module-b.jar!/");
URL url3 = new URL("file:/proj/module-c.jar!/");
@@ -74,9 +70,8 @@ public class RestartServerTests {
}
@Test
public void updateSetsJarLastModified() throws Exception {
void updateSetsJarLastModified(@TempDir File folder) throws Exception {
long startTime = System.currentTimeMillis();
File folder = this.temp.newFolder();
File jarFile = new File(folder, "module-a.jar");
new FileOutputStream(jarFile).close();
jarFile.setLastModified(0);
@@ -92,11 +87,10 @@ public class RestartServerTests {
}
@Test
public void updateReplacesLocalFilesWhenPossible() throws Exception {
void updateReplacesLocalFilesWhenPossible(@TempDir File folder) throws Exception {
// This is critical for Cloud Foundry support where the application is
// run exploded and resources can be found from the servlet root (outside of the
// classloader)
File folder = this.temp.newFolder();
File classFile = new File(folder, "ClassA.class");
FileCopyUtils.copy("abc".getBytes(), classFile);
URL url = folder.toURI().toURL();

View File

@@ -20,9 +20,8 @@ import java.io.File;
import java.io.IOException;
import java.net.URL;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import static org.assertj.core.api.Assertions.assertThat;
@@ -31,15 +30,12 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Phillip Webb
*/
public class DevToolsSettingsTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
class DevToolsSettingsTests {
private static final String ROOT = DevToolsSettingsTests.class.getPackage().getName().replace('.', '/') + "/";
@Test
public void includePatterns() throws Exception {
void includePatterns() throws Exception {
DevToolsSettings settings = DevToolsSettings.load(ROOT + "spring-devtools-include.properties");
assertThat(settings.isRestartInclude(new URL("file://test/a"))).isTrue();
assertThat(settings.isRestartInclude(new URL("file://test/b"))).isTrue();
@@ -47,7 +43,7 @@ public class DevToolsSettingsTests {
}
@Test
public void excludePatterns() throws Exception {
void excludePatterns() throws Exception {
DevToolsSettings settings = DevToolsSettings.load(ROOT + "spring-devtools-exclude.properties");
assertThat(settings.isRestartExclude(new URL("file://test/a"))).isTrue();
assertThat(settings.isRestartExclude(new URL("file://test/b"))).isTrue();
@@ -55,17 +51,16 @@ public class DevToolsSettingsTests {
}
@Test
public void defaultIncludePatterns() throws Exception {
void defaultIncludePatterns(@TempDir File tempDir) throws Exception {
DevToolsSettings settings = DevToolsSettings.get();
assertThat(settings.isRestartExclude(makeUrl("spring-boot"))).isTrue();
assertThat(settings.isRestartExclude(makeUrl("spring-boot-autoconfigure"))).isTrue();
assertThat(settings.isRestartExclude(makeUrl("spring-boot-actuator"))).isTrue();
assertThat(settings.isRestartExclude(makeUrl("spring-boot-starter"))).isTrue();
assertThat(settings.isRestartExclude(makeUrl("spring-boot-starter-some-thing"))).isTrue();
assertThat(settings.isRestartExclude(makeUrl(tempDir, "spring-boot"))).isTrue();
assertThat(settings.isRestartExclude(makeUrl(tempDir, "spring-boot-autoconfigure"))).isTrue();
assertThat(settings.isRestartExclude(makeUrl(tempDir, "spring-boot-actuator"))).isTrue();
assertThat(settings.isRestartExclude(makeUrl(tempDir, "spring-boot-starter"))).isTrue();
assertThat(settings.isRestartExclude(makeUrl(tempDir, "spring-boot-starter-some-thing"))).isTrue();
}
private URL makeUrl(String name) throws IOException {
File file = this.temporaryFolder.newFolder();
private URL makeUrl(File file, String name) throws IOException {
file = new File(file, name);
file = new File(file, "target");
file = new File(file, "classes");

View File

@@ -25,20 +25,20 @@ import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;
import java.util.concurrent.Executor;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.devtools.test.MockClientHttpRequestFactory;
import org.springframework.boot.devtools.tunnel.client.HttpTunnelConnection.TunnelChannel;
import org.springframework.boot.test.system.OutputCaptureRule;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.http.HttpStatus;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.Matchers.containsString;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -50,10 +50,8 @@ import static org.mockito.Mockito.verify;
* @author Rob Winch
* @author Andy Wilkinson
*/
public class HttpTunnelConnectionTests {
@Rule
public OutputCaptureRule outputCapture = new OutputCaptureRule();
@ExtendWith(OutputCaptureExtension.class)
class HttpTunnelConnectionTests {
private String url;
@@ -66,7 +64,7 @@ public class HttpTunnelConnectionTests {
private MockClientHttpRequestFactory requestFactory = new MockClientHttpRequestFactory();
@Before
@BeforeEach
public void setup() {
MockitoAnnotations.initMocks(this);
this.url = "http://localhost:12345";
@@ -75,32 +73,32 @@ public class HttpTunnelConnectionTests {
}
@Test
public void urlMustNotBeNull() {
void urlMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelConnection(null, this.requestFactory))
.withMessageContaining("URL must not be empty");
}
@Test
public void urlMustNotBeEmpty() {
void urlMustNotBeEmpty() {
assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelConnection("", this.requestFactory))
.withMessageContaining("URL must not be empty");
}
@Test
public void urlMustNotBeMalformed() {
void urlMustNotBeMalformed() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new HttpTunnelConnection("htttttp:///ttest", this.requestFactory))
.withMessageContaining("Malformed URL 'htttttp:///ttest'");
}
@Test
public void requestFactoryMustNotBeNull() {
void requestFactoryMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelConnection(this.url, null))
.withMessageContaining("RequestFactory must not be null");
}
@Test
public void closeTunnelChangesIsOpen() throws Exception {
void closeTunnelChangesIsOpen() throws Exception {
this.requestFactory.willRespondAfterDelay(1000, HttpStatus.GONE);
WritableByteChannel channel = openTunnel(false);
assertThat(channel.isOpen()).isTrue();
@@ -109,7 +107,7 @@ public class HttpTunnelConnectionTests {
}
@Test
public void closeTunnelCallsCloseableOnce() throws Exception {
void closeTunnelCallsCloseableOnce() throws Exception {
this.requestFactory.willRespondAfterDelay(1000, HttpStatus.GONE);
WritableByteChannel channel = openTunnel(false);
verify(this.closeable, never()).close();
@@ -119,7 +117,7 @@ public class HttpTunnelConnectionTests {
}
@Test
public void typicalTraffic() throws Exception {
void typicalTraffic() throws Exception {
this.requestFactory.willRespond("hi", "=2", "=3");
TunnelChannel channel = openTunnel(true);
write(channel, "hello");
@@ -129,7 +127,7 @@ public class HttpTunnelConnectionTests {
}
@Test
public void trafficWithLongPollTimeouts() throws Exception {
void trafficWithLongPollTimeouts() throws Exception {
for (int i = 0; i < 10; i++) {
this.requestFactory.willRespond(HttpStatus.NO_CONTENT);
}
@@ -141,11 +139,11 @@ public class HttpTunnelConnectionTests {
}
@Test
public void connectFailureLogsWarning() throws Exception {
void connectFailureLogsWarning(CapturedOutput capturedOutput) throws Exception {
this.requestFactory.willRespond(new ConnectException());
TunnelChannel tunnel = openTunnel(true);
assertThat(tunnel.isOpen()).isFalse();
this.outputCapture.expect(containsString("Failed to connect to remote application at http://localhost:12345"));
assertThat(capturedOutput).contains("Failed to connect to remote application at http://localhost:12345");
}
private void write(TunnelChannel channel, String string) throws IOException {

View File

@@ -25,7 +25,7 @@ import java.nio.channels.Channels;
import java.nio.channels.SocketChannel;
import java.nio.channels.WritableByteChannel;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
@@ -38,24 +38,24 @@ import static org.mockito.Mockito.verify;
*
* @author Phillip Webb
*/
public class TunnelClientTests {
class TunnelClientTests {
private MockTunnelConnection tunnelConnection = new MockTunnelConnection();
@Test
public void listenPortMustNotBeNegative() {
void listenPortMustNotBeNegative() {
assertThatIllegalArgumentException().isThrownBy(() -> new TunnelClient(-5, this.tunnelConnection))
.withMessageContaining("ListenPort must be greater than or equal to 0");
}
@Test
public void tunnelConnectionMustNotBeNull() {
void tunnelConnectionMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new TunnelClient(1, null))
.withMessageContaining("TunnelConnection must not be null");
}
@Test
public void typicalTraffic() throws Exception {
void typicalTraffic() throws Exception {
TunnelClient client = new TunnelClient(0, this.tunnelConnection);
int port = client.start();
SocketChannel channel = SocketChannel.open(new InetSocketAddress(port));
@@ -68,7 +68,7 @@ public class TunnelClientTests {
}
@Test
public void socketChannelClosedTriggersTunnelClose() throws Exception {
void socketChannelClosedTriggersTunnelClose() throws Exception {
TunnelClient client = new TunnelClient(0, this.tunnelConnection);
int port = client.start();
SocketChannel channel = SocketChannel.open(new InetSocketAddress(port));
@@ -81,7 +81,7 @@ public class TunnelClientTests {
}
@Test
public void stopTriggersTunnelClose() throws Exception {
void stopTriggersTunnelClose() throws Exception {
TunnelClient client = new TunnelClient(0, this.tunnelConnection);
int port = client.start();
SocketChannel channel = SocketChannel.open(new InetSocketAddress(port));
@@ -93,7 +93,7 @@ public class TunnelClientTests {
}
@Test
public void addListener() throws Exception {
void addListener() throws Exception {
TunnelClient client = new TunnelClient(0, this.tunnelConnection);
TunnelClientListener listener = mock(TunnelClientListener.class);
client.addListener(listener);

View File

@@ -21,7 +21,7 @@ import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
@@ -32,16 +32,16 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
*
* @author Phillip Webb
*/
public class HttpTunnelPayloadForwarderTests {
class HttpTunnelPayloadForwarderTests {
@Test
public void targetChannelMustNotBeNull() {
void targetChannelMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelPayloadForwarder(null))
.withMessageContaining("TargetChannel must not be null");
}
@Test
public void forwardInSequence() throws Exception {
void forwardInSequence() throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
WritableByteChannel channel = Channels.newChannel(out);
HttpTunnelPayloadForwarder forwarder = new HttpTunnelPayloadForwarder(channel);
@@ -52,7 +52,7 @@ public class HttpTunnelPayloadForwarderTests {
}
@Test
public void forwardOutOfSequence() throws Exception {
void forwardOutOfSequence() throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
WritableByteChannel channel = Channels.newChannel(out);
HttpTunnelPayloadForwarder forwarder = new HttpTunnelPayloadForwarder(channel);
@@ -63,7 +63,7 @@ public class HttpTunnelPayloadForwarderTests {
}
@Test
public void overflow() throws Exception {
void overflow() throws Exception {
WritableByteChannel channel = Channels.newChannel(new ByteArrayOutputStream());
HttpTunnelPayloadForwarder forwarder = new HttpTunnelPayloadForwarder(channel);
assertThatIllegalStateException().isThrownBy(() -> {

View File

@@ -25,7 +25,7 @@ import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
@@ -46,35 +46,35 @@ import static org.mockito.Mockito.mock;
*
* @author Phillip Webb
*/
public class HttpTunnelPayloadTests {
class HttpTunnelPayloadTests {
@Test
public void sequenceMustBePositive() {
void sequenceMustBePositive() {
assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelPayload(0, ByteBuffer.allocate(1)))
.withMessageContaining("Sequence must be positive");
}
@Test
public void dataMustNotBeNull() {
void dataMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelPayload(1, null))
.withMessageContaining("Data must not be null");
}
@Test
public void getSequence() {
void getSequence() {
HttpTunnelPayload payload = new HttpTunnelPayload(1, ByteBuffer.allocate(1));
assertThat(payload.getSequence()).isEqualTo(1L);
}
@Test
public void getData() throws Exception {
void getData() throws Exception {
ByteBuffer data = ByteBuffer.wrap("hello".getBytes());
HttpTunnelPayload payload = new HttpTunnelPayload(1, data);
assertThat(getData(payload)).isEqualTo(data.array());
}
@Test
public void assignTo() throws Exception {
void assignTo() throws Exception {
ByteBuffer data = ByteBuffer.wrap("hello".getBytes());
HttpTunnelPayload payload = new HttpTunnelPayload(2, data);
MockHttpServletResponse servletResponse = new MockHttpServletResponse();
@@ -85,7 +85,7 @@ public class HttpTunnelPayloadTests {
}
@Test
public void getNoData() throws Exception {
void getNoData() throws Exception {
MockHttpServletRequest servletRequest = new MockHttpServletRequest();
HttpInputMessage request = new ServletServerHttpRequest(servletRequest);
HttpTunnelPayload payload = HttpTunnelPayload.get(request);
@@ -93,7 +93,7 @@ public class HttpTunnelPayloadTests {
}
@Test
public void getWithMissingHeader() throws Exception {
void getWithMissingHeader() throws Exception {
MockHttpServletRequest servletRequest = new MockHttpServletRequest();
servletRequest.setContent("hello".getBytes());
HttpInputMessage request = new ServletServerHttpRequest(servletRequest);
@@ -102,7 +102,7 @@ public class HttpTunnelPayloadTests {
}
@Test
public void getWithData() throws Exception {
void getWithData() throws Exception {
MockHttpServletRequest servletRequest = new MockHttpServletRequest();
servletRequest.setContent("hello".getBytes());
servletRequest.addHeader("x-seq", 123);
@@ -113,7 +113,7 @@ public class HttpTunnelPayloadTests {
}
@Test
public void getPayloadData() throws Exception {
void getPayloadData() throws Exception {
ReadableByteChannel channel = Channels.newChannel(new ByteArrayInputStream("hello".getBytes()));
ByteBuffer payloadData = HttpTunnelPayload.getPayloadData(channel);
ByteArrayOutputStream out = new ByteArrayOutputStream();
@@ -125,7 +125,7 @@ public class HttpTunnelPayloadTests {
}
@Test
public void getPayloadDataWithTimeout() throws Exception {
void getPayloadDataWithTimeout() throws Exception {
ReadableByteChannel channel = mock(ReadableByteChannel.class);
given(channel.read(any(ByteBuffer.class))).willThrow(new SocketTimeoutException());
ByteBuffer payload = HttpTunnelPayload.getPayloadData(channel);

View File

@@ -16,7 +16,7 @@
package org.springframework.boot.devtools.tunnel.server;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
@@ -30,16 +30,16 @@ import static org.mockito.Mockito.verify;
*
* @author Phillip Webb
*/
public class HttpTunnelServerHandlerTests {
class HttpTunnelServerHandlerTests {
@Test
public void serverMustNotBeNull() {
void serverMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelServerHandler(null))
.withMessageContaining("Server must not be null");
}
@Test
public void handleDelegatesToServer() throws Exception {
void handleDelegatesToServer() throws Exception {
HttpTunnelServer server = mock(HttpTunnelServer.class);
HttpTunnelServerHandler handler = new HttpTunnelServerHandler(server);
ServerHttpRequest request = mock(ServerHttpRequest.class);

View File

@@ -27,8 +27,8 @@ import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
@@ -57,7 +57,7 @@ import static org.mockito.Mockito.verify;
*
* @author Phillip Webb
*/
public class HttpTunnelServerTests {
class HttpTunnelServerTests {
private static final int DEFAULT_LONG_POLL_TIMEOUT = 10000;
@@ -80,7 +80,7 @@ public class HttpTunnelServerTests {
private MockServerChannel serverChannel;
@Before
@BeforeEach
public void setup() throws Exception {
MockitoAnnotations.initMocks(this);
this.server = new HttpTunnelServer(this.serverConnection);
@@ -98,33 +98,33 @@ public class HttpTunnelServerTests {
}
@Test
public void serverConnectionIsRequired() {
void serverConnectionIsRequired() {
assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelServer(null))
.withMessageContaining("ServerConnection must not be null");
}
@Test
public void serverConnectedOnFirstRequest() throws Exception {
void serverConnectedOnFirstRequest() throws Exception {
verify(this.serverConnection, never()).open(anyInt());
this.server.handle(this.request, this.response);
verify(this.serverConnection, times(1)).open(DEFAULT_LONG_POLL_TIMEOUT);
}
@Test
public void longPollTimeout() throws Exception {
void longPollTimeout() throws Exception {
this.server.setLongPollTimeout(800);
this.server.handle(this.request, this.response);
verify(this.serverConnection, times(1)).open(800);
}
@Test
public void longPollTimeoutMustBePositiveValue() {
void longPollTimeoutMustBePositiveValue() {
assertThatIllegalArgumentException().isThrownBy(() -> this.server.setLongPollTimeout(0))
.withMessageContaining("LongPollTimeout must be a positive value");
}
@Test
public void initialRequestIsSentToServer() throws Exception {
void initialRequestIsSentToServer() throws Exception {
this.servletRequest.addHeader(SEQ_HEADER, "1");
this.servletRequest.setContent("hello".getBytes());
this.server.handle(this.request, this.response);
@@ -134,7 +134,7 @@ public class HttpTunnelServerTests {
}
@Test
public void initialRequestIsUsedForFirstServerResponse() throws Exception {
void initialRequestIsUsedForFirstServerResponse() throws Exception {
this.servletRequest.addHeader(SEQ_HEADER, "1");
this.servletRequest.setContent("hello".getBytes());
this.server.handle(this.request, this.response);
@@ -147,7 +147,7 @@ public class HttpTunnelServerTests {
}
@Test
public void initialRequestHasNoPayload() throws Exception {
void initialRequestHasNoPayload() throws Exception {
this.server.handle(this.request, this.response);
this.serverChannel.disconnect();
this.server.getServerThread().join();
@@ -155,7 +155,7 @@ public class HttpTunnelServerTests {
}
@Test
public void typicalRequestResponseTraffic() throws Exception {
void typicalRequestResponseTraffic() throws Exception {
MockHttpConnection h1 = new MockHttpConnection();
this.server.handle(h1);
MockHttpConnection h2 = new MockHttpConnection("hello server", 1);
@@ -176,7 +176,7 @@ public class HttpTunnelServerTests {
}
@Test
public void clientIsAwareOfServerClose() throws Exception {
void clientIsAwareOfServerClose() throws Exception {
MockHttpConnection h1 = new MockHttpConnection("1", 1);
this.server.handle(h1);
this.serverChannel.disconnect();
@@ -185,7 +185,7 @@ public class HttpTunnelServerTests {
}
@Test
public void clientCanCloseServer() throws Exception {
void clientCanCloseServer() throws Exception {
MockHttpConnection h1 = new MockHttpConnection();
this.server.handle(h1);
MockHttpConnection h2 = new MockHttpConnection("DISCONNECT", 1);
@@ -197,7 +197,7 @@ public class HttpTunnelServerTests {
}
@Test
public void neverMoreThanTwoHttpConnections() throws Exception {
void neverMoreThanTwoHttpConnections() throws Exception {
MockHttpConnection h1 = new MockHttpConnection();
this.server.handle(h1);
MockHttpConnection h2 = new MockHttpConnection("1", 2);
@@ -211,7 +211,7 @@ public class HttpTunnelServerTests {
}
@Test
public void requestReceivedOutOfOrder() throws Exception {
void requestReceivedOutOfOrder() throws Exception {
MockHttpConnection h1 = new MockHttpConnection();
MockHttpConnection h2 = new MockHttpConnection("1+2", 1);
MockHttpConnection h3 = new MockHttpConnection("+3", 2);
@@ -224,7 +224,7 @@ public class HttpTunnelServerTests {
}
@Test
public void httpConnectionsAreClosedAfterLongPollTimeout() throws Exception {
void httpConnectionsAreClosedAfterLongPollTimeout() throws Exception {
this.server.setDisconnectTimeout(1000);
this.server.setLongPollTimeout(100);
MockHttpConnection h1 = new MockHttpConnection();
@@ -239,7 +239,7 @@ public class HttpTunnelServerTests {
}
@Test
public void disconnectTimeout() throws Exception {
void disconnectTimeout() throws Exception {
this.server.setDisconnectTimeout(100);
this.server.setLongPollTimeout(100);
MockHttpConnection h1 = new MockHttpConnection();
@@ -250,13 +250,13 @@ public class HttpTunnelServerTests {
}
@Test
public void disconnectTimeoutMustBePositive() {
void disconnectTimeoutMustBePositive() {
assertThatIllegalArgumentException().isThrownBy(() -> this.server.setDisconnectTimeout(0))
.withMessageContaining("DisconnectTimeout must be a positive value");
}
@Test
public void httpConnectionRespondWithPayload() throws Exception {
void httpConnectionRespondWithPayload() throws Exception {
HttpConnection connection = new HttpConnection(this.request, this.response);
connection.waitForResponse();
connection.respond(new HttpTunnelPayload(1, ByteBuffer.wrap("hello".getBytes())));
@@ -266,7 +266,7 @@ public class HttpTunnelServerTests {
}
@Test
public void httpConnectionRespondWithStatus() throws Exception {
void httpConnectionRespondWithStatus() throws Exception {
HttpConnection connection = new HttpConnection(this.request, this.response);
connection.waitForResponse();
connection.respond(HttpStatus.I_AM_A_TEAPOT);
@@ -275,7 +275,7 @@ public class HttpTunnelServerTests {
}
@Test
public void httpConnectionAsync() throws Exception {
void httpConnectionAsync() throws Exception {
ServerHttpAsyncRequestControl async = mock(ServerHttpAsyncRequestControl.class);
ServerHttpRequest request = mock(ServerHttpRequest.class);
given(request.getAsyncRequestControl(this.response)).willReturn(async);
@@ -287,7 +287,7 @@ public class HttpTunnelServerTests {
}
@Test
public void httpConnectionNonAsync() throws Exception {
void httpConnectionNonAsync() throws Exception {
testHttpConnectionNonAsync(0);
testHttpConnectionNonAsync(100);
}
@@ -310,7 +310,7 @@ public class HttpTunnelServerTests {
}
@Test
public void httpConnectionRunning() throws Exception {
void httpConnectionRunning() throws Exception {
HttpConnection connection = new HttpConnection(this.request, this.response);
assertThat(connection.isOlderThan(100)).isFalse();
Thread.sleep(200);

View File

@@ -24,8 +24,8 @@ import java.nio.channels.ByteChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
@@ -35,7 +35,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
*
* @author Phillip Webb
*/
public class SocketTargetServerConnectionTests {
class SocketTargetServerConnectionTests {
private static final int DEFAULT_TIMEOUT = 1000;
@@ -43,14 +43,14 @@ public class SocketTargetServerConnectionTests {
private SocketTargetServerConnection connection;
@Before
@BeforeEach
public void setup() throws IOException {
this.server = new MockServer();
this.connection = new SocketTargetServerConnection(() -> this.server.getPort());
}
@Test
public void readData() throws Exception {
void readData() throws Exception {
this.server.willSend("hello".getBytes());
this.server.start();
ByteChannel channel = this.connection.open(DEFAULT_TIMEOUT);
@@ -60,7 +60,7 @@ public class SocketTargetServerConnectionTests {
}
@Test
public void writeData() throws Exception {
void writeData() throws Exception {
this.server.expect("hello".getBytes());
this.server.start();
ByteChannel channel = this.connection.open(DEFAULT_TIMEOUT);
@@ -70,7 +70,7 @@ public class SocketTargetServerConnectionTests {
}
@Test
public void timeout() throws Exception {
void timeout() throws Exception {
this.server.delay(1000);
this.server.start();
ByteChannel channel = this.connection.open(10);

View File

@@ -16,7 +16,7 @@
package org.springframework.boot.devtools.tunnel.server;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
@@ -26,16 +26,16 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
*
* @author Phillip Webb
*/
public class StaticPortProviderTests {
class StaticPortProviderTests {
@Test
public void portMustBePositive() {
void portMustBePositive() {
assertThatIllegalArgumentException().isThrownBy(() -> new StaticPortProvider(0))
.withMessageContaining("Port must be positive");
}
@Test
public void getPort() {
void getPort() {
StaticPortProvider provider = new StaticPortProvider(123);
assertThat(provider.getPort()).isEqualTo(123);
}