diff --git a/spring-batch-core/pom.xml b/spring-batch-core/pom.xml index 0507ec7409..84d52400be 100644 --- a/spring-batch-core/pom.xml +++ b/spring-batch-core/pom.xml @@ -87,6 +87,12 @@ + + org.testcontainers + junit-jupiter + ${testcontainers.version} + test + org.hsqldb hsqldb @@ -196,21 +202,9 @@ test - junit - junit - ${junit.version} - test - - - org.hamcrest - hamcrest-core - - - - - org.junit.vintage - junit-vintage-engine - ${junit-vintage-engine.version} + org.junit.jupiter + junit-jupiter-engine + ${junit-jupiter.version} test @@ -233,7 +227,7 @@ org.mockito - mockito-core + mockito-junit-jupiter ${mockito.version} test diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/AbstractExceptionTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/AbstractExceptionTests.java index 945bf3cac4..dd4a738acc 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/AbstractExceptionTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/AbstractExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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,14 +16,14 @@ package org.springframework.batch.core; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; public abstract class AbstractExceptionTests extends AbstractExceptionWithCauseTests { @Test - public void testExceptionString() throws Exception { + void testExceptionString() throws Exception { Exception exception = getException("foo"); assertEquals("foo", exception.getMessage()); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/AbstractExceptionWithCauseTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/AbstractExceptionWithCauseTests.java index 8b8e50cea7..def90d30b8 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/AbstractExceptionWithCauseTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/AbstractExceptionWithCauseTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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,14 +16,14 @@ package org.springframework.batch.core; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; public abstract class AbstractExceptionWithCauseTests { @Test - public void testExceptionStringThrowable() throws Exception { + void testExceptionStringThrowable() throws Exception { Exception exception = getException("foo", new IllegalStateException()); assertEquals("foo", exception.getMessage().substring(0, 3)); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/BatchStatusTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/BatchStatusTests.java index bbcfa9da0d..2d37584395 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/BatchStatusTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/BatchStatusTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,36 +15,35 @@ */ package org.springframework.batch.core; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author Dave Syer * @author Mahmoud Ben Hassine * */ -public class BatchStatusTests { +class BatchStatusTests { /** * Test method for {@link org.springframework.batch.core.BatchStatus#toString()}. */ @Test - public void testToString() { + void testToString() { assertEquals("ABANDONED", BatchStatus.ABANDONED.toString()); } @Test - public void testMaxStatus() { + void testMaxStatus() { assertEquals(BatchStatus.FAILED, BatchStatus.max(BatchStatus.FAILED, BatchStatus.COMPLETED)); assertEquals(BatchStatus.FAILED, BatchStatus.max(BatchStatus.COMPLETED, BatchStatus.FAILED)); assertEquals(BatchStatus.FAILED, BatchStatus.max(BatchStatus.FAILED, BatchStatus.FAILED)); @@ -53,13 +52,13 @@ public void testMaxStatus() { } @Test - public void testUpgradeStatusFinished() { + void testUpgradeStatusFinished() { assertEquals(BatchStatus.FAILED, BatchStatus.FAILED.upgradeTo(BatchStatus.COMPLETED)); assertEquals(BatchStatus.FAILED, BatchStatus.COMPLETED.upgradeTo(BatchStatus.FAILED)); } @Test - public void testUpgradeStatusUnfinished() { + void testUpgradeStatusUnfinished() { assertEquals(BatchStatus.COMPLETED, BatchStatus.STARTING.upgradeTo(BatchStatus.COMPLETED)); assertEquals(BatchStatus.COMPLETED, BatchStatus.COMPLETED.upgradeTo(BatchStatus.STARTING)); assertEquals(BatchStatus.STARTED, BatchStatus.STARTING.upgradeTo(BatchStatus.STARTED)); @@ -67,7 +66,7 @@ public void testUpgradeStatusUnfinished() { } @Test - public void testIsRunning() { + void testIsRunning() { assertFalse(BatchStatus.FAILED.isRunning()); assertFalse(BatchStatus.COMPLETED.isRunning()); assertTrue(BatchStatus.STARTED.isRunning()); @@ -75,7 +74,7 @@ public void testIsRunning() { } @Test - public void testIsUnsuccessful() { + void testIsUnsuccessful() { assertTrue(BatchStatus.FAILED.isUnsuccessful()); assertFalse(BatchStatus.COMPLETED.isUnsuccessful()); assertFalse(BatchStatus.STARTED.isUnsuccessful()); @@ -83,28 +82,22 @@ public void testIsUnsuccessful() { } @Test - public void testGetStatus() { + void testGetStatus() { assertEquals(BatchStatus.FAILED, BatchStatus.valueOf(BatchStatus.FAILED.toString())); } @Test - public void testGetStatusWrongCode() { - try { - BatchStatus.valueOf("foo"); - fail(); - } - catch (IllegalArgumentException ex) { - // expected - } + void testGetStatusWrongCode() { + assertThrows(IllegalArgumentException.class, () -> BatchStatus.valueOf("foo")); } - @Test(expected = NullPointerException.class) - public void testGetStatusNullCode() { - assertNull(BatchStatus.valueOf(null)); + @Test + void testGetStatusNullCode() { + assertThrows(NullPointerException.class, () -> BatchStatus.valueOf(null)); } @Test - public void testSerialization() throws Exception { + void testSerialization() throws Exception { ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bout); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/DefaultJobKeyGeneratorTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/DefaultJobKeyGeneratorTests.java index 18958d7be8..53ee6cbde5 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/DefaultJobKeyGeneratorTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/DefaultJobKeyGeneratorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2021 the original author or authors. + * Copyright 2013-2022 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. @@ -15,27 +15,22 @@ */ package org.springframework.batch.core; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class DefaultJobKeyGeneratorTests { +class DefaultJobKeyGeneratorTests { - private JobKeyGenerator jobKeyGenerator; + private final JobKeyGenerator jobKeyGenerator = new DefaultJobKeyGenerator(); - @Before - public void setUp() throws Exception { - jobKeyGenerator = new DefaultJobKeyGenerator(); - } - - @Test(expected = IllegalArgumentException.class) - public void testNullParameters() { - jobKeyGenerator.generateKey(null); + @Test + void testNullParameters() { + assertThrows(IllegalArgumentException.class, () -> jobKeyGenerator.generateKey(null)); } @Test - public void testMixedParameters() { + void testMixedParameters() { JobParameters jobParameters1 = new JobParametersBuilder().addString("foo", "bar").addString("bar", "foo") .toJobParameters(); JobParameters jobParameters2 = new JobParametersBuilder().addString("foo", "bar", true) @@ -46,7 +41,7 @@ public void testMixedParameters() { } @Test - public void testCreateJobKey() { + void testCreateJobKey() { JobParameters jobParameters = new JobParametersBuilder().addString("foo", "bar").addString("bar", "foo") .toJobParameters(); String key = jobKeyGenerator.generateKey(jobParameters); @@ -54,7 +49,7 @@ public void testCreateJobKey() { } @Test - public void testCreateJobKeyOrdering() { + void testCreateJobKeyOrdering() { JobParameters jobParameters1 = new JobParametersBuilder().addString("foo", "bar").addString("bar", "foo") .toJobParameters(); String key1 = jobKeyGenerator.generateKey(jobParameters1); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/EntityTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/EntityTests.java index 9b80fa1c1f..a8ad2e47ff 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/EntityTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/EntityTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,121 +15,94 @@ */ package org.springframework.batch.core; -import junit.framework.TestCase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Dave Syer * */ -public class EntityTests extends TestCase { +class EntityTests { - Entity entity = new Entity(11L); + private Entity entity = new Entity(11L); - /** - * Test method for {@link org.springframework.batch.core.Entity#hashCode()}. - */ - public void testHashCode() { + @Test + void testHashCode() { assertEquals(entity.hashCode(), new Entity(entity.getId()).hashCode()); } - /** - * Test method for {@link org.springframework.batch.core.Entity#hashCode()}. - */ - public void testHashCodeNullId() { + @Test + void testHashCodeNullId() { int withoutNull = entity.hashCode(); entity.setId(null); int withNull = entity.hashCode(); assertTrue(withoutNull != withNull); } - /** - * Test method for {@link org.springframework.batch.core.Entity#getVersion()}. - */ - public void testGetVersion() { - assertEquals(null, entity.getVersion()); + @Test + void testGetVersion() { + assertNull(entity.getVersion()); } - /** - * Test method for {@link org.springframework.batch.core.Entity#getVersion()}. - */ - public void testIncrementVersion() { + @Test + void testIncrementVersion() { entity.incrementVersion(); assertEquals(Integer.valueOf(0), entity.getVersion()); } - /** - * Test method for {@link org.springframework.batch.core.Entity#getVersion()}. - */ - public void testIncrementVersionTwice() { + @Test + void testIncrementVersionTwice() { entity.incrementVersion(); entity.incrementVersion(); assertEquals(Integer.valueOf(1), entity.getVersion()); } - /** - * @throws Exception - */ - public void testToString() throws Exception { + @Test + void testToString() { Entity job = new Entity(); - assertTrue(job.toString().indexOf("id=null") >= 0); + assertTrue(job.toString().contains("id=null")); } - /** - * Test method for - * {@link org.springframework.batch.core.Entity#equals(java.lang.Object)}. - */ - public void testEqualsSelf() { + @Test + void testEqualsSelf() { assertEquals(entity, entity); } - /** - * Test method for - * {@link org.springframework.batch.core.Entity#equals(java.lang.Object)}. - */ - public void testEqualsSelfWithNullId() { + @Test + void testEqualsSelfWithNullId() { entity = new Entity(null); assertEquals(entity, entity); } - /** - * Test method for - * {@link org.springframework.batch.core.Entity#equals(java.lang.Object)}. - */ - public void testEqualsEntityWithNullId() { + @Test + void testEqualsEntityWithNullId() { entity = new Entity(null); assertNotSame(entity, new Entity(null)); } - /** - * Test method for - * {@link org.springframework.batch.core.Entity#equals(java.lang.Object)}. - */ - public void testEqualsEntity() { + @Test + void testEqualsEntity() { assertEquals(entity, new Entity(entity.getId())); } - /** - * Test method for - * {@link org.springframework.batch.core.Entity#equals(java.lang.Object)}. - */ - public void testEqualsEntityWrongId() { - assertFalse(entity.equals(new Entity())); + @Test + void testEqualsEntityWrongId() { + assertNotEquals(entity, new Entity()); } - /** - * Test method for - * {@link org.springframework.batch.core.Entity#equals(java.lang.Object)}. - */ - public void testEqualsObject() { - assertFalse(entity.equals(new Object())); + @Test + void testEqualsObject() { + assertNotEquals(entity, new Object()); } - /** - * Test method for - * {@link org.springframework.batch.core.Entity#equals(java.lang.Object)}. - */ - public void testEqualsNull() { - assertFalse(entity.equals(null)); + @Test + void testEqualsNull() { + assertNotEquals(null, entity); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/ExitStatusTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/ExitStatusTests.java index 43e73e6f17..ce32d79e05 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/ExitStatusTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/ExitStatusTests.java @@ -15,11 +15,11 @@ */ package org.springframework.batch.core; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.util.SerializationUtils; /** @@ -27,206 +27,159 @@ * @author Mahmoud Ben Hassine * */ -public class ExitStatusTests { +class ExitStatusTests { @Test - public void testExitStatusNullDescription() { + void testExitStatusNullDescription() { ExitStatus status = new ExitStatus("10", null); assertEquals("", status.getExitDescription()); } @Test - public void testExitStatusBooleanInt() { + void testExitStatusBooleanInt() { ExitStatus status = new ExitStatus("10"); assertEquals("10", status.getExitCode()); } @Test - public void testExitStatusConstantsContinuable() { + void testExitStatusConstantsContinuable() { ExitStatus status = ExitStatus.EXECUTING; assertEquals("EXECUTING", status.getExitCode()); } @Test - public void testExitStatusConstantsFinished() { + void testExitStatusConstantsFinished() { ExitStatus status = ExitStatus.COMPLETED; assertEquals("COMPLETED", status.getExitCode()); } - /** - * Test equality of exit statuses. - * @throws Exception - */ @Test - public void testEqualsWithSameProperties() throws Exception { + void testEqualsWithSameProperties() { assertEquals(ExitStatus.EXECUTING, new ExitStatus("EXECUTING")); } @Test - public void testEqualsSelf() { + void testEqualsSelf() { ExitStatus status = new ExitStatus("test"); assertEquals(status, status); } @Test - public void testEquals() { + void testEquals() { assertEquals(new ExitStatus("test"), new ExitStatus("test")); } - /** - * Test equality of exit statuses. - * @throws Exception - */ @Test - public void testEqualsWithNull() throws Exception { + void testEqualsWithNull() { assertFalse(ExitStatus.EXECUTING.equals(null)); } - /** - * Test equality of exit statuses. - * @throws Exception - */ @Test - public void testHashcode() throws Exception { + void testHashcode() { assertEquals(ExitStatus.EXECUTING.toString().hashCode(), ExitStatus.EXECUTING.hashCode()); } - /** - * Test method for - * {@link org.springframework.batch.core.ExitStatus#and(org.springframework.batch.core.ExitStatus)} - * . - */ @Test - public void testAndExitStatusStillExecutable() { + void testAndExitStatusStillExecutable() { assertEquals(ExitStatus.EXECUTING.getExitCode(), ExitStatus.EXECUTING.and(ExitStatus.EXECUTING).getExitCode()); } - /** - * Test method for - * {@link org.springframework.batch.core.ExitStatus#and(org.springframework.batch.core.ExitStatus)} - * . - */ @Test - public void testAndExitStatusWhenFinishedAddedToContinuable() { + void testAndExitStatusWhenFinishedAddedToContinuable() { assertEquals(ExitStatus.COMPLETED.getExitCode(), ExitStatus.EXECUTING.and(ExitStatus.COMPLETED).getExitCode()); } - /** - * Test method for - * {@link org.springframework.batch.core.ExitStatus#and(org.springframework.batch.core.ExitStatus)} - * . - */ @Test - public void testAndExitStatusWhenContinuableAddedToFinished() { + void testAndExitStatusWhenContinuableAddedToFinished() { assertEquals(ExitStatus.COMPLETED.getExitCode(), ExitStatus.COMPLETED.and(ExitStatus.EXECUTING).getExitCode()); } - /** - * Test method for - * {@link org.springframework.batch.core.ExitStatus#and(org.springframework.batch.core.ExitStatus)} - * . - */ @Test - public void testAndExitStatusWhenCustomContinuableAddedToContinuable() { + void testAndExitStatusWhenCustomContinuableAddedToContinuable() { assertEquals("CUSTOM", ExitStatus.EXECUTING.and(ExitStatus.EXECUTING.replaceExitCode("CUSTOM")).getExitCode()); } - /** - * Test method for - * {@link org.springframework.batch.core.ExitStatus#and(org.springframework.batch.core.ExitStatus)} - * . - */ @Test - public void testAndExitStatusWhenCustomCompletedAddedToCompleted() { + void testAndExitStatusWhenCustomCompletedAddedToCompleted() { assertEquals("COMPLETED_CUSTOM", ExitStatus.COMPLETED.and(ExitStatus.EXECUTING.replaceExitCode("COMPLETED_CUSTOM")).getExitCode()); } - /** - * Test method for - * {@link org.springframework.batch.core.ExitStatus#and(org.springframework.batch.core.ExitStatus)} - * . - */ @Test - public void testAndExitStatusFailedPlusFinished() { + void testAndExitStatusFailedPlusFinished() { assertEquals("FAILED", ExitStatus.COMPLETED.and(ExitStatus.FAILED).getExitCode()); assertEquals("FAILED", ExitStatus.FAILED.and(ExitStatus.COMPLETED).getExitCode()); } - /** - * Test method for - * {@link org.springframework.batch.core.ExitStatus#and(org.springframework.batch.core.ExitStatus)} - * . - */ @Test - public void testAndExitStatusWhenCustomContinuableAddedToFinished() { + void testAndExitStatusWhenCustomContinuableAddedToFinished() { assertEquals("CUSTOM", ExitStatus.COMPLETED.and(ExitStatus.EXECUTING.replaceExitCode("CUSTOM")).getExitCode()); } @Test - public void testAddExitCode() throws Exception { + void testAddExitCode() { ExitStatus status = ExitStatus.EXECUTING.replaceExitCode("FOO"); assertTrue(ExitStatus.EXECUTING != status); assertEquals("FOO", status.getExitCode()); } @Test - public void testAddExitCodeToExistingStatus() throws Exception { + void testAddExitCodeToExistingStatus() { ExitStatus status = ExitStatus.EXECUTING.replaceExitCode("FOO").replaceExitCode("BAR"); assertTrue(ExitStatus.EXECUTING != status); assertEquals("BAR", status.getExitCode()); } @Test - public void testAddExitCodeToSameStatus() throws Exception { + void testAddExitCodeToSameStatus() { ExitStatus status = ExitStatus.EXECUTING.replaceExitCode(ExitStatus.EXECUTING.getExitCode()); assertTrue(ExitStatus.EXECUTING != status); assertEquals(ExitStatus.EXECUTING.getExitCode(), status.getExitCode()); } @Test - public void testAddExitDescription() throws Exception { + void testAddExitDescription() { ExitStatus status = ExitStatus.EXECUTING.addExitDescription("Foo"); assertTrue(ExitStatus.EXECUTING != status); assertEquals("Foo", status.getExitDescription()); } @Test - public void testAddExitDescriptionWIthStacktrace() throws Exception { + void testAddExitDescriptionWIthStacktrace() { ExitStatus status = ExitStatus.EXECUTING.addExitDescription(new RuntimeException("Foo")); assertTrue(ExitStatus.EXECUTING != status); String description = status.getExitDescription(); - assertTrue("Wrong description: " + description, description.contains("Foo")); - assertTrue("Wrong description: " + description, description.contains("RuntimeException")); + assertTrue(description.contains("Foo"), "Wrong description: " + description); + assertTrue(description.contains("RuntimeException"), "Wrong description: " + description); } @Test - public void testAddExitDescriptionToSameStatus() throws Exception { + void testAddExitDescriptionToSameStatus() { ExitStatus status = ExitStatus.EXECUTING.addExitDescription("Foo").addExitDescription("Foo"); assertTrue(ExitStatus.EXECUTING != status); assertEquals("Foo", status.getExitDescription()); } @Test - public void testAddEmptyExitDescription() throws Exception { + void testAddEmptyExitDescription() { ExitStatus status = ExitStatus.EXECUTING.addExitDescription("Foo").addExitDescription((String) null); assertEquals("Foo", status.getExitDescription()); } @Test - public void testAddExitCodeWithDescription() throws Exception { + void testAddExitCodeWithDescription() { ExitStatus status = new ExitStatus("BAR", "Bar").replaceExitCode("FOO"); assertEquals("FOO", status.getExitCode()); assertEquals("Bar", status.getExitDescription()); } @Test - public void testUnknownIsRunning() throws Exception { + void testUnknownIsRunning() { assertTrue(ExitStatus.UNKNOWN.isRunning()); } @Test - public void testSerializable() { + void testSerializable() { ExitStatus status = ExitStatus.EXECUTING.replaceExitCode("FOO"); ExitStatus clone = SerializationUtils.clone(status); assertEquals(status.getExitCode(), clone.getExitCode()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/JobExecutionTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/JobExecutionTests.java index 3a1694d9b0..084f97e507 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/JobExecutionTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/JobExecutionTests.java @@ -15,17 +15,17 @@ */ package org.springframework.batch.core; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; import java.util.Date; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.util.SerializationUtils; /** @@ -34,12 +34,12 @@ * @author Mahmoud Ben Hassine * */ -public class JobExecutionTests { +class JobExecutionTests { private JobExecution execution = new JobExecution(new JobInstance(11L, "foo"), 12L, new JobParameters()); @Test - public void testJobExecution() { + void testJobExecution() { assertNull(new JobExecution(new JobInstance(null, "foo"), null).getId()); } @@ -47,7 +47,7 @@ public void testJobExecution() { * Test method for {@link org.springframework.batch.core.JobExecution#getEndTime()}. */ @Test - public void testGetEndTime() { + void testGetEndTime() { assertNull(execution.getEndTime()); execution.setEndTime(new Date(100L)); assertEquals(100L, execution.getEndTime().getTime()); @@ -57,7 +57,7 @@ public void testGetEndTime() { * Test method for {@link org.springframework.batch.core.JobExecution#getEndTime()}. */ @Test - public void testIsRunning() { + void testIsRunning() { execution.setStartTime(new Date()); assertTrue(execution.isRunning()); execution.setEndTime(new Date(100L)); @@ -68,7 +68,7 @@ public void testIsRunning() { * Test method for {@link org.springframework.batch.core.JobExecution#getStartTime()}. */ @Test - public void testGetStartTime() { + void testGetStartTime() { execution.setStartTime(new Date(0L)); assertEquals(0L, execution.getStartTime().getTime()); } @@ -77,7 +77,7 @@ public void testGetStartTime() { * Test method for {@link org.springframework.batch.core.JobExecution#getStatus()}. */ @Test - public void testGetStatus() { + void testGetStatus() { assertEquals(BatchStatus.STARTING, execution.getStatus()); execution.setStatus(BatchStatus.COMPLETED); assertEquals(BatchStatus.COMPLETED, execution.getStatus()); @@ -87,7 +87,7 @@ public void testGetStatus() { * Test method for {@link org.springframework.batch.core.JobExecution#getStatus()}. */ @Test - public void testUpgradeStatus() { + void testUpgradeStatus() { assertEquals(BatchStatus.STARTING, execution.getStatus()); execution.upgradeStatus(BatchStatus.COMPLETED); assertEquals(BatchStatus.COMPLETED, execution.getStatus()); @@ -97,7 +97,7 @@ public void testUpgradeStatus() { * Test method for {@link org.springframework.batch.core.JobExecution#getStatus()}. */ @Test - public void testDowngradeStatus() { + void testDowngradeStatus() { execution.setStatus(BatchStatus.FAILED); execution.upgradeStatus(BatchStatus.COMPLETED); assertEquals(BatchStatus.FAILED, execution.getStatus()); @@ -107,7 +107,7 @@ public void testDowngradeStatus() { * Test method for {@link org.springframework.batch.core.JobExecution#getJobId()}. */ @Test - public void testGetJobId() { + void testGetJobId() { assertEquals(11, execution.getJobId().longValue()); execution = new JobExecution(new JobInstance(23L, "testJob"), null, new JobParameters()); assertEquals(23, execution.getJobId().longValue()); @@ -117,7 +117,7 @@ public void testGetJobId() { * Test method for {@link org.springframework.batch.core.JobExecution#getJobId()}. */ @Test - public void testGetJobIdForNullJob() { + void testGetJobIdForNullJob() { execution = new JobExecution((JobInstance) null, (JobParameters) null); assertEquals(null, execution.getJobId()); } @@ -126,7 +126,7 @@ public void testGetJobIdForNullJob() { * Test method for {@link org.springframework.batch.core.JobExecution#getJobId()}. */ @Test - public void testGetJob() { + void testGetJob() { assertNotNull(execution.getJobInstance()); } @@ -135,26 +135,26 @@ public void testGetJob() { * {@link org.springframework.batch.core.JobExecution#getExitStatus()}. */ @Test - public void testGetExitCode() { + void testGetExitCode() { assertEquals(ExitStatus.UNKNOWN, execution.getExitStatus()); execution.setExitStatus(new ExitStatus("23")); assertEquals("23", execution.getExitStatus().getExitCode()); } @Test - public void testContextContainsInfo() throws Exception { + void testContextContainsInfo() throws Exception { assertEquals("foo", execution.getJobInstance().getJobName()); } @Test - public void testAddAndRemoveStepExecution() throws Exception { + void testAddAndRemoveStepExecution() throws Exception { assertEquals(0, execution.getStepExecutions().size()); execution.createStepExecution("step"); assertEquals(1, execution.getStepExecutions().size()); } @Test - public void testStepExecutionsWithSameName() throws Exception { + void testStepExecutionsWithSameName() throws Exception { assertEquals(0, execution.getStepExecutions().size()); execution.createStepExecution("step"); assertEquals(1, execution.getStepExecutions().size()); @@ -163,14 +163,14 @@ public void testStepExecutionsWithSameName() throws Exception { } @Test - public void testSetStepExecutions() throws Exception { + void testSetStepExecutions() throws Exception { assertEquals(0, execution.getStepExecutions().size()); execution.addStepExecutions(Arrays.asList(new StepExecution("step", execution))); assertEquals(1, execution.getStepExecutions().size()); } @Test - public void testSetStepExecutionsWithIds() throws Exception { + void testSetStepExecutionsWithIds() throws Exception { assertEquals(0, execution.getStepExecutions().size()); new StepExecution("step", execution, 1L); assertEquals(1, execution.getStepExecutions().size()); @@ -179,20 +179,20 @@ public void testSetStepExecutionsWithIds() throws Exception { } @Test - public void testToString() throws Exception { - assertTrue("JobExecution string does not contain id", execution.toString().indexOf("id=") >= 0); - assertTrue("JobExecution string does not contain name: " + execution, execution.toString().indexOf("foo") >= 0); + void testToString() throws Exception { + assertTrue(execution.toString().contains("id="), "JobExecution string does not contain id"); + assertTrue(execution.toString().contains("foo"), "JobExecution string does not contain name: " + execution); } @Test - public void testToStringWithNullJob() throws Exception { + void testToStringWithNullJob() { execution = new JobExecution(new JobInstance(null, "foo"), null); - assertTrue("JobExecution string does not contain id", execution.toString().indexOf("id=") >= 0); - assertTrue("JobExecution string does not contain job: " + execution, execution.toString().indexOf("job=") >= 0); + assertTrue(execution.toString().contains("id="), "JobExecution string does not contain id"); + assertTrue(execution.toString().contains("job="), "JobExecution string does not contain job: " + execution); } @Test - public void testSerialization() { + void testSerialization() { JobExecution clone = SerializationUtils.clone(execution); assertEquals(execution, clone); assertNotNull(clone.createStepExecution("foo")); @@ -200,7 +200,7 @@ public void testSerialization() { } @Test - public void testFailureExceptions() { + void testFailureExceptions() { RuntimeException exception = new RuntimeException(); assertEquals(0, execution.getFailureExceptions().size()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/JobInstanceTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/JobInstanceTests.java index 4cd433243c..a53f4dfcc5 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/JobInstanceTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/JobInstanceTests.java @@ -15,55 +15,46 @@ */ package org.springframework.batch.core; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.util.SerializationUtils; /** * @author dsyer * - */ -public class JobInstanceTests { + **/ +class JobInstanceTests { private JobInstance instance = new JobInstance(11L, "job"); - /** - * Test method for {@link org.springframework.batch.core.JobInstance#getJobName()}. - */ @Test - public void testGetName() { + void testGetName() { instance = new JobInstance(1L, "foo"); assertEquals("foo", instance.getJobName()); } @Test - public void testGetJob() { + void testGetJob() { assertEquals("job", instance.getJobName()); } @Test - public void testCreateWithNulls() { - try { - new JobInstance(null, null); - fail("job instance can't exist without job specified"); - } - catch (IllegalArgumentException e) { - // expected - } + void testCreateWithNulls() { + assertThrows(IllegalArgumentException.class, () -> new JobInstance(null, null)); instance = new JobInstance(null, "testJob"); assertEquals("testJob", instance.getJobName()); } @Test - public void testSerialization() { + void testSerialization() { instance = new JobInstance(1L, "jobName"); assertEquals(instance, SerializationUtils.clone(instance)); } @Test - public void testGetInstanceId() { + void testGetInstanceId() { assertEquals(11, instance.getInstanceId()); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/JobParameterTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/JobParameterTests.java index c9433f1919..06fe4335a6 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/JobParameterTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/JobParameterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2021 the original author or authors. + * Copyright 2008-2022 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. @@ -15,72 +15,72 @@ */ package org.springframework.batch.core; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.Date; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author Lucas Ward * */ -public class JobParameterTests { +class JobParameterTests { JobParameter jobParameter; @Test - public void testStringParameter() { + void testStringParameter() { jobParameter = new JobParameter("test", true); assertEquals("test", jobParameter.getValue()); } - @Test(expected = IllegalArgumentException.class) - public void testNullStringParameter() { - jobParameter = new JobParameter((String) null, true); + @Test + void testNullStringParameter() { + assertThrows(IllegalArgumentException.class, () -> new JobParameter((String) null, true)); } @Test - public void testLongParameter() { + void testLongParameter() { jobParameter = new JobParameter(1L, true); assertEquals(1L, jobParameter.getValue()); } @Test - public void testDoubleParameter() { + void testDoubleParameter() { jobParameter = new JobParameter(1.1, true); assertEquals(1.1, jobParameter.getValue()); } @Test - public void testDateParameter() { + void testDateParameter() { Date epoch = new Date(0L); jobParameter = new JobParameter(epoch, true); assertEquals(new Date(0L), jobParameter.getValue()); } - @Test(expected = IllegalArgumentException.class) - public void testNullDateParameter() { - jobParameter = new JobParameter((Date) null, true); + @Test + void testNullDateParameter() { + assertThrows(IllegalArgumentException.class, () -> new JobParameter((Date) null, true)); } @Test - public void testDateParameterToString() { + void testDateParameterToString() { Date epoch = new Date(0L); jobParameter = new JobParameter(epoch, true); assertEquals("0", jobParameter.toString()); } @Test - public void testEquals() { + void testEquals() { jobParameter = new JobParameter("test", true); JobParameter testParameter = new JobParameter("test", true); - assertTrue(jobParameter.equals(testParameter)); + assertEquals(jobParameter, testParameter); } @Test - public void testHashcode() { + void testHashcode() { jobParameter = new JobParameter("test", true); JobParameter testParameter = new JobParameter("test", true); assertEquals(testParameter.hashCode(), jobParameter.hashCode()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/JobParametersBuilderTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/JobParametersBuilderTests.java index 6ab52e257d..95934142fd 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/JobParametersBuilderTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/JobParametersBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2021 the original author or authors. + * Copyright 2008-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,16 +22,16 @@ import java.util.Map; import java.util.Properties; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.explore.JobExplorer; import org.springframework.batch.core.job.SimpleJob; import org.springframework.batch.core.launch.support.RunIdIncrementer; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -43,7 +43,7 @@ * @author Mahmoud Ben Hassine * */ -public class JobParametersBuilderTests { +class JobParametersBuilderTests { private JobParametersBuilder parametersBuilder; @@ -55,10 +55,10 @@ public class JobParametersBuilderTests { private List jobExecutionList; - private Date date = new Date(System.currentTimeMillis()); + private final Date date = new Date(System.currentTimeMillis()); - @Before - public void initialize() { + @BeforeEach + void initialize() { this.job = new SimpleJob("simpleJob"); this.jobExplorer = mock(JobExplorer.class); this.jobInstanceList = new ArrayList<>(1); @@ -67,7 +67,7 @@ public void initialize() { } @Test - public void testAddingExistingJobParameters() { + void testAddingExistingJobParameters() { JobParameters params1 = new JobParametersBuilder().addString("foo", "bar").addString("bar", "baz") .toJobParameters(); @@ -82,7 +82,7 @@ public void testAddingExistingJobParameters() { } @Test - public void testNonIdentifyingParameters() { + void testNonIdentifyingParameters() { this.parametersBuilder.addDate("SCHEDULE_DATE", date, false); this.parametersBuilder.addLong("LONG", 1L, false); this.parametersBuilder.addString("STRING", "string value", false); @@ -100,7 +100,7 @@ public void testNonIdentifyingParameters() { } @Test - public void testToJobRuntimeParameters() { + void testToJobRuntimeParameters() { this.parametersBuilder.addDate("SCHEDULE_DATE", date); this.parametersBuilder.addLong("LONG", 1L); this.parametersBuilder.addString("STRING", "string value"); @@ -113,7 +113,7 @@ public void testToJobRuntimeParameters() { } @Test - public void testCopy() { + void testCopy() { this.parametersBuilder.addString("STRING", "string value"); this.parametersBuilder = new JobParametersBuilder(this.parametersBuilder.toJobParameters()); Iterator parameters = this.parametersBuilder.toJobParameters().getParameters().keySet().iterator(); @@ -121,7 +121,7 @@ public void testCopy() { } @Test - public void testOrderedTypes() { + void testOrderedTypes() { this.parametersBuilder.addDate("SCHEDULE_DATE", date); this.parametersBuilder.addLong("LONG", 1L); this.parametersBuilder.addString("STRING", "string value"); @@ -132,7 +132,7 @@ public void testOrderedTypes() { } @Test - public void testOrderedStrings() { + void testOrderedStrings() { this.parametersBuilder.addString("foo", "value foo"); this.parametersBuilder.addString("bar", "value bar"); this.parametersBuilder.addString("spam", "value spam"); @@ -143,7 +143,7 @@ public void testOrderedStrings() { } @Test - public void testAddJobParameter() { + void testAddJobParameter() { JobParameter jobParameter = new JobParameter("bar"); this.parametersBuilder.addParameter("foo", jobParameter); Map parameters = this.parametersBuilder.toJobParameters().getParameters(); @@ -152,7 +152,7 @@ public void testAddJobParameter() { } @Test - public void testProperties() { + void testProperties() { Properties props = new Properties(); props.setProperty("SCHEDULE_DATE", "A DATE"); props.setProperty("LONG", "1"); @@ -168,7 +168,7 @@ public void testProperties() { } @Test - public void testGetNextJobParametersFirstRun() { + void testGetNextJobParametersFirstRun() { job.setJobParametersIncrementer(new RunIdIncrementer()); initializeForNextJobParameters(); this.parametersBuilder.getNextJobParameters(this.job); @@ -176,7 +176,7 @@ public void testGetNextJobParametersFirstRun() { } @Test - public void testGetNextJobParametersNoIncrementer() { + void testGetNextJobParametersNoIncrementer() { initializeForNextJobParameters(); final Exception expectedException = assertThrows(IllegalArgumentException.class, () -> this.parametersBuilder.getNextJobParameters(this.job)); @@ -184,7 +184,7 @@ public void testGetNextJobParametersNoIncrementer() { } @Test - public void testGetNextJobParameters() { + void testGetNextJobParameters() { this.job.setJobParametersIncrementer(new RunIdIncrementer()); this.jobInstanceList.add(new JobInstance(1L, "simpleJobInstance")); this.jobExecutionList.add(getJobExecution(this.jobInstanceList.get(0), null)); @@ -196,7 +196,7 @@ public void testGetNextJobParameters() { } @Test - public void testGetNextJobParametersRestartable() { + void testGetNextJobParametersRestartable() { this.job.setRestartable(true); this.job.setJobParametersIncrementer(new RunIdIncrementer()); this.jobInstanceList.add(new JobInstance(1L, "simpleJobInstance")); @@ -210,7 +210,7 @@ public void testGetNextJobParametersRestartable() { } @Test - public void testGetNextJobParametersNoPreviousExecution() { + void testGetNextJobParametersNoPreviousExecution() { this.job.setJobParametersIncrementer(new RunIdIncrementer()); this.jobInstanceList.add(new JobInstance(1L, "simpleJobInstance")); when(this.jobExplorer.getJobInstances("simpleJob", 0, 1)).thenReturn(this.jobInstanceList); @@ -220,10 +220,10 @@ public void testGetNextJobParametersNoPreviousExecution() { baseJobParametersVerify(this.parametersBuilder.toJobParameters(), 4); } - @Test(expected = IllegalStateException.class) - public void testMissingJobExplorer() { + @Test + void testMissingJobExplorer() { this.parametersBuilder = new JobParametersBuilder(); - this.parametersBuilder.getNextJobParameters(this.job); + assertThrows(IllegalStateException.class, () -> this.parametersBuilder.getNextJobParameters(this.job)); } private void initializeForNextJobParameters() { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/JobParametersTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/JobParametersTests.java index bfb61d8b5c..2203754c70 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/JobParametersTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/JobParametersTests.java @@ -15,18 +15,18 @@ */ package org.springframework.batch.core; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.util.SerializationUtils; /** @@ -37,7 +37,7 @@ * @author Taeik Lim * */ -public class JobParametersTests { +class JobParametersTests { JobParameters parameters; @@ -45,8 +45,8 @@ public class JobParametersTests { Date date2 = new Date(7809089900L); - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { parameters = getNewParameters(); } @@ -66,77 +66,77 @@ private JobParameters getNewParameters() { } @Test - public void testGetString() { + void testGetString() { assertEquals("value1", parameters.getString("string.key1")); assertEquals("value2", parameters.getString("string.key2")); } @Test - public void testGetLong() { + void testGetLong() { assertEquals(1L, parameters.getLong("long.key1").longValue()); assertEquals(2L, parameters.getLong("long.key2").longValue()); } @Test - public void testGetDouble() { + void testGetDouble() { assertEquals(Double.valueOf(1.1d), parameters.getDouble("double.key1")); assertEquals(Double.valueOf(2.2d), parameters.getDouble("double.key2")); } @Test - public void testGetDate() { + void testGetDate() { assertEquals(date1, parameters.getDate("date.key1")); assertEquals(date2, parameters.getDate("date.key2")); } @Test - public void testGetMissingLong() { + void testGetMissingLong() { assertNull(parameters.getLong("missing.long1")); } @Test - public void testGetMissingDouble() { + void testGetMissingDouble() { assertNull(parameters.getDouble("missing.double1")); } @Test - public void testIsEmptyWhenEmpty() throws Exception { + void testIsEmptyWhenEmpty() throws Exception { assertTrue(new JobParameters().isEmpty()); } @Test - public void testIsEmptyWhenNotEmpty() throws Exception { + void testIsEmptyWhenNotEmpty() throws Exception { assertFalse(parameters.isEmpty()); } @Test - public void testEquals() { + void testEquals() { JobParameters testParameters = getNewParameters(); assertTrue(testParameters.equals(parameters)); } @Test - public void testEqualsSelf() { + void testEqualsSelf() { assertTrue(parameters.equals(parameters)); } @Test - public void testEqualsDifferent() { + void testEqualsDifferent() { assertFalse(parameters.equals(new JobParameters())); } @Test - public void testEqualsWrongType() { + void testEqualsWrongType() { assertFalse(parameters.equals("foo")); } @Test - public void testEqualsNull() { + void testEqualsNull() { assertFalse(parameters.equals(null)); } @Test - public void testToStringOrder() { + void testToStringOrder() { Map props = parameters.getParameters(); StringBuilder stringBuilder = new StringBuilder(); @@ -169,40 +169,40 @@ public void testToStringOrder() { } @Test - public void testHashCodeEqualWhenEmpty() throws Exception { + void testHashCodeEqualWhenEmpty() throws Exception { int code = new JobParameters().hashCode(); assertEquals(code, new JobParameters().hashCode()); } @Test - public void testHashCodeEqualWhenNotEmpty() throws Exception { + void testHashCodeEqualWhenNotEmpty() throws Exception { int code = getNewParameters().hashCode(); assertEquals(code, parameters.hashCode()); } @Test - public void testSerialization() { + void testSerialization() { JobParameters params = getNewParameters(); assertEquals(params, SerializationUtils.clone(params)); } @Test - public void testLongReturnsNullWhenKeyDoesntExit() { + void testLongReturnsNullWhenKeyDoesntExit() { assertNull(new JobParameters().getLong("keythatdoesntexist")); } @Test - public void testStringReturnsNullWhenKeyDoesntExit() { + void testStringReturnsNullWhenKeyDoesntExit() { assertNull(new JobParameters().getString("keythatdoesntexist")); } @Test - public void testDoubleReturnsNullWhenKeyDoesntExit() { + void testDoubleReturnsNullWhenKeyDoesntExit() { assertNull(new JobParameters().getDouble("keythatdoesntexist")); } @Test - public void testDateReturnsNullWhenKeyDoesntExit() { + void testDateReturnsNullWhenKeyDoesntExit() { assertNull(new JobParameters().getDate("keythatdoesntexist")); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/SpringBeanJobTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/SpringBeanJobTests.java index 1df1f85ffa..c47fd72c0c 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/SpringBeanJobTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/SpringBeanJobTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2014 the original author or authors. + * Copyright 2006-2022 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,10 +16,10 @@ package org.springframework.batch.core; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.job.JobSupport; import org.springframework.beans.factory.config.ConstructorArgumentValues; import org.springframework.beans.factory.support.ChildBeanDefinition; @@ -27,10 +27,10 @@ import org.springframework.context.support.GenericApplicationContext; import org.springframework.context.support.StaticApplicationContext; -public class SpringBeanJobTests { +class SpringBeanJobTests { @Test - public void testBeanName() throws Exception { + void testBeanName() { StaticApplicationContext context = new StaticApplicationContext(); JobSupport configuration = new JobSupport(); context.getAutowireCapableBeanFactory().initializeBean(configuration, "bean"); @@ -43,7 +43,7 @@ public void testBeanName() throws Exception { } @Test - public void testBeanNameWithBeanDefinition() throws Exception { + void testBeanNameWithBeanDefinition() { GenericApplicationContext context = new GenericApplicationContext(); ConstructorArgumentValues args = new ConstructorArgumentValues(); args.addGenericArgumentValue("foo"); @@ -59,7 +59,7 @@ public void testBeanNameWithBeanDefinition() throws Exception { } @Test - public void testBeanNameWithParentBeanDefinition() throws Exception { + void testBeanNameWithParentBeanDefinition() { GenericApplicationContext context = new GenericApplicationContext(); ConstructorArgumentValues args = new ConstructorArgumentValues(); args.addGenericArgumentValue("bar"); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/StepContributionTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/StepContributionTests.java index d5deab2a3b..cc39b005da 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/StepContributionTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/StepContributionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,37 +15,35 @@ */ package org.springframework.batch.core; -import junit.framework.TestCase; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; /** * @author Dave Syer * */ -public class StepContributionTests extends TestCase { +class StepContributionTests { - private StepExecution execution = new StepExecution("step", null); + private final StepExecution execution = new StepExecution("step", null); - private StepContribution contribution = new StepContribution(execution); + private final StepContribution contribution = new StepContribution(execution); - /** - * Test method for - * {@link org.springframework.batch.core.StepContribution#incrementFilterCount(int)} . - */ - public void testIncrementFilterCount() { + @Test + void testIncrementFilterCount() { assertEquals(0, contribution.getFilterCount()); contribution.incrementFilterCount(1); assertEquals(1, contribution.getFilterCount()); } @Test - public void testEqualsNull() throws Exception { - assertFalse(contribution.equals(null)); + void testEqualsNull() { + assertNotEquals(null, contribution); } @Test - public void testEqualsAnother() throws Exception { + void testEqualsAnother() { assertEquals(new StepExecution("foo", null).createStepContribution(), contribution); assertEquals(new StepExecution("foo", null).createStepContribution().hashCode(), contribution.hashCode()); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/StepExecutionTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/StepExecutionTests.java index e01d539fa6..69360ddabf 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/StepExecutionTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/StepExecutionTests.java @@ -15,19 +15,20 @@ */ package org.springframework.batch.core; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Date; import java.util.HashSet; 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.springframework.batch.core.step.StepSupport; import org.springframework.batch.item.ExecutionContext; import org.springframework.util.SerializationUtils; @@ -37,26 +38,26 @@ * @author Mahmoud Ben Hassine * */ -public class StepExecutionTests { +class StepExecutionTests { private StepExecution execution = newStepExecution(new StepSupport("stepName"), 23L); - private StepExecution blankExecution = newStepExecution(new StepSupport("blank"), null); + private final StepExecution blankExecution = newStepExecution(new StepSupport("blank"), null); - private ExecutionContext foobarEc = new ExecutionContext(); + private final ExecutionContext foobarEc = new ExecutionContext(); - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { foobarEc.put("foo", "bar"); } @Test - public void testStepExecution() { + void testStepExecution() { assertNull(new StepExecution("step", null).getId()); } @Test - public void testStepExecutionWithNullId() { + void testStepExecutionWithNullId() { assertNull(new StepExecution("stepName", new JobExecution(new JobInstance(null, "foo"), null)).getId()); } @@ -64,7 +65,7 @@ public void testStepExecutionWithNullId() { * Test method for {@link org.springframework.batch.core.JobExecution#getEndTime()}. */ @Test - public void testGetEndTime() { + void testGetEndTime() { assertNull(execution.getEndTime()); execution.setEndTime(new Date(0L)); assertEquals(0L, execution.getEndTime().getTime()); @@ -74,7 +75,7 @@ public void testGetEndTime() { * Test method for {@link StepExecution#getCreateTime()}. */ @Test - public void testGetCreateTime() { + void testGetCreateTime() { assertNotNull(execution.getCreateTime()); execution.setCreateTime(new Date(10L)); assertEquals(10L, execution.getCreateTime().getTime()); @@ -84,7 +85,7 @@ public void testGetCreateTime() { * Test method for {@link org.springframework.batch.core.JobExecution#getStatus()}. */ @Test - public void testGetStatus() { + void testGetStatus() { assertEquals(BatchStatus.STARTING, execution.getStatus()); execution.setStatus(BatchStatus.COMPLETED); assertEquals(BatchStatus.COMPLETED, execution.getStatus()); @@ -94,7 +95,7 @@ public void testGetStatus() { * Test method for {@link org.springframework.batch.core.JobExecution#getJobId()}. */ @Test - public void testGetJobId() { + void testGetJobId() { assertEquals(23, execution.getJobExecutionId().longValue()); } @@ -103,7 +104,7 @@ public void testGetJobId() { * {@link org.springframework.batch.core.JobExecution#getExitStatus()}. */ @Test - public void testGetExitCode() { + void testGetExitCode() { assertEquals(ExitStatus.EXECUTING, execution.getExitStatus()); execution.setExitStatus(ExitStatus.COMPLETED); assertEquals(ExitStatus.COMPLETED, execution.getExitStatus()); @@ -114,24 +115,24 @@ public void testGetExitCode() { * {@link org.springframework.batch.core.StepExecution#getCommitCount()}. */ @Test - public void testGetCommitCount() { + void testGetCommitCount() { execution.setCommitCount(123); assertEquals(123, execution.getCommitCount()); } @Test - public void testGetFilterCount() { + void testGetFilterCount() { execution.setFilterCount(123); assertEquals(123, execution.getFilterCount()); } @Test - public void testGetJobExecution() throws Exception { + void testGetJobExecution() { assertNotNull(execution.getJobExecution()); } @Test - public void testApplyContribution() throws Exception { + void testApplyContribution() { StepContribution contribution = execution.createStepContribution(); contribution.incrementReadSkipCount(); contribution.incrementWriteSkipCount(); @@ -147,35 +148,29 @@ public void testApplyContribution() throws Exception { } @Test - public void testTerminateOnly() throws Exception { + void testTerminateOnly() { assertFalse(execution.isTerminateOnly()); execution.setTerminateOnly(); assertTrue(execution.isTerminateOnly()); } @Test - public void testNullNameIsIllegal() throws Exception { - try { - new StepExecution(null, new JobExecution(new JobInstance(null, "job"), null)); - fail(); - } - catch (IllegalArgumentException e) { - // expected - } + void testNullNameIsIllegal() { + assertThrows(IllegalArgumentException.class, + () -> new StepExecution(null, new JobExecution(new JobInstance(null, "job"), null))); } @Test - public void testToString() throws Exception { - assertTrue("Should contain read count: " + execution.toString(), execution.toString().indexOf("read") >= 0); - assertTrue("Should contain write count: " + execution.toString(), execution.toString().indexOf("write") >= 0); - assertTrue("Should contain filter count: " + execution.toString(), execution.toString().indexOf("filter") >= 0); - assertTrue("Should contain commit count: " + execution.toString(), execution.toString().indexOf("commit") >= 0); - assertTrue("Should contain rollback count: " + execution.toString(), - execution.toString().indexOf("rollback") >= 0); + void testToString() throws Exception { + assertTrue(execution.toString().contains("read"), "Should contain read count: " + execution.toString()); + assertTrue(execution.toString().contains("write"), "Should contain write count: " + execution.toString()); + assertTrue(execution.toString().contains("filter"), "Should contain filter count: " + execution.toString()); + assertTrue(execution.toString().contains("commit"), "Should contain commit count: " + execution.toString()); + assertTrue(execution.toString().contains("rollback"), "Should contain rollback count: " + execution.toString()); } @Test - public void testExecutionContext() throws Exception { + void testExecutionContext() { assertNotNull(execution.getExecutionContext()); ExecutionContext context = new ExecutionContext(); context.putString("foo", "bar"); @@ -184,15 +179,15 @@ public void testExecutionContext() throws Exception { } @Test - public void testEqualsWithSameName() throws Exception { + void testEqualsWithSameName() { Step step = new StepSupport("stepName"); Entity stepExecution1 = newStepExecution(step, 11L, 4L); Entity stepExecution2 = newStepExecution(step, 11L, 5L); - assertFalse(stepExecution1.equals(stepExecution2)); + assertNotEquals(stepExecution1, stepExecution2); } @Test - public void testEqualsWithSameIdentifier() throws Exception { + void testEqualsWithSameIdentifier() { Step step = new StepSupport("stepName"); Entity stepExecution1 = newStepExecution(step, 11L); Entity stepExecution2 = newStepExecution(step, 11L); @@ -200,57 +195,57 @@ public void testEqualsWithSameIdentifier() throws Exception { } @Test - public void testEqualsWithNull() throws Exception { + void testEqualsWithNull() { Entity stepExecution = newStepExecution(new StepSupport("stepName"), 11L); - assertFalse(stepExecution.equals(null)); + assertNotEquals(null, stepExecution); } @Test - public void testEqualsWithNullIdentifiers() throws Exception { + void testEqualsWithNullIdentifiers() { Entity stepExecution = newStepExecution(new StepSupport("stepName"), 11L); - assertFalse(stepExecution.equals(blankExecution)); + assertNotEquals(stepExecution, blankExecution); } @Test - public void testEqualsWithNullJob() throws Exception { + void testEqualsWithNullJob() { Entity stepExecution = newStepExecution(new StepSupport("stepName"), 11L); - assertFalse(stepExecution.equals(blankExecution)); + assertNotEquals(stepExecution, blankExecution); } @Test - public void testEqualsWithSelf() throws Exception { - assertTrue(execution.equals(execution)); + void testEqualsWithSelf() { + assertEquals(execution, execution); } @Test - public void testEqualsWithDifferent() throws Exception { + void testEqualsWithDifferent() { Entity stepExecution = newStepExecution(new StepSupport("foo"), 13L); - assertFalse(execution.equals(stepExecution)); + assertNotEquals(execution, stepExecution); } @Test - public void testEqualsWithNullStepId() throws Exception { + void testEqualsWithNullStepId() { Step step = new StepSupport("name"); execution = newStepExecution(step, 31L); assertEquals("name", execution.getStepName()); StepExecution stepExecution = newStepExecution(step, 31L); assertEquals(stepExecution.getJobExecutionId(), execution.getJobExecutionId()); - assertTrue(execution.equals(stepExecution)); + assertEquals(execution, stepExecution); } @Test - public void testHashCode() throws Exception { - assertTrue("Hash code same as parent", new Entity(execution.getId()).hashCode() != execution.hashCode()); + void testHashCode() { + assertTrue(new Entity(execution.getId()).hashCode() != execution.hashCode(), "Hash code same as parent"); } @Test - public void testHashCodeWithNullIds() throws Exception { - assertTrue("Hash code not same as parent", - new Entity(execution.getId()).hashCode() != blankExecution.hashCode()); + void testHashCodeWithNullIds() { + assertTrue(new Entity(execution.getId()).hashCode() != blankExecution.hashCode(), + "Hash code not same as parent"); } @Test - public void testHashCodeViaHashSet() throws Exception { + void testHashCodeViaHashSet() { Set set = new HashSet<>(); set.add(execution); assertTrue(set.contains(execution)); @@ -259,7 +254,7 @@ public void testHashCodeViaHashSet() throws Exception { } @Test - public void testSerialization() { + void testSerialization() { ExitStatus status = ExitStatus.NOOP; execution.setExitStatus(status); @@ -273,7 +268,7 @@ public void testSerialization() { } @Test - public void testAddException() throws Exception { + void testAddException() { RuntimeException exception = new RuntimeException(); assertEquals(0, execution.getFailureExceptions().size()); @@ -286,7 +281,7 @@ public void testAddException() throws Exception { * Test method for {@link org.springframework.batch.core.JobExecution#getStatus()}. */ @Test - public void testDowngradeStatus() { + void testDowngradeStatus() { execution.setStatus(BatchStatus.FAILED); execution.upgradeStatus(BatchStatus.COMPLETED); assertEquals(BatchStatus.FAILED, execution.getStatus()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/InlineDataSourceDefinitionTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/InlineDataSourceDefinitionTests.java index aa2c47433d..20d526216e 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/InlineDataSourceDefinitionTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/InlineDataSourceDefinitionTests.java @@ -17,43 +17,36 @@ import javax.sql.DataSource; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; -import org.springframework.batch.core.JobParametersInvalidException; import org.springframework.batch.core.launch.JobLauncher; -import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException; -import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException; -import org.springframework.batch.core.repository.JobRestartException; import org.springframework.batch.repeat.RepeatStatus; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; -@RunWith(SpringRunner.class) -@ContextConfiguration -@Ignore // FIXME review this as part of issue 3942 -public class InlineDataSourceDefinitionTests { +import static org.junit.jupiter.api.Assertions.assertEquals; + +@SpringJUnitConfig +@Disabled // FIXME review this as part of issue 3942 +class InlineDataSourceDefinitionTests { @Test - public void testInlineDataSourceDefinition() throws Exception { + void testInlineDataSourceDefinition() throws Exception { ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyJobConfiguration.class); Job job = applicationContext.getBean(Job.class); JobLauncher jobLauncher = applicationContext.getBean(JobLauncher.class); JobExecution jobExecution = jobLauncher.run(job, new JobParameters()); - Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); + assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); } @Configuration diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/JobBuilderConfigurationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/JobBuilderConfigurationTests.java index 29085b42c1..b10ef54d6c 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/JobBuilderConfigurationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/JobBuilderConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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,11 +16,11 @@ package org.springframework.batch.core.configuration.annotation; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import javax.sql.DataSource; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.Job; @@ -52,35 +52,33 @@ public class JobBuilderConfigurationTests { public static boolean fail = false; - private JobExecution execution; - @Test - public void testVanillaBatchConfiguration() throws Exception { + void testVanillaBatchConfiguration() throws Exception { testJob(BatchStatus.COMPLETED, 2, TestConfiguration.class); } @Test - public void testConfigurerAsConfiguration() throws Exception { + void testConfigurerAsConfiguration() throws Exception { testJob(BatchStatus.COMPLETED, 1, TestConfigurer.class); } @Test - public void testConfigurerAsBean() throws Exception { + void testConfigurerAsBean() throws Exception { testJob(BatchStatus.COMPLETED, 1, BeansConfigurer.class); } @Test - public void testTwoConfigurations() throws Exception { + void testTwoConfigurations() throws Exception { testJob("testJob", BatchStatus.COMPLETED, 2, TestConfiguration.class, AnotherConfiguration.class); } @Test - public void testTwoConfigurationsAndConfigurer() throws Exception { + void testTwoConfigurationsAndConfigurer() throws Exception { testJob("testJob", BatchStatus.COMPLETED, 2, TestConfiguration.class, TestConfigurer.class); } @Test - public void testTwoConfigurationsAndBeansConfigurer() throws Exception { + void testTwoConfigurationsAndBeansConfigurer() throws Exception { testJob("testJob", BatchStatus.COMPLETED, 2, TestConfiguration.class, BeansConfigurer.class); } @@ -97,7 +95,7 @@ private void testJob(String jobName, BatchStatus status, int stepExecutionCount, AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(configs); Job job = jobName == null ? context.getBean(Job.class) : context.getBean(jobName, Job.class); JobLauncher jobLauncher = context.getBean(JobLauncher.class); - execution = jobLauncher.run(job, new JobParametersBuilder() + JobExecution execution = jobLauncher.run(job, new JobParametersBuilder() .addLong("run.id", (long) (Math.random() * Long.MAX_VALUE)).toJobParameters()); assertEquals(status, execution.getStatus()); assertEquals(stepExecutionCount, execution.getStepExecutions().size()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/JobLoaderConfigurationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/JobLoaderConfigurationTests.java index 6d961b71c8..e98f46492f 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/JobLoaderConfigurationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/JobLoaderConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2022 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. @@ -15,11 +15,11 @@ */ package org.springframework.batch.core.configuration.annotation; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import jakarta.annotation.PostConstruct; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; @@ -49,17 +49,15 @@ * @author Mahmoud Ben Hassine * */ -public class JobLoaderConfigurationTests { - - private JobExecution execution; +class JobLoaderConfigurationTests { @Test - public void testJobLoader() throws Exception { + void testJobLoader() throws Exception { testJob("test", BatchStatus.COMPLETED, 2, LoaderFactoryConfiguration.class); } @Test - public void testJobLoaderWithArray() throws Exception { + void testJobLoaderWithArray() throws Exception { testJob("test", BatchStatus.COMPLETED, 2, LoaderRegistrarConfiguration.class); } @@ -72,7 +70,7 @@ private void testJob(String jobName, BatchStatus status, int stepExecutionCount, AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(configs); Job job = jobName == null ? context.getBean(Job.class) : context.getBean(JobLocator.class).getJob(jobName); JobLauncher jobLauncher = context.getBean(JobLauncher.class); - execution = jobLauncher.run(job, new JobParametersBuilder() + JobExecution execution = jobLauncher.run(job, new JobParametersBuilder() .addLong("run.id", (long) (Math.random() * Long.MAX_VALUE)).toJobParameters()); assertEquals(status, execution.getStatus()); assertEquals(stepExecutionCount, execution.getStepExecutions().size()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/JobScopeConfigurationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/JobScopeConfigurationTests.java index 8f635ed76b..bbd043477a 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/JobScopeConfigurationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/JobScopeConfigurationTests.java @@ -16,15 +16,15 @@ package org.springframework.batch.core.configuration.annotation; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.concurrent.Callable; -import org.junit.After; -import org.junit.Assert; -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.batch.core.JobExecution; import org.springframework.batch.core.JobInstance; @@ -59,7 +59,7 @@ public class JobScopeConfigurationTests { private JobExecution jobExecution; @Test - public void testXmlJobScopeWithProxyTargetClass() throws Exception { + void testXmlJobScopeWithProxyTargetClass() throws Exception { context = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/annotation/JobScopeConfigurationTestsProxyTargetClass-context.xml"); JobSynchronizationManager.register(jobExecution); @@ -68,7 +68,7 @@ public void testXmlJobScopeWithProxyTargetClass() throws Exception { } @Test - public void testXmlJobScopeWithInterface() throws Exception { + void testXmlJobScopeWithInterface() throws Exception { context = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/annotation/JobScopeConfigurationTestsInterface-context.xml"); JobSynchronizationManager.register(jobExecution); @@ -78,7 +78,7 @@ public void testXmlJobScopeWithInterface() throws Exception { } @Test - public void testXmlJobScopeWithInheritance() throws Exception { + void testXmlJobScopeWithInheritance() throws Exception { context = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/annotation/JobScopeConfigurationTestsInheritance-context.xml"); JobSynchronizationManager.register(jobExecution); @@ -87,14 +87,14 @@ public void testXmlJobScopeWithInheritance() throws Exception { } @Test - public void testJobScopeWithProxyTargetClass() throws Exception { + void testJobScopeWithProxyTargetClass() throws Exception { init(JobScopeConfigurationRequiringProxyTargetClass.class); SimpleHolder value = context.getBean(SimpleHolder.class); assertEquals("JOB", value.call()); } @Test - public void testStepScopeXmlImportUsingNamespace() throws Exception { + void testStepScopeXmlImportUsingNamespace() throws Exception { init(JobScopeConfigurationXmlImportUsingNamespace.class); SimpleHolder value = (SimpleHolder) context.getBean("xmlValue"); @@ -104,17 +104,17 @@ public void testStepScopeXmlImportUsingNamespace() throws Exception { } @Test - public void testJobScopeWithProxyTargetClassInjected() throws Exception { + void testJobScopeWithProxyTargetClassInjected() throws Exception { init(JobScopeConfigurationInjectingProxy.class); SimpleHolder value = context.getBean(Wrapper.class).getValue(); assertEquals("JOB", value.call()); } @Test - public void testIntentionallyBlowUpOnMissingContextWithProxyTargetClass() throws Exception { + void testIntentionallyBlowUpOnMissingContextWithProxyTargetClass() throws Exception { init(JobScopeConfigurationRequiringProxyTargetClass.class); JobSynchronizationManager.release(); - final Exception expectedException = Assert.assertThrows(BeanCreationException.class, () -> { + final Exception expectedException = assertThrows(BeanCreationException.class, () -> { SimpleHolder value = context.getBean(SimpleHolder.class); assertEquals("JOB", value.call()); }); @@ -124,10 +124,10 @@ public void testIntentionallyBlowUpOnMissingContextWithProxyTargetClass() throws } @Test - public void testIntentionallyBlowupWithForcedInterface() throws Exception { + void testIntentionallyBlowupWithForcedInterface() throws Exception { init(JobScopeConfigurationForcingInterfaceProxy.class); JobSynchronizationManager.release(); - final Exception expectedException = Assert.assertThrows(BeanCreationException.class, () -> { + final Exception expectedException = assertThrows(BeanCreationException.class, () -> { SimpleHolder value = context.getBean(SimpleHolder.class); assertEquals("JOB", value.call()); }); @@ -137,7 +137,7 @@ public void testIntentionallyBlowupWithForcedInterface() throws Exception { } @Test - public void testJobScopeWithDefaults() throws Exception { + void testJobScopeWithDefaults() throws Exception { init(JobScopeConfigurationWithDefaults.class); @SuppressWarnings("unchecked") Callable value = context.getBean(Callable.class); @@ -145,10 +145,10 @@ public void testJobScopeWithDefaults() throws Exception { } @Test - public void testIntentionallyBlowUpOnMissingContextWithInterface() throws Exception { + void testIntentionallyBlowUpOnMissingContextWithInterface() throws Exception { init(JobScopeConfigurationWithDefaults.class); JobSynchronizationManager.release(); - final Exception expectedException = Assert.assertThrows(BeanCreationException.class, () -> { + final Exception expectedException = assertThrows(BeanCreationException.class, () -> { @SuppressWarnings("unchecked") Callable value = context.getBean(Callable.class); assertEquals("JOB", value.call()); @@ -169,14 +169,14 @@ public void init(Class... config) throws Exception { JobSynchronizationManager.register(jobExecution); } - @Before - public void setup() { + @BeforeEach + void setup() { JobSynchronizationManager.release(); jobExecution = new JobExecution(new JobInstance(5l, "JOB"), null, null); } - @After - public void close() { + @AfterEach + void close() { JobSynchronizationManager.release(); if (context != null) { context.close(); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/StepScopeConfigurationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/StepScopeConfigurationTests.java index 4eb5cfd2fe..ecce86bede 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/StepScopeConfigurationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/StepScopeConfigurationTests.java @@ -16,10 +16,9 @@ package org.springframework.batch.core.configuration.annotation; -import org.junit.After; -import org.junit.Assert; -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.batch.core.StepContribution; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.scope.context.ChunkContext; @@ -41,8 +40,9 @@ import java.util.concurrent.Callable; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Dave Syer @@ -57,7 +57,7 @@ public class StepScopeConfigurationTests { private StepExecution stepExecution; @Test - public void testXmlStepScopeWithProxyTargetClass() throws Exception { + void testXmlStepScopeWithProxyTargetClass() throws Exception { context = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/annotation/StepScopeConfigurationTestsProxyTargetClass-context.xml"); StepSynchronizationManager.register(stepExecution); @@ -66,7 +66,7 @@ public void testXmlStepScopeWithProxyTargetClass() throws Exception { } @Test - public void testXmlStepScopeWithInterface() throws Exception { + void testXmlStepScopeWithInterface() throws Exception { context = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/annotation/StepScopeConfigurationTestsInterface-context.xml"); StepSynchronizationManager.register(stepExecution); @@ -76,7 +76,7 @@ public void testXmlStepScopeWithInterface() throws Exception { } @Test - public void testXmlStepScopeWithInheritance() throws Exception { + void testXmlStepScopeWithInheritance() throws Exception { context = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/annotation/StepScopeConfigurationTestsInheritance-context.xml"); StepSynchronizationManager.register(stepExecution); @@ -85,14 +85,14 @@ public void testXmlStepScopeWithInheritance() throws Exception { } @Test - public void testStepScopeWithProxyTargetClass() throws Exception { + void testStepScopeWithProxyTargetClass() throws Exception { init(StepScopeConfigurationRequiringProxyTargetClass.class); SimpleHolder value = context.getBean(SimpleHolder.class); assertEquals("STEP", value.call()); } @Test - public void testStepScopeXmlImportUsingNamespace() throws Exception { + void testStepScopeXmlImportUsingNamespace() throws Exception { init(StepScopeConfigurationXmlImportUsingNamespace.class); SimpleHolder value = (SimpleHolder) context.getBean("xmlValue"); @@ -102,18 +102,18 @@ public void testStepScopeXmlImportUsingNamespace() throws Exception { } @Test - public void testStepScopeWithProxyTargetClassInjected() throws Exception { + void testStepScopeWithProxyTargetClassInjected() throws Exception { init(StepScopeConfigurationInjectingProxy.class); SimpleHolder value = context.getBean(Wrapper.class).getValue(); assertEquals("STEP", value.call()); } @Test - public void testIntentionallyBlowUpOnMissingContextWithProxyTargetClass() throws Exception { + void testIntentionallyBlowUpOnMissingContextWithProxyTargetClass() throws Exception { init(StepScopeConfigurationRequiringProxyTargetClass.class); StepSynchronizationManager.release(); - final Exception expectedException = Assert.assertThrows(BeanCreationException.class, () -> { + final Exception expectedException = assertThrows(BeanCreationException.class, () -> { SimpleHolder value = context.getBean(SimpleHolder.class); assertEquals("STEP", value.call()); }); @@ -123,10 +123,10 @@ public void testIntentionallyBlowUpOnMissingContextWithProxyTargetClass() throws } @Test - public void testIntentionallyBlowupWithForcedInterface() throws Exception { + void testIntentionallyBlowupWithForcedInterface() throws Exception { init(StepScopeConfigurationForcingInterfaceProxy.class); StepSynchronizationManager.release(); - final Exception expectedException = Assert.assertThrows(BeanCreationException.class, () -> { + final Exception expectedException = assertThrows(BeanCreationException.class, () -> { SimpleHolder value = context.getBean(SimpleHolder.class); assertEquals("STEP", value.call()); }); @@ -136,7 +136,7 @@ public void testIntentionallyBlowupWithForcedInterface() throws Exception { } @Test - public void testStepScopeWithDefaults() throws Exception { + void testStepScopeWithDefaults() throws Exception { init(StepScopeConfigurationWithDefaults.class); @SuppressWarnings("unchecked") Callable value = context.getBean(Callable.class); @@ -144,11 +144,11 @@ public void testStepScopeWithDefaults() throws Exception { } @Test - public void testIntentionallyBlowUpOnMissingContextWithInterface() throws Exception { + void testIntentionallyBlowUpOnMissingContextWithInterface() throws Exception { init(StepScopeConfigurationWithDefaults.class); StepSynchronizationManager.release(); - final Exception expectedException = Assert.assertThrows(BeanCreationException.class, () -> { + final Exception expectedException = assertThrows(BeanCreationException.class, () -> { @SuppressWarnings("unchecked") Callable value = context.getBean(Callable.class); assertEquals("STEP", value.call()); @@ -169,14 +169,14 @@ public void init(Class... config) throws Exception { StepSynchronizationManager.register(stepExecution); } - @Before - public void setup() { + @BeforeEach + void setup() { StepSynchronizationManager.release(); stepExecution = new StepExecution("STEP", null); } - @After - public void close() { + @AfterEach + void close() { StepSynchronizationManager.release(); if (context != null) { context.close(); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/TransactionManagerConfigurationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/TransactionManagerConfigurationTests.java index 03a8bc1693..9e45dcac00 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/TransactionManagerConfigurationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/TransactionManagerConfigurationTests.java @@ -18,12 +18,11 @@ import javax.sql.DataSource; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.aop.Advisor; -import org.springframework.aop.TargetSource; import org.springframework.aop.framework.Advised; import org.springframework.batch.core.repository.JobRepository; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; @@ -33,8 +32,8 @@ /** * @author Mahmoud Ben Hassine */ -@RunWith(MockitoJUnitRunner.class) -public abstract class TransactionManagerConfigurationTests { +@ExtendWith(MockitoExtension.class) +abstract class TransactionManagerConfigurationTests { @Mock protected static PlatformTransactionManager transactionManager; @@ -53,8 +52,7 @@ PlatformTransactionManager getTransactionManagerSetOnJobRepository(JobRepository // AbstractJobRepositoryFactoryBean.initializeProxy Advisor[] advisors = target.getAdvisors(); for (Advisor advisor : advisors) { - if (advisor.getAdvice() instanceof TransactionInterceptor) { - TransactionInterceptor transactionInterceptor = (TransactionInterceptor) advisor.getAdvice(); + if (advisor.getAdvice() instanceof TransactionInterceptor transactionInterceptor) { return (PlatformTransactionManager) transactionInterceptor.getTransactionManager(); } } @@ -62,10 +60,9 @@ PlatformTransactionManager getTransactionManagerSetOnJobRepository(JobRepository } static DataSource createDataSource() { - return new EmbeddedDatabaseBuilder() + return new EmbeddedDatabaseBuilder().generateUniqueName(true) .addScript("classpath:org/springframework/batch/core/schema-drop-hsqldb.sql") - .addScript("classpath:org/springframework/batch/core/schema-hsqldb.sql").generateUniqueName(true) - .build(); + .addScript("classpath:org/springframework/batch/core/schema-hsqldb.sql").build(); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/TransactionManagerConfigurationWithBatchConfigurerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/TransactionManagerConfigurationWithBatchConfigurerTests.java index 90a667807b..97b459b0b4 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/TransactionManagerConfigurationWithBatchConfigurerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/TransactionManagerConfigurationWithBatchConfigurerTests.java @@ -18,13 +18,9 @@ import javax.sql.DataSource; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import org.springframework.batch.core.Job; import org.springframework.batch.core.repository.JobRepository; -import org.springframework.batch.repeat.RepeatStatus; -import org.springframework.beans.factory.UnsatisfiedDependencyException; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; @@ -33,34 +29,38 @@ import org.springframework.test.util.AopTestUtils; import org.springframework.transaction.PlatformTransactionManager; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * @author Mahmoud Ben Hassine */ -public class TransactionManagerConfigurationWithBatchConfigurerTests extends TransactionManagerConfigurationTests { +class TransactionManagerConfigurationWithBatchConfigurerTests extends TransactionManagerConfigurationTests { @Test - public void testConfigurationWithDataSourceAndNoTransactionManager() throws Exception { + void testConfigurationWithDataSourceAndNoTransactionManager() throws Exception { ApplicationContext applicationContext = new AnnotationConfigApplicationContext( BatchConfigurationWithDataSourceAndNoTransactionManager.class); BatchConfigurer batchConfigurer = applicationContext.getBean(BatchConfigurer.class); PlatformTransactionManager platformTransactionManager = batchConfigurer.getTransactionManager(); - Assert.assertTrue(platformTransactionManager instanceof JdbcTransactionManager); + assertTrue(platformTransactionManager instanceof JdbcTransactionManager); JdbcTransactionManager JdbcTransactionManager = AopTestUtils.getTargetObject(platformTransactionManager); - Assert.assertEquals(applicationContext.getBean(DataSource.class), JdbcTransactionManager.getDataSource()); - Assert.assertSame(getTransactionManagerSetOnJobRepository(applicationContext.getBean(JobRepository.class)), + assertEquals(applicationContext.getBean(DataSource.class), JdbcTransactionManager.getDataSource()); + assertSame(getTransactionManagerSetOnJobRepository(applicationContext.getBean(JobRepository.class)), platformTransactionManager); } @Test - public void testConfigurationWithDataSourceAndTransactionManager() throws Exception { + void testConfigurationWithDataSourceAndTransactionManager() throws Exception { ApplicationContext applicationContext = new AnnotationConfigApplicationContext( BatchConfigurationWithDataSourceAndTransactionManager.class); BatchConfigurer batchConfigurer = applicationContext.getBean(BatchConfigurer.class); PlatformTransactionManager platformTransactionManager = batchConfigurer.getTransactionManager(); - Assert.assertSame(transactionManager, platformTransactionManager); - Assert.assertSame(getTransactionManagerSetOnJobRepository(applicationContext.getBean(JobRepository.class)), + assertSame(transactionManager, platformTransactionManager); + assertSame(getTransactionManagerSetOnJobRepository(applicationContext.getBean(JobRepository.class)), transactionManager); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/TransactionManagerConfigurationWithoutBatchConfigurerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/TransactionManagerConfigurationWithoutBatchConfigurerTests.java index f1013f0306..59c99cc56e 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/TransactionManagerConfigurationWithoutBatchConfigurerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/TransactionManagerConfigurationWithoutBatchConfigurerTests.java @@ -18,86 +18,76 @@ import javax.sql.DataSource; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import org.springframework.batch.core.JobParameters; -import org.springframework.batch.core.launch.JobLauncher; import org.springframework.batch.core.repository.JobRepository; import org.springframework.beans.factory.BeanCreationException; -import org.springframework.beans.factory.UnsatisfiedDependencyException; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.jdbc.support.JdbcTransactionManager; -import org.springframework.test.util.AopTestUtils; import org.springframework.transaction.PlatformTransactionManager; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * @author Mahmoud Ben Hassine */ -public class TransactionManagerConfigurationWithoutBatchConfigurerTests extends TransactionManagerConfigurationTests { - - @Test(expected = BeanCreationException.class) - public void testConfigurationWithNoDataSourceAndNoTransactionManager() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - BatchConfigurationWithNoDataSourceAndNoTransactionManager.class); - // beans created by `@EnableBatchProcessing` are lazy proxies, - // SimpleBatchConfiguration.initialize is only triggered - // when a method is called on one of these proxies - JobRepository jobRepository = context.getBean(JobRepository.class); - Assert.assertFalse(jobRepository.isJobInstanceExists("myJob", new JobParameters())); +class TransactionManagerConfigurationWithoutBatchConfigurerTests extends TransactionManagerConfigurationTests { + + @Test + void testConfigurationWithNoDataSourceAndNoTransactionManager() { + assertThrows(BeanCreationException.class, () -> new AnnotationConfigApplicationContext( + BatchConfigurationWithNoDataSourceAndNoTransactionManager.class)); } - @Test(expected = BeanCreationException.class) - public void testConfigurationWithNoDataSourceAndTransactionManager() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - BatchConfigurationWithNoDataSourceAndTransactionManager.class); - // beans created by `@EnableBatchProcessing` are lazy proxies, - // SimpleBatchConfiguration.initialize is only triggered - // when a method is called on one of these proxies - JobRepository jobRepository = context.getBean(JobRepository.class); - Assert.assertFalse(jobRepository.isJobInstanceExists("myJob", new JobParameters())); + @Test + void testConfigurationWithNoDataSourceAndTransactionManager() { + assertThrows(BeanCreationException.class, () -> new AnnotationConfigApplicationContext( + BatchConfigurationWithNoDataSourceAndTransactionManager.class)); } @Test - public void testConfigurationWithDataSourceAndNoTransactionManager() throws Exception { + void testConfigurationWithDataSourceAndNoTransactionManager() throws Exception { ApplicationContext applicationContext = new AnnotationConfigApplicationContext( BatchConfigurationWithDataSourceAndNoTransactionManager.class); PlatformTransactionManager platformTransactionManager = getTransactionManagerSetOnJobRepository( applicationContext.getBean(JobRepository.class)); - Assert.assertTrue(platformTransactionManager instanceof JdbcTransactionManager); + assertTrue(platformTransactionManager instanceof JdbcTransactionManager); JdbcTransactionManager JdbcTransactionManager = (JdbcTransactionManager) platformTransactionManager; - Assert.assertEquals(applicationContext.getBean(DataSource.class), JdbcTransactionManager.getDataSource()); + assertEquals(applicationContext.getBean(DataSource.class), JdbcTransactionManager.getDataSource()); } @Test - public void testConfigurationWithDataSourceAndOneTransactionManager() throws Exception { + void testConfigurationWithDataSourceAndOneTransactionManager() throws Exception { ApplicationContext applicationContext = new AnnotationConfigApplicationContext( BatchConfigurationWithDataSourceAndOneTransactionManager.class); PlatformTransactionManager platformTransactionManager = applicationContext .getBean(PlatformTransactionManager.class); - Assert.assertSame(transactionManager, platformTransactionManager); + assertSame(transactionManager, platformTransactionManager); // In this case, the supplied transaction manager won't be used by batch and a // JdbcTransactionManager will be used instead. // The user has to provide a custom BatchConfigurer. - Assert.assertTrue(getTransactionManagerSetOnJobRepository( + assertTrue(getTransactionManagerSetOnJobRepository( applicationContext.getBean(JobRepository.class)) instanceof JdbcTransactionManager); } @Test - public void testConfigurationWithDataSourceAndMultipleTransactionManagers() throws Exception { + void testConfigurationWithDataSourceAndMultipleTransactionManagers() throws Exception { ApplicationContext applicationContext = new AnnotationConfigApplicationContext( BatchConfigurationWithDataSourceAndMultipleTransactionManagers.class); PlatformTransactionManager platformTransactionManager = applicationContext .getBean(PlatformTransactionManager.class); - Assert.assertSame(transactionManager2, platformTransactionManager); + assertSame(transactionManager2, platformTransactionManager); // In this case, the supplied primary transaction manager won't be used by batch // and a JdbcTransactionManager will be used instead. // The user has to provide a custom BatchConfigurer. - Assert.assertTrue(getTransactionManagerSetOnJobRepository( + assertTrue(getTransactionManagerSetOnJobRepository( applicationContext.getBean(JobRepository.class)) instanceof JdbcTransactionManager); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/ApplicationContextJobFactoryTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/ApplicationContextJobFactoryTests.java index 794dd39142..e12b9e8ffd 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/ApplicationContextJobFactoryTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/ApplicationContextJobFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2012 the original author or authors. + * Copyright 2008-2022 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. @@ -15,27 +15,27 @@ */ package org.springframework.batch.core.configuration.support; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.job.JobSupport; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.StaticApplicationContext; -public class ApplicationContextJobFactoryTests { +class ApplicationContextJobFactoryTests { @Test - public void testFactoryContext() throws Exception { + void testFactoryContext() { ApplicationContextJobFactory factory = new ApplicationContextJobFactory("job", new StubApplicationContextFactory()); assertNotNull(factory.createJob()); } @Test - public void testPostProcessing() throws Exception { + void testPostProcessing() { ApplicationContextJobFactory factory = new ApplicationContextJobFactory("job", new PostProcessingApplicationContextFactory()); assertEquals("bar", factory.getJobName()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/AutomaticJobRegistrarContextTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/AutomaticJobRegistrarContextTests.java index eae166649d..5af7467e00 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/AutomaticJobRegistrarContextTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/AutomaticJobRegistrarContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2010 the original author or authors. + * Copyright 2010-2022 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. @@ -15,32 +15,29 @@ */ package org.springframework.batch.core.configuration.support; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Collection; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.Job; import org.springframework.batch.core.configuration.JobRegistry; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration -public class AutomaticJobRegistrarContextTests { +@SpringJUnitConfig +class AutomaticJobRegistrarContextTests { @Autowired private JobRegistry registry; @Test - public void testLocateJob() throws Exception { + void testLocateJob() throws Exception { Collection names = registry.getJobNames(); assertEquals(2, names.size()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/AutomaticJobRegistrarTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/AutomaticJobRegistrarTests.java index 7224355195..c58894659f 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/AutomaticJobRegistrarTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/AutomaticJobRegistrarTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 the original author or authors. + * Copyright 2010-2022 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. @@ -15,16 +15,16 @@ */ package org.springframework.batch.core.configuration.support; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Collection; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.batch.core.Job; import org.springframework.beans.factory.BeanCreationException; @@ -41,14 +41,14 @@ * @author Mahmoud Ben Hassine * */ -public class AutomaticJobRegistrarTests { +class AutomaticJobRegistrarTests { - private AutomaticJobRegistrar registrar = new AutomaticJobRegistrar(); + private final AutomaticJobRegistrar registrar = new AutomaticJobRegistrar(); - private MapJobRegistry registry = new MapJobRegistry(); + private final MapJobRegistry registry = new MapJobRegistry(); - @Before - public void setUp() { + @BeforeEach + void setUp() { DefaultJobLoader jobLoader = new DefaultJobLoader(); jobLoader.setJobRegistry(registry); registrar.setJobLoader(jobLoader); @@ -56,7 +56,7 @@ public void setUp() { @SuppressWarnings("cast") @Test - public void testOrderedImplemented() throws Exception { + void testOrderedImplemented() { assertTrue(registrar instanceof Ordered); assertEquals(Ordered.LOWEST_PRECEDENCE, registrar.getOrder()); @@ -66,27 +66,26 @@ public void testOrderedImplemented() throws Exception { } @Test - public void testDefaultAutoStartup() throws Exception { + void testDefaultAutoStartup() { assertTrue(registrar.isAutoStartup()); } @Test - public void testDefaultPhase() throws Exception { + void testDefaultPhase() { assertEquals(Integer.MIN_VALUE + 1000, registrar.getPhase()); } @Test - public void testLocateJob() throws Exception { + void testLocateJob() throws Exception { Resource[] jobPaths = new Resource[] { new ClassPathResource("org/springframework/batch/core/launch/support/job.xml"), new ClassPathResource("org/springframework/batch/core/launch/support/job2.xml") }; - @SuppressWarnings("resource") GenericApplicationContext applicationContext = new GenericApplicationContext(); applicationContext.refresh(); setUpApplicationContextFactories(jobPaths, applicationContext); @@ -105,11 +104,10 @@ public void testLocateJob() throws Exception { } @Test - public void testNoJobFound() throws Exception { + void testNoJobFound() { Resource[] jobPaths = new Resource[] { new ClassPathResource("org/springframework/batch/core/launch/support/test-environment.xml") }; - @SuppressWarnings("resource") GenericApplicationContext applicationContext = new GenericApplicationContext(); applicationContext.refresh(); setUpApplicationContextFactories(jobPaths, applicationContext); @@ -118,11 +116,10 @@ public void testNoJobFound() throws Exception { } @Test - public void testDuplicateJobsInFile() throws Exception { + void testDuplicateJobsInFile() { Resource[] jobPaths = new Resource[] { new ClassPathResource("org/springframework/batch/core/launch/support/2jobs.xml") }; - @SuppressWarnings("resource") GenericApplicationContext applicationContext = new GenericApplicationContext(); applicationContext.refresh(); setUpApplicationContextFactories(jobPaths, applicationContext); @@ -132,11 +129,10 @@ public void testDuplicateJobsInFile() throws Exception { } @Test - public void testChildContextOverridesBeanPostProcessor() throws Exception { + void testChildContextOverridesBeanPostProcessor() { Resource[] jobPaths = new Resource[] { new ClassPathResource("org/springframework/batch/core/launch/support/2jobs.xml") }; - @SuppressWarnings("resource") ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext( "/org/springframework/batch/core/launch/support/test-environment-with-registry-and-auto-register.xml"); registrar.setApplicationContext(applicationContext); @@ -146,23 +142,18 @@ public void testChildContextOverridesBeanPostProcessor() throws Exception { } @Test - public void testErrorInContext() throws Exception { + void testErrorInContext() { Resource[] jobPaths = new Resource[] { new ClassPathResource("org/springframework/batch/core/launch/support/2jobs.xml"), new ClassPathResource("org/springframework/batch/core/launch/support/error.xml") }; setUpApplicationContextFactories(jobPaths, null); - try { - registrar.start(); - fail("Expected BeanCreationException"); - } - catch (BeanCreationException e) { - } + assertThrows(BeanCreationException.class, registrar::start); } @Test - public void testClear() throws Exception { + void testClear() { Resource[] jobPaths = new Resource[] { new ClassPathResource("org/springframework/batch/core/launch/support/2jobs.xml") }; @@ -175,7 +166,7 @@ public void testClear() throws Exception { } @Test - public void testStartStopRunning() throws Exception { + void testStartStopRunning() { Resource[] jobPaths = new Resource[] { new ClassPathResource("org/springframework/batch/core/launch/support/2jobs.xml") }; @@ -190,7 +181,7 @@ public void testStartStopRunning() throws Exception { } @Test - public void testStartStopRunningWithCallback() throws Exception { + void testStartStopRunningWithCallback() { Runnable callback = Mockito.mock(Runnable.class); Resource[] jobPaths = new Resource[] { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/DefaultJobLoaderTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/DefaultJobLoaderTests.java index c7316a73ff..e0c3802992 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/DefaultJobLoaderTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/DefaultJobLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,14 +15,15 @@ */ package org.springframework.batch.core.configuration.support; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.Collection; import java.util.Collections; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParametersIncrementer; @@ -31,7 +32,6 @@ import org.springframework.batch.core.configuration.DuplicateJobException; import org.springframework.batch.core.configuration.JobRegistry; import org.springframework.batch.core.configuration.StepRegistry; -import org.springframework.batch.core.launch.NoSuchJobException; import org.springframework.batch.core.step.NoSuchStepException; import org.springframework.batch.core.step.StepLocator; import org.springframework.core.io.ByteArrayResource; @@ -44,7 +44,7 @@ * @author Stephane Nicoll * @author Mahmoud Ben Hassine */ -public class DefaultJobLoaderTests { +class DefaultJobLoaderTests { /** * The name of the job as defined in the test context used in this test. @@ -56,14 +56,14 @@ public class DefaultJobLoaderTests { */ private static final String TEST_STEP_NAME = "test-step"; - private JobRegistry jobRegistry = new MapJobRegistry(); + private final JobRegistry jobRegistry = new MapJobRegistry(); - private StepRegistry stepRegistry = new MapStepRegistry(); + private final StepRegistry stepRegistry = new MapStepRegistry(); - private DefaultJobLoader jobLoader = new DefaultJobLoader(jobRegistry, stepRegistry); + private final DefaultJobLoader jobLoader = new DefaultJobLoader(jobRegistry, stepRegistry); @Test - public void testClear() throws Exception { + void testClear() throws Exception { GenericApplicationContextFactory factory = new GenericApplicationContextFactory( new ByteArrayResource(JOB_XML.getBytes())); jobLoader.load(factory); @@ -75,7 +75,7 @@ public void testClear() throws Exception { } @Test - public void testLoadWithExplicitName() throws Exception { + void testLoadWithExplicitName() throws Exception { GenericApplicationContextFactory factory = new GenericApplicationContextFactory( new ByteArrayResource(JOB_XML.getBytes())); jobLoader.load(factory); @@ -85,7 +85,7 @@ public void testLoadWithExplicitName() throws Exception { } @Test - public void createWithBothRegistries() { + void createWithBothRegistries() { final DefaultJobLoader loader = new DefaultJobLoader(); loader.setJobRegistry(jobRegistry); loader.setStepRegistry(stepRegistry); @@ -94,7 +94,7 @@ public void createWithBothRegistries() { } @Test - public void createWithOnlyJobRegistry() { + void createWithOnlyJobRegistry() { final DefaultJobLoader loader = new DefaultJobLoader(); loader.setJobRegistry(jobRegistry); @@ -102,7 +102,7 @@ public void createWithOnlyJobRegistry() { } @Test - public void testRegistryUpdated() throws DuplicateJobException { + void testRegistryUpdated() throws DuplicateJobException { GenericApplicationContextFactory factory = new GenericApplicationContextFactory( new ClassPathResource("trivial-context.xml", getClass())); jobLoader.load(factory); @@ -111,7 +111,7 @@ public void testRegistryUpdated() throws DuplicateJobException { } @Test - public void testMultipleJobsInTheSameContext() throws DuplicateJobException { + void testMultipleJobsInTheSameContext() throws DuplicateJobException { GenericApplicationContextFactory factory = new GenericApplicationContextFactory( new ClassPathResource("job-context-with-steps.xml", getClass())); jobLoader.load(factory); @@ -123,7 +123,7 @@ public void testMultipleJobsInTheSameContext() throws DuplicateJobException { } @Test - public void testMultipleJobsInTheSameContextWithSeparateSteps() throws DuplicateJobException { + void testMultipleJobsInTheSameContextWithSeparateSteps() throws DuplicateJobException { GenericApplicationContextFactory factory = new GenericApplicationContextFactory( new ClassPathResource("job-context-with-separate-steps.xml", getClass())); jobLoader.load(factory); @@ -135,7 +135,7 @@ public void testMultipleJobsInTheSameContextWithSeparateSteps() throws Duplicate } @Test - public void testNoStepRegistryAvailable() throws DuplicateJobException { + void testNoStepRegistryAvailable() throws DuplicateJobException { final JobLoader loader = new DefaultJobLoader(jobRegistry); GenericApplicationContextFactory factory = new GenericApplicationContextFactory( new ClassPathResource("job-context-with-steps.xml", getClass())); @@ -145,36 +145,22 @@ public void testNoStepRegistryAvailable() throws DuplicateJobException { } @Test - public void testLoadWithJobThatIsNotAStepLocator() throws DuplicateJobException { + void testLoadWithJobThatIsNotAStepLocator() { GenericApplicationContextFactory factory = new GenericApplicationContextFactory( new ByteArrayResource(BASIC_JOB_XML.getBytes())); - try { - jobLoader.load(factory); - fail("Should have failed with a [" + UnsupportedOperationException.class.getName() + "] as job does not" - + "implement StepLocator."); - } - catch (UnsupportedOperationException e) { - // Job is not a step locator, can't register steps - } - + assertThrows(UnsupportedOperationException.class, () -> jobLoader.load(factory)); } @Test - public void testLoadWithJobThatIsNotAStepLocatorNoStepRegistry() throws DuplicateJobException { + void testLoadWithJobThatIsNotAStepLocatorNoStepRegistry() { final JobLoader loader = new DefaultJobLoader(jobRegistry); GenericApplicationContextFactory factory = new GenericApplicationContextFactory( new ByteArrayResource(BASIC_JOB_XML.getBytes())); - try { - loader.load(factory); - } - catch (UnsupportedOperationException e) { - fail("Should not have failed with a [" + UnsupportedOperationException.class.getName() + "] as " - + "stepRegistry is not available for this JobLoader instance."); - } + assertDoesNotThrow(() -> loader.load(factory)); } @Test - public void testReload() throws Exception { + void testReload() throws Exception { GenericApplicationContextFactory factory = new GenericApplicationContextFactory( new ClassPathResource("trivial-context.xml", getClass())); jobLoader.load(factory); @@ -186,7 +172,7 @@ public void testReload() throws Exception { } @Test - public void testReloadWithAutoRegister() throws Exception { + void testReloadWithAutoRegister() throws Exception { GenericApplicationContextFactory factory = new GenericApplicationContextFactory( new ClassPathResource("trivial-context-autoregister.xml", getClass())); jobLoader.load(factory); @@ -199,31 +185,13 @@ public void testReloadWithAutoRegister() throws Exception { protected void assertStepExist(String jobName, String... stepNames) { for (String stepName : stepNames) { - try { - stepRegistry.getStep(jobName, stepName); - } - catch (NoSuchJobException e) { - fail("Job with name [" + jobName + "] should have been found."); - } - catch (NoSuchStepException e) { - fail("Step with name [" + stepName + "] for job [" + jobName + "] should have been found."); - } + assertDoesNotThrow(() -> stepRegistry.getStep(jobName, stepName)); } } protected void assertStepDoNotExist(String jobName, String... stepNames) { for (String stepName : stepNames) { - try { - final Step step = stepRegistry.getStep(jobName, stepName); - fail("Step with name [" + stepName + "] for job [" + jobName + "] should " - + "not have been found but got [" + step + "]"); - } - catch (NoSuchJobException e) { - fail("Job with name [" + jobName + "] should have been found."); - } - catch (NoSuchStepException e) { - // OK - } + assertThrows(NoSuchStepException.class, () -> stepRegistry.getStep(jobName, stepName)); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/GenericApplicationContextFactoryTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/GenericApplicationContextFactoryTests.java index d9da01b88c..69f5fc20d8 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/GenericApplicationContextFactoryTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/GenericApplicationContextFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,12 +15,13 @@ */ package org.springframework.batch.core.configuration.support; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.Job; import org.springframework.batch.core.job.JobSupport; @@ -47,28 +48,26 @@ * @author Mahmoud Ben Hassine * */ -public class GenericApplicationContextFactoryTests { +class GenericApplicationContextFactoryTests { @Test - public void testCreateJob() { + void testCreateJob() { GenericApplicationContextFactory factory = new GenericApplicationContextFactory( new ClassPathResource(ClassUtils.addResourcePathToPackagePath(getClass(), "trivial-context.xml"))); - @SuppressWarnings("resource") ConfigurableApplicationContext context = factory.createApplicationContext(); assertNotNull(context); - assertTrue("Wrong id: " + context, context.getId().contains("trivial-context.xml")); + assertTrue(context.getId().contains("trivial-context.xml"), "Wrong id: " + context); } @Test - public void testGetJobName() { + void testGetJobName() { GenericApplicationContextFactory factory = new GenericApplicationContextFactory( new ClassPathResource(ClassUtils.addResourcePathToPackagePath(getClass(), "trivial-context.xml"))); assertEquals("test-job", factory.createApplicationContext().getBeanNamesForType(Job.class)[0]); } - @SuppressWarnings("resource") @Test - public void testParentConfigurationInherited() { + void testParentConfigurationInherited() { GenericApplicationContextFactory factory = new GenericApplicationContextFactory( new ClassPathResource(ClassUtils.addResourcePathToPackagePath(getClass(), "child-context.xml"))); factory.setApplicationContext(new ClassPathXmlApplicationContext( @@ -79,9 +78,8 @@ public void testParentConfigurationInherited() { assertEquals(4, context.getBean("foo", Foo.class).values[1], 0.01); } - @SuppressWarnings("resource") @Test - public void testBeanFactoryPostProcessorOrderRespected() { + void testBeanFactoryPostProcessorOrderRespected() { GenericApplicationContextFactory factory = new GenericApplicationContextFactory( new ClassPathResource(ClassUtils.addResourcePathToPackagePath(getClass(), "placeholder-context.xml"))); factory.setApplicationContext(new ClassPathXmlApplicationContext( @@ -91,26 +89,24 @@ public void testBeanFactoryPostProcessorOrderRespected() { assertEquals("spam", context.getBean("test-job", Job.class).getName()); } + // FIXME replacing PropertyPlaceholderConfigurer with + // PropertySourcesPlaceholderConfigurer does not seem to inherit profiles @Test - @Ignore // FIXME replacing PropertyPlaceholderConfigurer with - // PropertySourcesPlaceholderConfigurer does not seem to inherit profiles - public void testBeanFactoryProfileRespected() { + @Disabled + void testBeanFactoryProfileRespected() { GenericApplicationContextFactory factory = new GenericApplicationContextFactory( new ClassPathResource(ClassUtils.addResourcePathToPackagePath(getClass(), "profiles.xml"))); - @SuppressWarnings("resource") ClassPathXmlApplicationContext parentContext = new ClassPathXmlApplicationContext( ClassUtils.addResourcePathToPackagePath(getClass(), "parent-context.xml")); parentContext.getEnvironment().setActiveProfiles("preferred"); factory.setApplicationContext(parentContext); - @SuppressWarnings("resource") ConfigurableApplicationContext context = factory.createApplicationContext(); assertEquals("test-job", context.getBeanNamesForType(Job.class)[0]); assertEquals("spam", context.getBean("test-job", Job.class).getName()); } - @SuppressWarnings("resource") @Test - public void testBeanFactoryPostProcessorsNotCopied() { + void testBeanFactoryPostProcessorsNotCopied() { GenericApplicationContextFactory factory = new GenericApplicationContextFactory( new ClassPathResource(ClassUtils.addResourcePathToPackagePath(getClass(), "child-context.xml"))); factory.setApplicationContext(new ClassPathXmlApplicationContext( @@ -124,9 +120,8 @@ public void testBeanFactoryPostProcessorsNotCopied() { assertEquals(4, context.getBean("foo", Foo.class).values[1], 0.01); } - @SuppressWarnings("resource") @Test - public void testBeanFactoryConfigurationNotCopied() { + void testBeanFactoryConfigurationNotCopied() { GenericApplicationContextFactory factory = new GenericApplicationContextFactory( new ClassPathResource(ClassUtils.addResourcePathToPackagePath(getClass(), "child-context.xml"))); factory.setApplicationContext(new ClassPathXmlApplicationContext( @@ -141,7 +136,7 @@ public void testBeanFactoryConfigurationNotCopied() { } @Test - public void testEquals() throws Exception { + void testEquals() { Resource resource = new ClassPathResource( ClassUtils.addResourcePathToPackagePath(getClass(), "child-context.xml")); GenericApplicationContextFactory factory = new GenericApplicationContextFactory(resource); @@ -151,7 +146,7 @@ public void testEquals() throws Exception { } @Test - public void testEqualsMultipleConfigs() throws Exception { + void testEqualsMultipleConfigs() { Resource resource1 = new ClassPathResource( ClassUtils.addResourcePathToPackagePath(getClass(), "abstract-context.xml")); Resource resource2 = new ClassPathResource( @@ -163,7 +158,7 @@ public void testEqualsMultipleConfigs() throws Exception { } @Test - public void testParentConfigurationInheritedMultipleConfigs() { + void testParentConfigurationInheritedMultipleConfigs() { Resource resource1 = new ClassPathResource( ClassUtils.addResourcePathToPackagePath(getClass(), "abstract-context.xml")); Resource resource2 = new ClassPathResource( @@ -185,17 +180,17 @@ public void testParentConfigurationInheritedMultipleConfigs() { assertTrue(autowiredFound); } - @Test(expected = IllegalArgumentException.class) - public void testDifferentResourceTypes() throws Exception { + @Test + void testDifferentResourceTypes() { Resource resource1 = new ClassPathResource( ClassUtils.addResourcePathToPackagePath(getClass(), "abstract-context.xml")); GenericApplicationContextFactory factory = new GenericApplicationContextFactory(resource1, Configuration1.class); - factory.createApplicationContext(); + assertThrows(IllegalArgumentException.class, factory::createApplicationContext); } @Test - public void testPackageScanning() throws Exception { + void testPackageScanning() { GenericApplicationContextFactory factory = new GenericApplicationContextFactory( "org.springframework.batch.core.configuration.support"); ConfigurableApplicationContext context = factory.createApplicationContext(); @@ -207,7 +202,7 @@ public void testPackageScanning() throws Exception { } @Test - public void testMultipleConfigurationClasses() throws Exception { + void testMultipleConfigurationClasses() { GenericApplicationContextFactory factory = new GenericApplicationContextFactory(Configuration1.class, Configuration2.class); ConfigurableApplicationContext context = factory.createApplicationContext(); @@ -219,7 +214,7 @@ public void testMultipleConfigurationClasses() throws Exception { } @Test - public void testParentChildLifecycleEvents() throws InterruptedException { + void testParentChildLifecycleEvents() { AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext(ParentContext.class); GenericApplicationContextFactory child = new GenericApplicationContextFactory(ChildContextConfiguration.class); child.setApplicationContext(parent); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/GroupAwareJobTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/GroupAwareJobTests.java index 113489511f..ad1af070fe 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/GroupAwareJobTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/GroupAwareJobTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,9 +15,9 @@ */ package org.springframework.batch.core.configuration.support; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.Job; import org.springframework.batch.core.job.JobSupport; @@ -25,24 +25,24 @@ * @author Dave Syer * */ -public class GroupAwareJobTests { +class GroupAwareJobTests { - private Job job = new JobSupport("foo"); + private final Job job = new JobSupport("foo"); @Test - public void testCreateJob() { + void testCreateJob() { GroupAwareJob result = new GroupAwareJob(job); assertEquals("foo", result.getName()); } @Test - public void testGetJobName() { + void testGetJobName() { GroupAwareJob result = new GroupAwareJob("jobs", job); assertEquals("jobs.foo", result.getName()); } @Test - public void testToString() { + void testToString() { GroupAwareJob result = new GroupAwareJob("jobs", job); assertEquals("JobSupport: [name=jobs.foo]", result.toString()); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/JobFactoryRegistrationListenerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/JobFactoryRegistrationListenerTests.java index 55cbabf293..d834a3e981 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/JobFactoryRegistrationListenerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/JobFactoryRegistrationListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2013 the original author or authors. + * Copyright 2006-2022 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. @@ -15,9 +15,9 @@ */ package org.springframework.batch.core.configuration.support; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.Job; import org.springframework.batch.core.configuration.JobFactory; @@ -25,19 +25,14 @@ * @author Dave Syer * */ -public class JobFactoryRegistrationListenerTests { +class JobFactoryRegistrationListenerTests { - private JobFactoryRegistrationListener listener = new JobFactoryRegistrationListener(); + private final JobFactoryRegistrationListener listener = new JobFactoryRegistrationListener(); - private MapJobRegistry registry = new MapJobRegistry(); + private final MapJobRegistry registry = new MapJobRegistry(); - /** - * Test method for - * {@link org.springframework.batch.core.configuration.support.JobFactoryRegistrationListener#bind(org.springframework.batch.core.configuration.JobFactory, java.util.Map)}. - * @throws Exception - */ @Test - public void testBind() throws Exception { + void testBind() throws Exception { listener.setJobRegistry(registry); listener.bind(new JobFactory() { @Override @@ -53,13 +48,8 @@ public String getJobName() { assertEquals(1, registry.getJobNames().size()); } - /** - * Test method for - * {@link org.springframework.batch.core.configuration.support.JobFactoryRegistrationListener#unbind(org.springframework.batch.core.configuration.JobFactory, java.util.Map)}. - * @throws Exception - */ @Test - public void testUnbind() throws Exception { + void testUnbind() throws Exception { testBind(); listener.unbind(new JobFactory() { @Override diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/JobRegistryBeanPostProcessorTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/JobRegistryBeanPostProcessorTests.java index 4af662ea94..923ac92bbe 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/JobRegistryBeanPostProcessorTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/JobRegistryBeanPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,14 +15,14 @@ */ package org.springframework.batch.core.configuration.support; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Collection; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.configuration.DuplicateJobException; import org.springframework.batch.core.job.JobSupport; import org.springframework.beans.FatalBeanException; @@ -30,38 +30,32 @@ /** * @author Dave Syer - * + * */ -public class JobRegistryBeanPostProcessorTests { +class JobRegistryBeanPostProcessorTests { - private JobRegistryBeanPostProcessor processor = new JobRegistryBeanPostProcessor(); + private final JobRegistryBeanPostProcessor processor = new JobRegistryBeanPostProcessor(); @Test - public void testInitializationFails() throws Exception { - try { - processor.afterPropertiesSet(); - fail("Expected IllegalArgumentException"); - } - catch (IllegalArgumentException e) { - // expected - assertTrue(e.getMessage().contains("JobRegistry")); - } + void testInitializationFails() { + Exception exception = assertThrows(IllegalArgumentException.class, processor::afterPropertiesSet); + assertTrue(exception.getMessage().contains("JobRegistry")); } @Test - public void testBeforeInitialization() throws Exception { + void testBeforeInitialization() { // should be a no-op assertEquals("foo", processor.postProcessBeforeInitialization("foo", "bar")); } @Test - public void testAfterInitializationWithWrongType() throws Exception { + void testAfterInitializationWithWrongType() { // should be a no-op assertEquals("foo", processor.postProcessAfterInitialization("foo", "bar")); } @Test - public void testAfterInitializationWithCorrectType() throws Exception { + void testAfterInitializationWithCorrectType() { MapJobRegistry registry = new MapJobRegistry(); processor.setJobRegistry(registry); JobSupport job = new JobSupport(); @@ -71,7 +65,7 @@ public void testAfterInitializationWithCorrectType() throws Exception { } @Test - public void testAfterInitializationWithGroupName() throws Exception { + void testAfterInitializationWithGroupName() { MapJobRegistry registry = new MapJobRegistry(); processor.setJobRegistry(registry); processor.setGroupName("jobs"); @@ -82,24 +76,19 @@ public void testAfterInitializationWithGroupName() throws Exception { } @Test - public void testAfterInitializationWithDuplicate() throws Exception { + void testAfterInitializationWithDuplicate() { MapJobRegistry registry = new MapJobRegistry(); processor.setJobRegistry(registry); JobSupport job = new JobSupport(); job.setBeanName("foo"); processor.postProcessAfterInitialization(job, "bar"); - try { - processor.postProcessAfterInitialization(job, "spam"); - fail("Expected FatalBeanException"); - } - catch (FatalBeanException e) { - // Expected - assertTrue(e.getCause() instanceof DuplicateJobException); - } + Exception exception = assertThrows(FatalBeanException.class, + () -> processor.postProcessAfterInitialization(job, "spam")); + assertTrue(exception.getCause() instanceof DuplicateJobException); } @Test - public void testUnregisterOnDestroy() throws Exception { + void testUnregisterOnDestroy() throws Exception { MapJobRegistry registry = new MapJobRegistry(); processor.setJobRegistry(registry); JobSupport job = new JobSupport(); @@ -110,8 +99,7 @@ public void testUnregisterOnDestroy() throws Exception { } @Test - @SuppressWarnings("resource") - public void testExecutionWithApplicationContext() throws Exception { + void testExecutionWithApplicationContext() throws Exception { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("test-context.xml", getClass()); MapJobRegistry registry = (MapJobRegistry) context.getBean("registry"); Collection configurations = registry.getJobNames(); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/JobRegistryIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/JobRegistryIntegrationTests.java index 05368b8fc2..7586b62ebe 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/JobRegistryIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/JobRegistryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,23 +15,20 @@ */ package org.springframework.batch.core.configuration.support; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.Job; import org.springframework.batch.core.configuration.JobRegistry; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class JobRegistryIntegrationTests { +@SpringJUnitConfig +class JobRegistryIntegrationTests { @Autowired private JobRegistry jobRegistry; @@ -40,7 +37,7 @@ public class JobRegistryIntegrationTests { private Job job; @Test - public void testRegistry() throws Exception { + void testRegistry() { assertEquals(1, jobRegistry.getJobNames().size()); assertEquals(job.getName(), jobRegistry.getJobNames().iterator().next()); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/MapJobRegistryTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/MapJobRegistryTests.java index 2fc3affa09..d35c5ff7d9 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/MapJobRegistryTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/MapJobRegistryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -17,79 +17,52 @@ import java.util.Collection; -import junit.framework.TestCase; - +import org.junit.jupiter.api.Test; import org.springframework.batch.core.configuration.DuplicateJobException; import org.springframework.batch.core.configuration.JobFactory; import org.springframework.batch.core.job.JobSupport; import org.springframework.batch.core.launch.NoSuchJobException; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * @author Dave Syer * */ -public class MapJobRegistryTests extends TestCase { +class MapJobRegistryTests { - private MapJobRegistry registry = new MapJobRegistry(); + private final MapJobRegistry registry = new MapJobRegistry(); - /** - * Test method for - * {@link org.springframework.batch.core.configuration.support.MapJobRegistry#unregister(String)}. - * @throws Exception - */ - public void testUnregister() throws Exception { + @Test + void testUnregister() throws Exception { registry.register(new ReferenceJobFactory(new JobSupport("foo"))); assertNotNull(registry.getJob("foo")); registry.unregister("foo"); - try { - assertNull(registry.getJob("foo")); - fail("Expected NoSuchJobConfigurationException"); - } - catch (NoSuchJobException e) { - // expected - assertTrue(e.getMessage().indexOf("foo") >= 0); - } + Exception exception = assertThrows(NoSuchJobException.class, () -> registry.getJob("foo")); + assertTrue(exception.getMessage().contains("foo")); } - /** - * Test method for - * {@link org.springframework.batch.core.configuration.support.MapJobRegistry#getJob(java.lang.String)}. - */ - public void testReplaceDuplicateConfiguration() throws Exception { + @Test + void testReplaceDuplicateConfiguration() throws Exception { registry.register(new ReferenceJobFactory(new JobSupport("foo"))); - try { - registry.register(new ReferenceJobFactory(new JobSupport("foo"))); - fail("Expected DuplicateJobConfigurationException"); - } - catch (DuplicateJobException e) { - // unexpected: even if the job is different we want a DuplicateJobException - assertTrue(e.getMessage().indexOf("foo") >= 0); - } + JobFactory jobFactory = new ReferenceJobFactory(new JobSupport("foo")); + Exception exception = assertThrows(DuplicateJobException.class, () -> registry.register(jobFactory)); + assertTrue(exception.getMessage().contains("foo")); } - /** - * Test method for - * {@link org.springframework.batch.core.configuration.support.MapJobRegistry#getJob(java.lang.String)}. - */ - public void testRealDuplicateConfiguration() throws Exception { + @Test + void testRealDuplicateConfiguration() throws Exception { JobFactory jobFactory = new ReferenceJobFactory(new JobSupport("foo")); registry.register(jobFactory); - try { - registry.register(jobFactory); - fail("Unexpected DuplicateJobConfigurationException"); - } - catch (DuplicateJobException e) { - // expected - assertTrue(e.getMessage().indexOf("foo") >= 0); - } + Exception exception = assertThrows(DuplicateJobException.class, () -> registry.register(jobFactory)); + assertTrue(exception.getMessage().contains("foo")); } - /** - * Test method for - * {@link org.springframework.batch.core.configuration.support.MapJobRegistry#getJobNames()}. - * @throws Exception - */ - public void testGetJobConfigurations() throws Exception { + @Test + void testGetJobConfigurations() throws Exception { JobFactory jobFactory = new ReferenceJobFactory(new JobSupport("foo")); registry.register(jobFactory); registry.register(new ReferenceJobFactory(new JobSupport("bar"))); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/MapStepRegistryTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/MapStepRegistryTests.java index f812945ff6..394132cb31 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/MapStepRegistryTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/MapStepRegistryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 the original author or authors. + * Copyright 2012-2022 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. @@ -15,14 +15,14 @@ */ package org.springframework.batch.core.configuration.support; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.DuplicateJobException; import org.springframework.batch.core.configuration.StepRegistry; @@ -33,43 +33,29 @@ /** * @author Sebastien Gerard */ -public class MapStepRegistryTests { - - private static final String EXCEPTION_NOT_THROWN_MSG = "An exception should have been thrown"; +class MapStepRegistryTests { @Test - public void registerStepEmptyCollection() throws DuplicateJobException { + void registerStepEmptyCollection() throws DuplicateJobException { final StepRegistry stepRegistry = createRegistry(); launchRegisterGetRegistered(stepRegistry, "myJob", getStepCollection()); } @Test - public void registerStepNullJobName() throws DuplicateJobException { - final StepRegistry stepRegistry = createRegistry(); - - try { - stepRegistry.register(null, new HashSet<>()); - Assert.fail(EXCEPTION_NOT_THROWN_MSG); - } - catch (IllegalArgumentException e) { - } + void registerStepNullJobName() { + StepRegistry stepRegistry = createRegistry(); + assertThrows(IllegalArgumentException.class, () -> stepRegistry.register(null, new HashSet<>())); } @Test - public void registerStepNullSteps() throws DuplicateJobException { - final StepRegistry stepRegistry = createRegistry(); - - try { - stepRegistry.register("fdsfsd", null); - Assert.fail(EXCEPTION_NOT_THROWN_MSG); - } - catch (IllegalArgumentException e) { - } + void registerStepNullSteps() { + StepRegistry stepRegistry = createRegistry(); + assertThrows(IllegalArgumentException.class, () -> stepRegistry.register("fdsfsd", null)); } @Test - public void registerStepGetStep() throws DuplicateJobException { + void registerStepGetStep() throws DuplicateJobException { final StepRegistry stepRegistry = createRegistry(); launchRegisterGetRegistered(stepRegistry, "myJob", @@ -77,7 +63,7 @@ public void registerStepGetStep() throws DuplicateJobException { } @Test - public void getJobNotRegistered() throws DuplicateJobException { + void getJobNotRegistered() throws DuplicateJobException { final StepRegistry stepRegistry = createRegistry(); final String aStepName = "myStep"; @@ -88,14 +74,14 @@ public void getJobNotRegistered() throws DuplicateJobException { } @Test - public void getJobNotRegisteredNoRegistration() { + void getJobNotRegisteredNoRegistration() { final StepRegistry stepRegistry = createRegistry(); assertJobNotRegistered(stepRegistry, "a ghost"); } @Test - public void getStepNotRegistered() throws DuplicateJobException { + void getStepNotRegistered() throws DuplicateJobException { final StepRegistry stepRegistry = createRegistry(); final String jobName = "myJob"; @@ -106,7 +92,7 @@ public void getStepNotRegistered() throws DuplicateJobException { } @Test - public void registerTwice() throws DuplicateJobException { + void registerTwice() throws DuplicateJobException { final StepRegistry stepRegistry = createRegistry(); final String jobName = "myJob"; @@ -117,44 +103,27 @@ public void registerTwice() throws DuplicateJobException { launchRegisterGetRegistered(stepRegistry, jobName, stepsFirstRegistration); // Second registration with same name should fail - try { - stepRegistry.register(jobName, getStepCollection(createStep("myFourthStep"), createStep("lastOne"))); - fail("Should have failed with a " + DuplicateJobException.class.getSimpleName()); - } - catch (DuplicateJobException e) { - // OK - } + assertThrows(DuplicateJobException.class, () -> stepRegistry.register(jobName, + getStepCollection(createStep("myFourthStep"), createStep("lastOne")))); } @Test - public void getStepNullJobName() throws NoSuchJobException { - final StepRegistry stepRegistry = createRegistry(); - - try { - stepRegistry.getStep(null, "a step"); - Assert.fail(EXCEPTION_NOT_THROWN_MSG); - } - catch (IllegalArgumentException e) { - } + void getStepNullJobName() { + StepRegistry stepRegistry = createRegistry(); + assertThrows(IllegalArgumentException.class, () -> stepRegistry.getStep(null, "a step")); } @Test - public void getStepNullStepName() throws NoSuchJobException, DuplicateJobException { + void getStepNullStepName() throws DuplicateJobException { final StepRegistry stepRegistry = createRegistry(); final String stepName = "myStep"; launchRegisterGetRegistered(stepRegistry, "myJob", getStepCollection(createStep(stepName))); - - try { - stepRegistry.getStep(null, stepName); - Assert.fail(EXCEPTION_NOT_THROWN_MSG); - } - catch (IllegalArgumentException e) { - } + assertThrows(IllegalArgumentException.class, () -> stepRegistry.getStep(null, stepName)); } @Test - public void registerStepUnregisterJob() throws DuplicateJobException { + void registerStepUnregisterJob() throws DuplicateJobException { final StepRegistry stepRegistry = createRegistry(); final Collection steps = getStepCollection(createStep("myStep"), createStep("myOtherStep"), @@ -168,19 +137,13 @@ public void registerStepUnregisterJob() throws DuplicateJobException { } @Test - public void unregisterJobNameNull() { - final StepRegistry stepRegistry = createRegistry(); - - try { - stepRegistry.unregisterStepsFromJob(null); - Assert.fail(EXCEPTION_NOT_THROWN_MSG); - } - catch (IllegalArgumentException e) { - } + void unregisterJobNameNull() { + StepRegistry stepRegistry = createRegistry(); + assertThrows(IllegalArgumentException.class, () -> stepRegistry.unregisterStepsFromJob(null)); } @Test - public void unregisterNoRegistration() { + void unregisterNoRegistration() { final StepRegistry stepRegistry = createRegistry(); assertJobNotRegistered(stepRegistry, "a job"); @@ -205,22 +168,12 @@ protected void launchRegisterGetRegistered(StepRegistry stepRegistry, String job } protected void assertJobNotRegistered(StepRegistry stepRegistry, String jobName) { - try { - stepRegistry.getStep(jobName, "a step"); - Assert.fail(EXCEPTION_NOT_THROWN_MSG); - } - catch (NoSuchJobException e) { - } + assertThrows(NoSuchJobException.class, () -> stepRegistry.getStep(jobName, "a step")); } protected void assertStepsRegistered(StepRegistry stepRegistry, String jobName, Collection steps) { for (Step step : steps) { - try { - stepRegistry.getStep(jobName, step.getName()); - } - catch (NoSuchJobException e) { - Assert.fail("Unexpected exception " + e); - } + assertDoesNotThrow(() -> stepRegistry.getStep(jobName, step.getName())); } } @@ -231,15 +184,7 @@ protected void assertStepsNotRegistered(StepRegistry stepRegistry, String jobNam } protected void assertStepNameNotRegistered(StepRegistry stepRegistry, String jobName, String stepName) { - try { - stepRegistry.getStep(jobName, stepName); - Assert.fail(EXCEPTION_NOT_THROWN_MSG); - } - catch (NoSuchJobException e) { - Assert.fail("Unexpected exception"); - } - catch (NoSuchStepException e) { - } + assertThrows(NoSuchStepException.class, () -> stepRegistry.getStep(jobName, stepName)); } } \ No newline at end of file diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/ReferenceJobFactoryTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/ReferenceJobFactoryTests.java index bee25289e0..122bf05556 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/ReferenceJobFactoryTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/ReferenceJobFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,19 +15,19 @@ */ package org.springframework.batch.core.configuration.support; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.job.JobSupport; /** * @author Dave Syer * */ -public class ReferenceJobFactoryTests { +class ReferenceJobFactoryTests { @Test - public void testGroupName() throws Exception { + void testGroupName() { ReferenceJobFactory factory = new ReferenceJobFactory(new JobSupport("foo")); assertEquals("foo", factory.getJobName()); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/AbstractJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/AbstractJobParserTests.java index bd9510f5df..d22a663a74 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/AbstractJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/AbstractJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -17,7 +17,7 @@ import java.util.ArrayList; -import org.junit.Before; +import org.junit.jupiter.api.BeforeEach; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -29,8 +29,6 @@ import org.springframework.batch.core.repository.JobRestartException; import org.springframework.beans.factory.annotation.Autowired; -import static org.junit.Assert.fail; - /** * @author Dan Garrette * @author Mahmoud Ben Hassine @@ -47,8 +45,8 @@ public abstract class AbstractJobParserTests { @Autowired protected ArrayList stepNamesList = new ArrayList<>(); - @Before - public void setUp() { + @BeforeEach + void setUp() { stepNamesList.clear(); } @@ -67,8 +65,7 @@ protected StepExecution getStepExecution(JobExecution jobExecution, String stepN return stepExecution; } } - fail("No stepExecution found with name: [" + stepName + "]"); - return null; + throw new AssertionError("No stepExecution found with name: [" + stepName + "]"); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/AutoRegisteringJobScopeTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/AutoRegisteringJobScopeTests.java index ffd360cf55..4db299aff6 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/AutoRegisteringJobScopeTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/AutoRegisteringJobScopeTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013 the original author or authors. + * Copyright 2013-2022 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. @@ -15,11 +15,11 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.scope.JobScope; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; @@ -28,24 +28,22 @@ * @author Thomas Risberg * @author Jimmy Praet */ -public class AutoRegisteringJobScopeTests { +class AutoRegisteringJobScopeTests { @Test - @SuppressWarnings("resource") - public void testJobElement() throws Exception { + void testJobElement() { ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/xml/AutoRegisteringJobScopeForJobElementTests-context.xml"); Map beans = ctx.getBeansOfType(JobScope.class); - assertTrue("JobScope not defined properly", beans.size() == 1); + assertEquals(1, beans.size(), "JobScope not defined properly"); } @Test - @SuppressWarnings("resource") - public void testStepElement() throws Exception { + void testStepElement() { ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/xml/AutoRegisteringJobScopeForStepElementTests-context.xml"); Map beans = ctx.getBeansOfType(JobScope.class); - assertTrue("JobScope not defined properly", beans.size() == 1); + assertEquals(1, beans.size(), "JobScope not defined properly"); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/AutoRegisteringStepScopeTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/AutoRegisteringStepScopeTests.java index 015a9ee2d1..9fb40b888b 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/AutoRegisteringStepScopeTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/AutoRegisteringStepScopeTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2009 the original author or authors. + * Copyright 2006-2022 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. @@ -15,36 +15,34 @@ */ package org.springframework.batch.core.configuration.xml; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.scope.StepScope; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.Map; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Thomas Risberg */ -public class AutoRegisteringStepScopeTests { +class AutoRegisteringStepScopeTests { @Test - @SuppressWarnings("resource") - public void testJobElement() throws Exception { + void testJobElement() { ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/xml/AutoRegisteringStepScopeForJobElementTests-context.xml"); Map beans = ctx.getBeansOfType(StepScope.class); - assertTrue("StepScope not defined properly", beans.size() == 1); + assertEquals(1, beans.size(), "StepScope not defined properly"); } @Test - @SuppressWarnings("resource") - public void testStepElement() throws Exception { + void testStepElement() { ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/xml/AutoRegisteringStepScopeForStepElementTests-context.xml"); Map beans = ctx.getBeansOfType(StepScope.class); - assertTrue("StepScope not defined properly", beans.size() == 1); + assertEquals(1, beans.size(), "StepScope not defined properly"); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/BeanDefinitionOverrideTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/BeanDefinitionOverrideTests.java index 93e724de3c..9a91891aed 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/BeanDefinitionOverrideTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/BeanDefinitionOverrideTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014 the original author or authors. + * Copyright 2014-2022 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. @@ -15,7 +15,7 @@ */ package org.springframework.batch.core.configuration.xml; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; /** @@ -23,10 +23,10 @@ * Test cases for BATCH-1863. *

*/ -public class BeanDefinitionOverrideTests { +class BeanDefinitionOverrideTests { @Test - public void testAllowBeanOverride() { + void testAllowBeanOverride() { ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(); applicationContext.setConfigLocation( "org/springframework/batch/core/configuration/xml/BeanDefinitionOverrideTests-context.xml"); @@ -34,7 +34,7 @@ public void testAllowBeanOverride() { } @Test - public void testAllowBeanOverrideFalse() { + void testAllowBeanOverrideFalse() { ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(); applicationContext.setAllowBeanDefinitionOverriding(false); applicationContext.setConfigLocation( diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/BranchStepJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/BranchStepJobParserTests.java index 0cc093956b..dfbc44e4aa 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/BranchStepJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/BranchStepJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,14 +15,13 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.ArrayList; import java.util.List; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -30,16 +29,14 @@ import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.repository.JobRepository; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer - * + * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class BranchStepJobParserTests { +@SpringJUnitConfig +class BranchStepJobParserTests { @Autowired private Job job; @@ -48,7 +45,7 @@ public class BranchStepJobParserTests { private JobRepository jobRepository; @Test - public void testBranchStep() throws Exception { + void testBranchStep() throws Exception { assertNotNull(job); JobExecution jobExecution = jobRepository.createJobExecution(job.getName(), new JobParameters()); job.execute(jobExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/ChunkElementParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/ChunkElementParserTests.java index 0314a95043..feecf382bd 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/ChunkElementParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/ChunkElementParserTests.java @@ -20,7 +20,7 @@ import java.util.Collection; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.Step; import org.springframework.batch.core.step.item.SimpleChunkProcessor; @@ -34,6 +34,7 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.core.NestedRuntimeException; import org.springframework.dao.CannotAcquireLockException; import org.springframework.dao.CannotSerializeTransactionException; import org.springframework.dao.ConcurrencyFailureException; @@ -45,11 +46,11 @@ import org.springframework.test.util.ReflectionTestUtils; import org.springframework.util.StringUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Dan Garrette @@ -57,56 +58,43 @@ * @author Mahmoud Ben Hassine * @since 2.0 */ -public class ChunkElementParserTests { +class ChunkElementParserTests { @Test - @SuppressWarnings("resource") - public void testSimpleAttributes() throws Exception { + void testSimpleAttributes() { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/xml/ChunkElementSimpleAttributeParserTests-context.xml"); Object step = context.getBean("s1", Step.class); - assertNotNull("Step not parsed", step); + assertNotNull(step, "Step not parsed"); Object tasklet = ReflectionTestUtils.getField(step, "tasklet"); Object chunkProcessor = ReflectionTestUtils.getField(tasklet, "chunkProcessor"); - assertTrue("Wrong processor type", chunkProcessor instanceof SimpleChunkProcessor); + assertTrue(chunkProcessor instanceof SimpleChunkProcessor, "Wrong processor type"); } @Test - @SuppressWarnings("resource") - public void testCommitIntervalLateBinding() throws Exception { + void testCommitIntervalLateBinding() { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/xml/ChunkElementLateBindingParserTests-context.xml"); Step step = context.getBean("s1", Step.class); - assertNotNull("Step not parsed", step); + assertNotNull(step, "Step not parsed"); } @Test - @SuppressWarnings("resource") - public void testSkipAndRetryAttributes() throws Exception { + void testSkipAndRetryAttributes() { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/xml/ChunkElementSkipAndRetryAttributeParserTests-context.xml"); Step step = context.getBean("s1", Step.class); - assertNotNull("Step not parsed", step); + assertNotNull(step, "Step not parsed"); } @Test - @SuppressWarnings("resource") - public void testIllegalSkipAndRetryAttributes() throws Exception { - try { - ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( - "org/springframework/batch/core/configuration/xml/ChunkElementIllegalSkipAndRetryAttributeParserTests-context.xml"); - Step step = context.getBean("s1", Step.class); - assertNotNull("Step not parsed", step); - fail("Expected BeanCreationException"); - } - catch (BeanCreationException e) { - // expected - } + void testIllegalSkipAndRetryAttributes() { + assertThrows(BeanCreationException.class, () -> new ClassPathXmlApplicationContext( + "org/springframework/batch/core/configuration/xml/ChunkElementIllegalSkipAndRetryAttributeParserTests-context.xml")); } @Test - public void testRetryPolicyAttribute() throws Exception { - @SuppressWarnings("resource") + void testRetryPolicyAttribute() throws Exception { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/xml/ChunkElementRetryPolicyParserTests-context.xml"); Map, Boolean> retryable = getNestedExceptionMap("s1", context, @@ -118,8 +106,7 @@ public void testRetryPolicyAttribute() throws Exception { } @Test - public void testRetryPolicyElement() throws Exception { - @SuppressWarnings("resource") + void testRetryPolicyElement() throws Exception { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/xml/ChunkElementRetryPolicyParserTests-context.xml"); SimpleRetryPolicy policy = (SimpleRetryPolicy) getPolicy("s2", context, @@ -128,8 +115,7 @@ public void testRetryPolicyElement() throws Exception { } @Test - public void testSkipPolicyAttribute() throws Exception { - @SuppressWarnings("resource") + void testSkipPolicyAttribute() throws Exception { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/xml/ChunkElementSkipPolicyParserTests-context.xml"); SkipPolicy policy = getSkipPolicy("s1", context); @@ -138,8 +124,7 @@ public void testSkipPolicyAttribute() throws Exception { } @Test - public void testSkipPolicyElement() throws Exception { - @SuppressWarnings("resource") + void testSkipPolicyElement() throws Exception { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/xml/ChunkElementSkipPolicyParserTests-context.xml"); SkipPolicy policy = getSkipPolicy("s2", context); @@ -148,48 +133,41 @@ public void testSkipPolicyElement() throws Exception { } @Test - @SuppressWarnings("resource") - public void testProcessorTransactionalAttributes() throws Exception { + void testProcessorTransactionalAttributes() { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/xml/ChunkElementTransactionalAttributeParserTests-context.xml"); Object step = context.getBean("s1", Step.class); - assertNotNull("Step not parsed", step); + assertNotNull(step, "Step not parsed"); Object tasklet = ReflectionTestUtils.getField(step, "tasklet"); Object chunkProcessor = ReflectionTestUtils.getField(tasklet, "chunkProcessor"); Boolean processorTransactional = (Boolean) ReflectionTestUtils.getField(chunkProcessor, "processorTransactional"); - assertFalse("Flag not set", processorTransactional); + assertFalse(processorTransactional, "Flag not set"); } @Test - @SuppressWarnings("resource") - public void testProcessorTransactionalNotAllowedOnSimpleProcessor() throws Exception { + void testProcessorTransactionalNotAllowedOnSimpleProcessor() { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/xml/ChunkElementIllegalAttributeParserTests-context.xml"); Object step = context.getBean("s1", Step.class); - assertNotNull("Step not parsed", step); + assertNotNull(step, "Step not parsed"); Object tasklet = ReflectionTestUtils.getField(step, "tasklet"); Object chunkProcessor = ReflectionTestUtils.getField(tasklet, "chunkProcessor"); assertTrue(chunkProcessor instanceof SimpleChunkProcessor); } @Test - public void testProcessorNonTransactionalNotAllowedWithTransactionalReader() throws Exception { - try { - new ClassPathXmlApplicationContext( - "org/springframework/batch/core/configuration/xml/ChunkElementIllegalTransactionalAttributeParserTests-context.xml"); - fail("Expected BeanCreationException"); - } - catch (BeanCreationException e) { - String msg = e.getRootCause().getMessage(); - assertTrue("Wrong message: " + msg, - msg.contains("The field 'processor-transactional' cannot be false if 'reader-transactional")); - } - + void testProcessorNonTransactionalNotAllowedWithTransactionalReader() { + NestedRuntimeException exception = assertThrows(BeanCreationException.class, + () -> new ClassPathXmlApplicationContext( + "org/springframework/batch/core/configuration/xml/ChunkElementIllegalTransactionalAttributeParserTests-context.xml")); + String msg = exception.getRootCause().getMessage(); + assertTrue(msg.contains("The field 'processor-transactional' cannot be false if 'reader-transactional"), + "Wrong message: " + msg); } @Test - public void testRetryable() throws Exception { + void testRetryable() throws Exception { Map, Boolean> retryable = getRetryableExceptionClasses("s1", getContext()); System.err.println(retryable); assertEquals(3, retryable.size()); @@ -198,7 +176,7 @@ public void testRetryable() throws Exception { } @Test - public void testRetryableInherited() throws Exception { + void testRetryableInherited() throws Exception { Map, Boolean> retryable = getRetryableExceptionClasses("s3", getContext()); System.err.println(retryable); assertEquals(2, retryable.size()); @@ -206,7 +184,7 @@ public void testRetryableInherited() throws Exception { } @Test - public void testRetryableInheritedMerge() throws Exception { + void testRetryableInheritedMerge() throws Exception { Map, Boolean> retryable = getRetryableExceptionClasses("s4", getContext()); System.err.println(retryable); assertEquals(3, retryable.size()); @@ -214,7 +192,7 @@ public void testRetryableInheritedMerge() throws Exception { } @Test - public void testInheritSkippable() throws Exception { + void testInheritSkippable() throws Exception { Map, Boolean> skippable = getSkippableExceptionClasses("s1", getContext()); System.err.println(skippable); assertEquals(5, skippable.size()); @@ -225,7 +203,7 @@ public void testInheritSkippable() throws Exception { } @Test - public void testInheritSkippableWithNoMerge() throws Exception { + void testInheritSkippableWithNoMerge() throws Exception { Map, Boolean> skippable = getSkippableExceptionClasses("s2", getContext()); assertEquals(3, skippable.size()); containsClassified(skippable, IllegalArgumentException.class, true); @@ -235,7 +213,7 @@ public void testInheritSkippableWithNoMerge() throws Exception { } @Test - public void testInheritStreams() throws Exception { + void testInheritStreams() throws Exception { Collection streams = getStreams("s1", getContext()); assertEquals(2, streams.size()); boolean c = false; @@ -248,7 +226,7 @@ public void testInheritStreams() throws Exception { } @Test - public void testInheritRetryListeners() throws Exception { + void testInheritRetryListeners() throws Exception { Collection retryListeners = getRetryListeners("s1", getContext()); assertEquals(2, retryListeners.size()); boolean g = false; @@ -266,7 +244,7 @@ else if (o instanceof DummyRetryListener) { } @Test - public void testInheritStreamsWithNoMerge() throws Exception { + void testInheritStreamsWithNoMerge() throws Exception { Collection streams = getStreams("s2", getContext()); assertEquals(1, streams.size()); boolean c = false; @@ -279,7 +257,7 @@ public void testInheritStreamsWithNoMerge() throws Exception { } @Test - public void testInheritRetryListenersWithNoMerge() throws Exception { + void testInheritRetryListenersWithNoMerge() throws Exception { Collection retryListeners = getRetryListeners("s2", getContext()); assertEquals(1, retryListeners.size()); boolean h = false; diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/DecisionJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/DecisionJobParserTests.java index bdb2cba7e0..f8b89f76b0 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/DecisionJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/DecisionJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2019 the original author or authors. + * Copyright 2006-2022 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. @@ -15,11 +15,10 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -31,16 +30,14 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.lang.Nullable; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class DecisionJobParserTests { +@SpringJUnitConfig +class DecisionJobParserTests { @Autowired @Qualifier("job") @@ -50,7 +47,7 @@ public class DecisionJobParserTests { private JobRepository jobRepository; @Test - public void testDecisionState() throws Exception { + void testDecisionState() throws Exception { assertNotNull(job); JobExecution jobExecution = jobRepository.createJobExecution(job.getName(), new JobParameters()); job.execute(jobExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/DefaultFailureJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/DefaultFailureJobParserTests.java index 42477f6dbb..b50661c214 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/DefaultFailureJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/DefaultFailureJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,28 +15,25 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dan Garrette * @since 2.0 */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class DefaultFailureJobParserTests extends AbstractJobParserTests { +@SpringJUnitConfig +class DefaultFailureJobParserTests extends AbstractJobParserTests { @Test - public void testDefaultFailure() throws Exception { + void testDefaultFailure() throws Exception { JobExecution jobExecution = createJobExecution(); job.execute(jobExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/DefaultSuccessJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/DefaultSuccessJobParserTests.java index 07f955f91a..3859bf4968 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/DefaultSuccessJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/DefaultSuccessJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,27 +15,24 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dan Garrette * @since 2.0 */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class DefaultSuccessJobParserTests extends AbstractJobParserTests { +@SpringJUnitConfig +class DefaultSuccessJobParserTests extends AbstractJobParserTests { @Test - public void testDefaultSuccess() throws Exception { + void testDefaultSuccess() throws Exception { JobExecution jobExecution = createJobExecution(); job.execute(jobExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/DefaultUnknownJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/DefaultUnknownJobParserTests.java index 18c0992296..8a6ee6d6cd 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/DefaultUnknownJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/DefaultUnknownJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,30 +15,27 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.StepExecutionListener; import org.springframework.lang.Nullable; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dan Garrette * @author Mahmoud Ben Hassine * @since 2.0 */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class DefaultUnknownJobParserTests extends AbstractJobParserTests { +@SpringJUnitConfig +class DefaultUnknownJobParserTests extends AbstractJobParserTests { @Test - public void testDefaultUnknown() throws Exception { + void testDefaultUnknown() throws Exception { JobExecution jobExecution = createJobExecution(); job.execute(jobExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/DuplicateTransitionJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/DuplicateTransitionJobParserTests.java index 064aa3b4ac..710666cebd 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/DuplicateTransitionJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/DuplicateTransitionJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,30 +15,30 @@ */ package org.springframework.batch.core.configuration.xml; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.util.ClassUtils; +import static org.junit.jupiter.api.Assertions.assertThrows; + /** * @author Dan Garrette * @author Dave Syer * @since 2.0 */ -public class DuplicateTransitionJobParserTests { +class DuplicateTransitionJobParserTests { - @Test(expected = BeanDefinitionStoreException.class) - @SuppressWarnings("resource") - public void testNextAttributeWithNestedElement() throws Exception { - new ClassPathXmlApplicationContext(ClassUtils.addResourcePathToPackagePath(getClass(), - "NextAttributeMultipleFinalJobParserTests-context.xml")); + @Test + void testNextAttributeWithNestedElement() { + assertThrows(BeanDefinitionStoreException.class, () -> new ClassPathXmlApplicationContext(ClassUtils + .addResourcePathToPackagePath(getClass(), "NextAttributeMultipleFinalJobParserTests-context.xml"))); } - @Test(expected = BeanDefinitionStoreException.class) - @SuppressWarnings("resource") - public void testDuplicateTransition() throws Exception { - new ClassPathXmlApplicationContext( - ClassUtils.addResourcePathToPackagePath(getClass(), "DuplicateTransitionJobParserTests-context.xml")); + @Test + void testDuplicateTransition() { + assertThrows(BeanDefinitionStoreException.class, () -> new ClassPathXmlApplicationContext( + ClassUtils.addResourcePathToPackagePath(getClass(), "DuplicateTransitionJobParserTests-context.xml"))); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/EndTransitionDefaultStatusJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/EndTransitionDefaultStatusJobParserTests.java index 0e8f678470..5a1ee0ca6d 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/EndTransitionDefaultStatusJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/EndTransitionDefaultStatusJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,28 +15,25 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dan Garrette * @since 2.0 */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class EndTransitionDefaultStatusJobParserTests extends AbstractJobParserTests { +@SpringJUnitConfig +class EndTransitionDefaultStatusJobParserTests extends AbstractJobParserTests { @Test - public void testEndTransitionDefaultStatus() throws Exception { + void testEndTransitionDefaultStatus() throws Exception { JobExecution jobExecution = createJobExecution(); job.execute(jobExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/EndTransitionJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/EndTransitionJobParserTests.java index d4d9190861..5cf04b2469 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/EndTransitionJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/EndTransitionJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,30 +15,27 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dan Garrette * @since 2.0 */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class EndTransitionJobParserTests extends AbstractJobParserTests { +@SpringJUnitConfig +class EndTransitionJobParserTests extends AbstractJobParserTests { @Test - public void testEndTransition() throws Exception { + void testEndTransition() throws Exception { // // First Launch @@ -64,16 +61,7 @@ public void testEndTransition() throws Exception { // Second Launch // stepNamesList.clear(); - try { - jobExecution = createJobExecution(); - fail("JobInstanceAlreadyCompleteException expected"); - } - catch (JobInstanceAlreadyCompleteException e) { - // - // Expected - // - } - + assertThrows(JobInstanceAlreadyCompleteException.class, this::createJobExecution); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/FailTransitionDefaultStatusJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/FailTransitionDefaultStatusJobParserTests.java index 3214388d10..17fabe7979 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/FailTransitionDefaultStatusJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/FailTransitionDefaultStatusJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,28 +15,25 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dan Garrette * @since 2.0 */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class FailTransitionDefaultStatusJobParserTests extends AbstractJobParserTests { +@SpringJUnitConfig +class FailTransitionDefaultStatusJobParserTests extends AbstractJobParserTests { @Test - public void testFailTransitionDefaultStatus() throws Exception { + void testFailTransitionDefaultStatus() throws Exception { JobExecution jobExecution = createJobExecution(); job.execute(jobExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/FailTransitionJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/FailTransitionJobParserTests.java index f6de0552f1..aae2910a6b 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/FailTransitionJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/FailTransitionJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,28 +15,25 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dan Garrette * @since 2.0 */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class FailTransitionJobParserTests extends AbstractJobParserTests { +@SpringJUnitConfig +class FailTransitionJobParserTests extends AbstractJobParserTests { @Test - public void testFailTransition() throws Exception { + void testFailTransition() throws Exception { // // First Launch diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/FlowJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/FlowJobParserTests.java index 01e16fbb8e..f204a28825 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/FlowJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/FlowJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,14 +15,13 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.ArrayList; import java.util.List; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -31,17 +30,15 @@ import org.springframework.batch.core.repository.JobRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * @author Mahmoud Ben Hassine * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class FlowJobParserTests { +@SpringJUnitConfig +class FlowJobParserTests { @Autowired @Qualifier("job1") @@ -63,7 +60,7 @@ public class FlowJobParserTests { private JobRepository jobRepository; @Test - public void testFlowJob() throws Exception { + void testFlowJob() throws Exception { assertNotNull(job1); JobExecution jobExecution = jobRepository.createJobExecution(job1.getName(), new JobParameters()); job1.execute(jobExecution); @@ -74,7 +71,7 @@ public void testFlowJob() throws Exception { } @Test - public void testFlowJobWithNestedTransitions() throws Exception { + void testFlowJobWithNestedTransitions() throws Exception { assertNotNull(job2); JobExecution jobExecution = jobRepository.createJobExecution(job2.getName(), new JobParameters()); job2.execute(jobExecution); @@ -86,7 +83,7 @@ public void testFlowJobWithNestedTransitions() throws Exception { } @Test - public void testFlowJobWithNoSteps() throws Exception { + void testFlowJobWithNoSteps() throws Exception { assertNotNull(job3); JobExecution jobExecution = jobRepository.createJobExecution(job3.getName(), new JobParameters()); job3.execute(jobExecution); @@ -97,7 +94,7 @@ public void testFlowJobWithNoSteps() throws Exception { } @Test - public void testFlowInSplit() throws Exception { + void testFlowInSplit() throws Exception { assertNotNull(job4); JobExecution jobExecution = jobRepository.createJobExecution(job4.getName(), new JobParameters()); job4.execute(jobExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/FlowStepParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/FlowStepParserTests.java index c86fb2c5d8..2ee4e500a0 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/FlowStepParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/FlowStepParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,14 +15,13 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.ArrayList; import java.util.List; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -34,17 +33,15 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.lang.Nullable; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * @author Mahmoud Ben Hassine * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class FlowStepParserTests { +@SpringJUnitConfig +class FlowStepParserTests { @Autowired @Qualifier("job1") @@ -66,7 +63,7 @@ public class FlowStepParserTests { private JobRepository jobRepository; @Test - public void testFlowStep() throws Exception { + void testFlowStep() throws Exception { assertNotNull(job1); JobExecution jobExecution = jobRepository.createJobExecution(job1.getName(), new JobParameters()); job1.execute(jobExecution); @@ -77,7 +74,7 @@ public void testFlowStep() throws Exception { } @Test - public void testFlowExternalStep() throws Exception { + void testFlowExternalStep() throws Exception { assertNotNull(job2); JobExecution jobExecution = jobRepository.createJobExecution(job2.getName(), new JobParameters()); job2.execute(jobExecution); @@ -88,7 +85,7 @@ public void testFlowExternalStep() throws Exception { } @Test - public void testRepeatedFlow() throws Exception { + void testRepeatedFlow() throws Exception { assertNotNull(job3); JobExecution jobExecution = jobRepository.createJobExecution(job3.getName(), new JobParameters()); job3.execute(jobExecution); @@ -100,7 +97,7 @@ public void testRepeatedFlow() throws Exception { @Test // TODO: BATCH-1745 - public void testRestartedFlow() throws Exception { + void testRestartedFlow() throws Exception { assertNotNull(job4); JobExecution jobExecution = jobRepository.createJobExecution(job4.getName(), new JobParameters()); job4.execute(jobExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/InlineItemHandlerParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/InlineItemHandlerParserTests.java index 858d06fa61..5acc06b074 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/InlineItemHandlerParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/InlineItemHandlerParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2014 the original author or authors. + * Copyright 2009-2022 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. @@ -15,13 +15,13 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Map; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.scope.context.StepSynchronizationManager; @@ -37,12 +37,12 @@ * @author Dan Garrette * @since 2.1 */ -public class InlineItemHandlerParserTests { +class InlineItemHandlerParserTests { private ConfigurableApplicationContext context; - @After - public void close() { + @AfterEach + void close() { if (context != null) { context.close(); } @@ -50,7 +50,7 @@ public void close() { } @Test - public void testInlineHandlers() throws Exception { + void testInlineHandlers() { context = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/xml/InlineItemHandlerParserTests-context.xml"); Object step = context.getBean("inlineHandlers"); @@ -67,7 +67,7 @@ public void testInlineHandlers() throws Exception { } @Test - public void testInlineAdapters() throws Exception { + void testInlineAdapters() { context = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/xml/InlineItemHandlerParserTests-context.xml"); Object step = context.getBean("inlineAdapters"); @@ -98,7 +98,7 @@ public void testInlineAdapters() throws Exception { } @Test - public void testInlineHandlersWithStepScope() throws Exception { + void testInlineHandlersWithStepScope() { context = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/xml/InlineItemHandlerWithStepScopeParserTests-context.xml"); StepSynchronizationManager.register(new StepExecution("step", new JobExecution(123L))); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobExecutionListenerMethodAttributeParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobExecutionListenerMethodAttributeParserTests.java index 06814e530b..2814f7bcb1 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobExecutionListenerMethodAttributeParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobExecutionListenerMethodAttributeParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2008 the original author or authors. + * Copyright 2002-2022 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. @@ -15,24 +15,21 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParametersBuilder; import org.springframework.batch.core.repository.JobRepository; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Lucas Ward * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) +@SpringJUnitConfig public class JobExecutionListenerMethodAttributeParserTests { public static boolean beforeCalled = false; @@ -46,7 +43,7 @@ public class JobExecutionListenerMethodAttributeParserTests { JobRepository jobRepository; @Test - public void testListeners() throws Exception { + void testListeners() throws Exception { JobExecution jobExecution = jobRepository.createJobExecution("testJob", new JobParametersBuilder().addLong("now", System.currentTimeMillis()).toJobParameters()); job.execute(jobExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobExecutionListenerParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobExecutionListenerParserTests.java index f8ee428e2f..8f9d3a195d 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobExecutionListenerParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobExecutionListenerParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2008 the original author or authors. + * Copyright 2002-2022 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. @@ -15,10 +15,9 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParametersBuilder; @@ -26,15 +25,13 @@ import org.springframework.batch.core.annotation.BeforeJob; import org.springframework.batch.core.repository.JobRepository; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Lucas Ward * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) +@SpringJUnitConfig public class JobExecutionListenerParserTests { public static boolean beforeCalled = false; @@ -48,7 +45,7 @@ public class JobExecutionListenerParserTests { JobRepository jobRepository; @Test - public void testListeners() throws Exception { + void testListeners() throws Exception { JobExecution jobExecution = jobRepository.createJobExecution("testJob", new JobParametersBuilder().addLong("now", System.currentTimeMillis()).toJobParameters()); job.execute(jobExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobParserExceptionTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobParserExceptionTests.java index 14b0cde801..49b5bec12d 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobParserExceptionTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobParserExceptionTests.java @@ -15,71 +15,52 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.BeanCreationException; -import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.parsing.BeanDefinitionParsingException; import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.core.NestedRuntimeException; -public class JobParserExceptionTests { +class JobParserExceptionTests { @Test - public void testUnreachableStep() { - try { - new ClassPathXmlApplicationContext( - "org/springframework/batch/core/configuration/xml/JobParserUnreachableStepTests-context.xml"); - fail("Error expected"); - } - catch (BeanDefinitionParsingException e) { - assertTrue(e.getMessage().contains("The element [s2] is unreachable")); - } + void testUnreachableStep() { + Exception exception = assertThrows(BeanDefinitionParsingException.class, + () -> new ClassPathXmlApplicationContext( + "org/springframework/batch/core/configuration/xml/JobParserUnreachableStepTests-context.xml")); + assertTrue(exception.getMessage().contains("The element [s2] is unreachable")); } @Test - public void testUnreachableStepInFlow() { - try { - new ClassPathXmlApplicationContext( - "org/springframework/batch/core/configuration/xml/JobParserUnreachableStepInFlowTests-context.xml"); - fail("Error expected"); - } - catch (BeanDefinitionParsingException e) { - assertTrue(e.getMessage().contains("The element [s4] is unreachable")); - } + void testUnreachableStepInFlow() { + Exception exception = assertThrows(BeanDefinitionParsingException.class, + () -> new ClassPathXmlApplicationContext( + "org/springframework/batch/core/configuration/xml/JobParserUnreachableStepInFlowTests-context.xml")); + assertTrue(exception.getMessage().contains("The element [s4] is unreachable")); } @Test - public void testNextOutOfScope() { - try { - new ClassPathXmlApplicationContext( - "org/springframework/batch/core/configuration/xml/JobParserNextOutOfScopeTests-context.xml"); - fail("Error expected"); - } - catch (BeanCreationException e) { - String message = e.getRootCause().getMessage(); - assertTrue("Wrong message: " + message, message - .matches(".*Missing state for \\[StateTransition: \\[state=.*s2, pattern=\\*, next=.*s3\\]\\]")); - } + void testNextOutOfScope() { + NestedRuntimeException exception = assertThrows(BeanCreationException.class, + () -> new ClassPathXmlApplicationContext( + "org/springframework/batch/core/configuration/xml/JobParserNextOutOfScopeTests-context.xml")); + String message = exception.getRootCause().getMessage(); + assertTrue( + message.matches(".*Missing state for \\[StateTransition: \\[state=.*s2, pattern=\\*, next=.*s3\\]\\]"), + "Wrong message: " + message); } @Test - public void testWrongSchemaInRoot() { - try { - new ClassPathXmlApplicationContext( - "org/springframework/batch/core/configuration/xml/JobParserWrongSchemaInRootTests-context.xml"); - fail("Error expected"); - } - catch (BeanDefinitionParsingException e) { - String message = e.getMessage(); - assertTrue("Wrong message: " + message, - message.startsWith("Configuration problem: You are using a version of the spring-batch XSD")); - } - catch (BeanDefinitionStoreException e) { - // Probably the internet is not available and the schema validation failed. - fail("Wrong exception when schema didn't match: " + e.getMessage()); - } + void testWrongSchemaInRoot() { + Exception exception = assertThrows(BeanDefinitionParsingException.class, + () -> new ClassPathXmlApplicationContext( + "org/springframework/batch/core/configuration/xml/JobParserWrongSchemaInRootTests-context.xml")); + String message = exception.getMessage(); + assertTrue(message.startsWith("Configuration problem: You are using a version of the spring-batch XSD"), + "Wrong message: " + message); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobParserJobFactoryBeanTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobParserJobFactoryBeanTests.java index ae91f2e9c7..f3cb9eb1d7 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobParserJobFactoryBeanTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobParserJobFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2009 the original author or authors. + * Copyright 2009-2022 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. @@ -15,17 +15,17 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class JobParserJobFactoryBeanTests { +class JobParserJobFactoryBeanTests { - private JobParserJobFactoryBean factory = new JobParserJobFactoryBean("jobFactory"); + private final JobParserJobFactoryBean factory = new JobParserJobFactoryBean("jobFactory"); @Test - public void testSingleton() throws Exception { - assertTrue("Expected singleton", factory.isSingleton()); + void testSingleton() { + assertTrue(factory.isSingleton(), "Expected singleton"); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobParserParentAttributeTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobParserParentAttributeTests.java index 93304d4311..d04c078171 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobParserParentAttributeTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobParserParentAttributeTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,14 +15,13 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.List; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.aop.framework.Advised; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecutionListener; @@ -31,8 +30,7 @@ import org.springframework.batch.core.repository.support.SimpleJobRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.util.ReflectionTestUtils; /** @@ -41,9 +39,8 @@ * @author Mahmoud Ben Hassine * @since 2.0 */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class JobParserParentAttributeTests { +@SpringJUnitConfig +class JobParserParentAttributeTests { @Autowired @Qualifier("listenerClearingJob") @@ -78,7 +75,7 @@ public class JobParserParentAttributeTests { private Job job1; @Test - public void testInheritListeners() throws Exception { + void testInheritListeners() throws Exception { List job1Listeners = getListeners(job1); assertEquals(2, job1Listeners.size()); boolean a = false; @@ -96,7 +93,7 @@ else if (l instanceof DummyJobExecutionListener) { } @Test - public void testInheritListeners_NoMerge() throws Exception { + void testInheritListeners_NoMerge() throws Exception { List job2Listeners = getListeners(job2); assertEquals(1, job2Listeners.size()); boolean c = false; @@ -109,7 +106,7 @@ public void testInheritListeners_NoMerge() throws Exception { } @Test - public void testStandaloneListener() throws Exception { + void testStandaloneListener() throws Exception { List jobListeners = getListeners(job3); assertEquals(2, jobListeners.size()); boolean a = false; @@ -127,7 +124,7 @@ else if (l instanceof DummyJobExecutionListener) { } @Test - public void testJobRepositoryDefaults() throws Exception { + void testJobRepositoryDefaults() throws Exception { assertTrue(getJobRepository(defaultRepoJob) instanceof SimpleJobRepository); assertTrue(getJobRepository(specifiedRepoJob) instanceof DummyJobRepository); assertTrue(getJobRepository(inheritSpecifiedRepoJob) instanceof DummyJobRepository); @@ -135,7 +132,7 @@ public void testJobRepositoryDefaults() throws Exception { } @Test - public void testListenerClearingJob() throws Exception { + void testListenerClearingJob() throws Exception { assertEquals(0, getListeners(listenerClearingJob).size()); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobParserValidatorTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobParserValidatorTests.java index ed1e6e37df..54e3b79887 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobParserValidatorTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobParserValidatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,14 +15,14 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Collection; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.JobParametersInvalidException; @@ -31,17 +31,15 @@ import org.springframework.batch.core.job.DefaultJobParametersValidator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.util.ReflectionTestUtils; /** * @author Dave Syer * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class JobParserValidatorTests { +@SpringJUnitConfig +class JobParserValidatorTests { @Autowired @Qualifier("job1") @@ -55,35 +53,35 @@ public class JobParserValidatorTests { @Qualifier("job3") private Job job3; - @Test(expected = JobParametersInvalidException.class) - public void testValidatorAttribute() throws Exception { + @Test + void testValidatorAttribute() { assertNotNull(job1); JobParametersValidator validator = (JobParametersValidator) ReflectionTestUtils.getField(job1, "jobParametersValidator"); assertNotNull(validator); - validator.validate(new JobParameters()); + assertThrows(JobParametersInvalidException.class, () -> validator.validate(new JobParameters())); } - @Test(expected = JobParametersInvalidException.class) - public void testValidatorRef() throws Exception { + @Test + void testValidatorRef() { assertNotNull(job2); JobParametersValidator validator = (JobParametersValidator) ReflectionTestUtils.getField(job2, "jobParametersValidator"); assertNotNull(validator); - validator.validate(new JobParameters()); + assertThrows(JobParametersInvalidException.class, () -> validator.validate(new JobParameters())); } - @Test(expected = JobParametersInvalidException.class) - public void testValidatorBean() throws Exception { + @Test + void testValidatorBean() { assertNotNull(job3); JobParametersValidator validator = (JobParametersValidator) ReflectionTestUtils.getField(job3, "jobParametersValidator"); assertNotNull(validator); - validator.validate(new JobParameters()); + assertThrows(JobParametersInvalidException.class, () -> validator.validate(new JobParameters())); } @Test - public void testParametersValidator() { + void testParametersValidator() { assertTrue(job1 instanceof AbstractJob); Object validator = ReflectionTestUtils.getField(job1, "jobParametersValidator"); assertTrue(validator instanceof DefaultJobParametersValidator); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobRegistryJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobRegistryJobParserTests.java index 1512152145..9c6f4cf623 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobRegistryJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobRegistryJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2013 the original author or authors. + * Copyright 2006-2022 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. @@ -15,25 +15,22 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.Job; import org.springframework.batch.core.configuration.ListableJobLocator; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) +@SpringJUnitConfig public class JobRegistryJobParserTests implements ApplicationContextAware { @Autowired @@ -47,7 +44,7 @@ public void setApplicationContext(ApplicationContext applicationContext) throws } @Test - public void testOneStep() throws Exception { + void testOneStep() { assertEquals(2, applicationContext.getBeanNamesForType(Job.class).length); assertEquals(2, jobRegistry.getJobNames().size()); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobRepositoryDefaultParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobRepositoryDefaultParserTests.java index 6a945b65d3..26871439af 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobRepositoryDefaultParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobRepositoryDefaultParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,30 +15,27 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.repository.JobRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class JobRepositoryDefaultParserTests { +@SpringJUnitConfig +class JobRepositoryDefaultParserTests { @Autowired @Qualifier("jobRepository") private JobRepository jobRepository; @Test - public void testOneStep() throws Exception { + void testOneStep() { assertNotNull(jobRepository); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobRepositoryParserReferenceTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobRepositoryParserReferenceTests.java index cd95693ee8..d0a6d753b9 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobRepositoryParserReferenceTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobRepositoryParserReferenceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,30 +15,27 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.repository.JobRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class JobRepositoryParserReferenceTests { +@SpringJUnitConfig +class JobRepositoryParserReferenceTests { @Autowired @Qualifier("jobRepo1") private JobRepository jobRepository; @Test - public void testOneStep() throws Exception { + void testOneStep() { assertNotNull(jobRepository); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobRepositoryParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobRepositoryParserTests.java index f0b6353676..dade661504 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobRepositoryParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobRepositoryParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,30 +15,27 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.repository.JobRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Thomas Risberg * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class JobRepositoryParserTests { +@SpringJUnitConfig +class JobRepositoryParserTests { @Autowired @Qualifier("jobRepo1") private JobRepository jobRepository; @Test - public void testOneStep() throws Exception { + void testOneStep() { assertNotNull(jobRepository); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobStepParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobStepParserTests.java index bdb8dcc51b..dff6c73368 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobStepParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/JobStepParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,14 +15,13 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.ArrayList; import java.util.List; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -31,17 +30,15 @@ import org.springframework.batch.core.repository.JobRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * @author Mahmoud Ben Hassine * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class JobStepParserTests { +@SpringJUnitConfig +class JobStepParserTests { @Autowired @Qualifier("job1") @@ -55,7 +52,7 @@ public class JobStepParserTests { private JobRepository jobRepository; @Test - public void testFlowStep() throws Exception { + void testFlowStep() throws Exception { assertNotNull(job1); JobExecution jobExecution = jobRepository.createJobExecution(job1.getName(), new JobParameters()); job1.execute(jobExecution); @@ -66,7 +63,7 @@ public void testFlowStep() throws Exception { } @Test - public void testFlowExternalStep() throws Exception { + void testFlowExternalStep() throws Exception { assertNotNull(job2); JobExecution jobExecution = jobRepository.createJobExecution(job2.getName(), new JobParameters()); job2.execute(jobExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/NamespacePrefixedJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/NamespacePrefixedJobParserTests.java index 0bfe06b9e8..f097fb88ce 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/NamespacePrefixedJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/NamespacePrefixedJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,11 +15,10 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -27,17 +26,15 @@ import org.springframework.batch.core.repository.JobRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * @author Mahmoud Ben Hassine * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class NamespacePrefixedJobParserTests { +@SpringJUnitConfig +class NamespacePrefixedJobParserTests { @Autowired @Qualifier("job1") @@ -47,7 +44,7 @@ public class NamespacePrefixedJobParserTests { private JobRepository jobRepository; @Test - public void testNoopJob() throws Exception { + void testNoopJob() throws Exception { assertNotNull(job1); JobExecution jobExecution = jobRepository.createJobExecution(job1.getName(), new JobParameters()); job1.execute(jobExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/NextAttributeJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/NextAttributeJobParserTests.java index 2d679e8ed9..d510ca3f4c 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/NextAttributeJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/NextAttributeJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,28 +15,25 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dan Garrette * @since 2.0 */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class NextAttributeJobParserTests extends AbstractJobParserTests { +@SpringJUnitConfig +class NextAttributeJobParserTests extends AbstractJobParserTests { @Test - public void testNextAttributeFailedDefault() throws Exception { + void testNextAttributeFailedDefault() throws Exception { // // Launch 1 diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/NextAttributeUnknownJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/NextAttributeUnknownJobParserTests.java index 2d496260e6..3720442df6 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/NextAttributeUnknownJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/NextAttributeUnknownJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,30 +15,27 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.StepExecutionListener; import org.springframework.lang.Nullable; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * @author Mahmoud Ben Hassine * @since 2.1.9 */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class NextAttributeUnknownJobParserTests extends AbstractJobParserTests { +@SpringJUnitConfig +class NextAttributeUnknownJobParserTests extends AbstractJobParserTests { @Test - public void testDefaultUnknown() throws Exception { + void testDefaultUnknown() throws Exception { JobExecution jobExecution = createJobExecution(); job.execute(jobExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/OneStepJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/OneStepJobParserTests.java index 0d38be1afd..f1a470d2fc 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/OneStepJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/OneStepJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,11 +15,10 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -27,16 +26,14 @@ import org.springframework.batch.core.repository.JobRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class OneStepJobParserTests { +@SpringJUnitConfig +class OneStepJobParserTests { @Autowired @Qualifier("job") @@ -46,7 +43,7 @@ public class OneStepJobParserTests { private JobRepository jobRepository; @Test - public void testOneStep() throws Exception { + void testOneStep() throws Exception { assertNotNull(job); JobExecution jobExecution = jobRepository.createJobExecution(job.getName(), new JobParameters()); job.execute(jobExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/ParentStepFactoryBeanParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/ParentStepFactoryBeanParserTests.java index 32ab2c9f67..9913385164 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/ParentStepFactoryBeanParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/ParentStepFactoryBeanParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,10 +15,10 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.Step; import org.springframework.batch.core.step.item.FaultTolerantChunkProcessor; import org.springframework.context.ConfigurableApplicationContext; @@ -29,68 +29,63 @@ * @author Dave Syer * */ -public class ParentStepFactoryBeanParserTests { +class ParentStepFactoryBeanParserTests { @Test - @SuppressWarnings("resource") - public void testSimpleAttributes() throws Exception { + void testSimpleAttributes() { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/xml/ParentStepFactoryBeanParserTests-context.xml"); Object step = context.getBean("s1", Step.class); - assertNotNull("Step not parsed", step); + assertNotNull(step, "Step not parsed"); Object tasklet = ReflectionTestUtils.getField(step, "tasklet"); Object chunkProcessor = ReflectionTestUtils.getField(tasklet, "chunkProcessor"); - assertTrue("Wrong processor type", chunkProcessor instanceof FaultTolerantChunkProcessor); + assertTrue(chunkProcessor instanceof FaultTolerantChunkProcessor, "Wrong processor type"); } @Test - @SuppressWarnings("resource") - public void testSkippableAttributes() throws Exception { + void testSkippableAttributes() { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/xml/ParentSkippableStepFactoryBeanParserTests-context.xml"); Object step = context.getBean("s1", Step.class); - assertNotNull("Step not parsed", step); + assertNotNull(step, "Step not parsed"); Object tasklet = ReflectionTestUtils.getField(step, "tasklet"); Object chunkProcessor = ReflectionTestUtils.getField(tasklet, "chunkProcessor"); - assertTrue("Wrong processor type", chunkProcessor instanceof FaultTolerantChunkProcessor); + assertTrue(chunkProcessor instanceof FaultTolerantChunkProcessor, "Wrong processor type"); } @Test - @SuppressWarnings("resource") - public void testRetryableAttributes() throws Exception { + void testRetryableAttributes() { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/xml/ParentRetryableStepFactoryBeanParserTests-context.xml"); Object step = context.getBean("s1", Step.class); - assertNotNull("Step not parsed", step); + assertNotNull(step, "Step not parsed"); Object tasklet = ReflectionTestUtils.getField(step, "tasklet"); Object chunkProcessor = ReflectionTestUtils.getField(tasklet, "chunkProcessor"); - assertTrue("Wrong processor type", chunkProcessor instanceof FaultTolerantChunkProcessor); + assertTrue(chunkProcessor instanceof FaultTolerantChunkProcessor, "Wrong processor type"); } // BATCH-1396 @Test - @SuppressWarnings("resource") - public void testRetryableLateBindingAttributes() throws Exception { + void testRetryableLateBindingAttributes() { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/xml/ParentRetryableLateBindingStepFactoryBeanParserTests-context.xml"); Object step = context.getBean("s1", Step.class); - assertNotNull("Step not parsed", step); + assertNotNull(step, "Step not parsed"); Object tasklet = ReflectionTestUtils.getField(step, "tasklet"); Object chunkProcessor = ReflectionTestUtils.getField(tasklet, "chunkProcessor"); - assertTrue("Wrong processor type", chunkProcessor instanceof FaultTolerantChunkProcessor); + assertTrue(chunkProcessor instanceof FaultTolerantChunkProcessor, "Wrong processor type"); } // BATCH-1396 @Test - @SuppressWarnings("resource") - public void testSkippableLateBindingAttributes() throws Exception { + void testSkippableLateBindingAttributes() { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/xml/ParentSkippableLateBindingStepFactoryBeanParserTests-context.xml"); Object step = context.getBean("s1", Step.class); - assertNotNull("Step not parsed", step); + assertNotNull(step, "Step not parsed"); Object tasklet = ReflectionTestUtils.getField(step, "tasklet"); Object chunkProcessor = ReflectionTestUtils.getField(tasklet, "chunkProcessor"); - assertTrue("Wrong processor type", chunkProcessor instanceof FaultTolerantChunkProcessor); + assertTrue(chunkProcessor instanceof FaultTolerantChunkProcessor, "Wrong processor type"); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/PartitionStepParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/PartitionStepParserTests.java index fa0ef1318e..3790b31339 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/PartitionStepParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/PartitionStepParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,8 +15,8 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.lang.reflect.Field; import java.util.ArrayList; @@ -25,9 +25,8 @@ import java.util.Collections; import java.util.List; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -45,8 +44,7 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.util.ReflectionUtils; /** @@ -54,8 +52,7 @@ * @author Josh Long * @author Mahmoud Ben Hassine */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) +@SpringJUnitConfig public class PartitionStepParserTests implements ApplicationContextAware { @Autowired @@ -94,8 +91,8 @@ public void setApplicationContext(ApplicationContext applicationContext) throws this.applicationContext = applicationContext; } - @Before - public void setUp() { + @BeforeEach + void setUp() { nameStoringTasklet.setStepNamesList(savedStepNames); } @@ -110,7 +107,7 @@ private T accessPrivateField(Object o, String fieldName) { } @Test - public void testDefaultHandlerStep() throws Exception { + void testDefaultHandlerStep() throws Exception { assertNotNull(job1); JobExecution jobExecution = jobRepository.createJobExecution(job1.getName(), new JobParameters()); job1.execute(jobExecution); @@ -124,7 +121,7 @@ public void testDefaultHandlerStep() throws Exception { } @Test - public void testHandlerRefStep() throws Exception { + void testHandlerRefStep() throws Exception { assertNotNull(job2); JobExecution jobExecution = jobRepository.createJobExecution(job2.getName(), new JobParameters()); job2.execute(jobExecution); @@ -142,8 +139,8 @@ public void testHandlerRefStep() throws Exception { * handler has a reference to the inline step definition */ @Test - public void testNestedPartitionStepStepReference() throws Throwable { - assertNotNull("the reference to the job3 configured in the XML file must not be null", job3); + void testNestedPartitionStepStepReference() throws Throwable { + assertNotNull(job3, "the reference to the job3 configured in the XML file must not be null"); JobExecution jobExecution = jobRepository.createJobExecution(job3.getName(), new JobParameters()); job3.execute(jobExecution); @@ -159,8 +156,8 @@ public void testNestedPartitionStepStepReference() throws Throwable { "partitionHandler"); TaskletStep taskletStep = accessPrivateField(taskExecutorPartitionHandler, "step"); - assertNotNull("the taskletStep wasn't configured with a step. " - + "We're trusting that the factory ensured " + "a reference was given.", taskletStep); + assertNotNull(taskletStep, "the taskletStep wasn't configured with a step. " + + "We're trusting that the factory ensured " + "a reference was given."); } } assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus()); @@ -181,8 +178,8 @@ public void testNestedPartitionStepStepReference() throws Throwable { * handler has a reference to the inline step definition */ @Test - public void testNestedPartitionStep() throws Throwable { - assertNotNull("the reference to the job4 configured in the XML file must not be null", job4); + void testNestedPartitionStep() throws Throwable { + assertNotNull(job4, "the reference to the job4 configured in the XML file must not be null"); JobExecution jobExecution = jobRepository.createJobExecution(job4.getName(), new JobParameters()); job4.execute(jobExecution); @@ -199,8 +196,8 @@ public void testNestedPartitionStep() throws Throwable { "partitionHandler"); TaskletStep taskletStep = accessPrivateField(taskExecutorPartitionHandler, "step"); - assertNotNull("the taskletStep wasn't configured with a step. " - + "We're trusting that the factory ensured " + "a reference was given.", taskletStep); + assertNotNull(taskletStep, "the taskletStep wasn't configured with a step. " + + "We're trusting that the factory ensured " + "a reference was given."); } } assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus()); @@ -214,7 +211,7 @@ public void testNestedPartitionStep() throws Throwable { } @Test - public void testCustomHandlerRefStep() throws Exception { + void testCustomHandlerRefStep() throws Exception { assertNotNull(job5); JobExecution jobExecution = jobRepository.createJobExecution(job5.getName(), new JobParameters()); job5.execute(jobExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/PartitionStepWithFlowParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/PartitionStepWithFlowParserTests.java index 88b2eaffcf..a2391387a4 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/PartitionStepWithFlowParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/PartitionStepWithFlowParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,16 +15,15 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -36,17 +35,15 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.lang.Nullable; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * @author Josh Long * @author Mahmoud Ben Hassine */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class PartitionStepWithFlowParserTests { +@SpringJUnitConfig +class PartitionStepWithFlowParserTests { @Autowired @Qualifier("job1") @@ -59,15 +56,15 @@ public class PartitionStepWithFlowParserTests { @Autowired private JobRepository jobRepository; - private List savedStepNames = new ArrayList<>(); + private final List savedStepNames = new ArrayList<>(); - @Before - public void setUp() { + @BeforeEach + void setUp() { nameStoringTasklet.setStepNamesList(savedStepNames); } @Test - public void testRepeatedFlowStep() throws Exception { + void testRepeatedFlowStep() throws Exception { assertNotNull(job1); JobExecution jobExecution = jobRepository.createJobExecution(job1.getName(), new JobParametersBuilder().addLong("gridSize", 1L).toJobParameters()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/PartitionStepWithLateBindingParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/PartitionStepWithLateBindingParserTests.java index c964bae2c2..ee6c0fb2c5 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/PartitionStepWithLateBindingParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/PartitionStepWithLateBindingParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,16 +15,15 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -33,17 +32,15 @@ import org.springframework.batch.core.repository.JobRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * @author Josh Long * @author Mahmoud Ben Hassine */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class PartitionStepWithLateBindingParserTests { +@SpringJUnitConfig +class PartitionStepWithLateBindingParserTests { @Autowired @Qualifier("job1") @@ -56,15 +53,15 @@ public class PartitionStepWithLateBindingParserTests { @Autowired private JobRepository jobRepository; - private List savedStepNames = new ArrayList<>(); + private final List savedStepNames = new ArrayList<>(); - @Before - public void setUp() { + @BeforeEach + void setUp() { nameStoringTasklet.setStepNamesList(savedStepNames); } @Test - public void testExplicitHandlerStep() throws Exception { + void testExplicitHandlerStep() throws Exception { assertNotNull(job1); JobExecution jobExecution = jobRepository.createJobExecution(job1.getName(), new JobParametersBuilder().addLong("gridSize", 1L).toJobParameters()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/PartitionStepWithNonDefaultTransactionManagerParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/PartitionStepWithNonDefaultTransactionManagerParserTests.java index 454d256bf3..9508171ecd 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/PartitionStepWithNonDefaultTransactionManagerParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/PartitionStepWithNonDefaultTransactionManagerParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,28 +15,25 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.repository.JobRepository; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * @author Mahmoud Ben Hassine * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class PartitionStepWithNonDefaultTransactionManagerParserTests { +@SpringJUnitConfig +class PartitionStepWithNonDefaultTransactionManagerParserTests { @Autowired private Job job; @@ -45,7 +42,7 @@ public class PartitionStepWithNonDefaultTransactionManagerParserTests { private JobRepository jobRepository; @Test - public void testDefaultHandlerStep() throws Exception { + void testDefaultHandlerStep() throws Exception { assertNotNull(job); JobExecution jobExecution = jobRepository.createJobExecution(job.getName(), new JobParameters()); job.execute(jobExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/RepositoryJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/RepositoryJobParserTests.java index f4526f906e..0a8cad596e 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/RepositoryJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/RepositoryJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,11 +15,10 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -27,16 +26,14 @@ import org.springframework.batch.core.repository.JobRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class RepositoryJobParserTests { +@SpringJUnitConfig +class RepositoryJobParserTests { @Autowired @Qualifier("job") @@ -46,7 +43,7 @@ public class RepositoryJobParserTests { private JobRepository jobRepository; @Test - public void testTaskletStepWithBadListener() throws Exception { + void testTaskletStepWithBadListener() throws Exception { assertNotNull(job); JobExecution jobExecution = jobRepository.createJobExecution(job.getName(), new JobParameters()); job.execute(jobExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/SplitDifferentResultsFailFirstJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/SplitDifferentResultsFailFirstJobParserTests.java index c04ebb49be..79e04e3a94 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/SplitDifferentResultsFailFirstJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/SplitDifferentResultsFailFirstJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,32 +15,29 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dan Garrette * @since 2.0 */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class SplitDifferentResultsFailFirstJobParserTests extends AbstractJobParserTests { +@SpringJUnitConfig +class SplitDifferentResultsFailFirstJobParserTests extends AbstractJobParserTests { @Test - public void testSplitDifferentResultsFailFirst() throws Exception { + void testSplitDifferentResultsFailFirst() throws Exception { JobExecution jobExecution = createJobExecution(); job.execute(jobExecution); assertEquals(2, stepNamesList.size()); - assertEquals("Wrong step names: " + stepNamesList, "[fail, s1]", stepNamesList.toString()); + assertEquals("[fail, s1]", stepNamesList.toString(), "Wrong step names: " + stepNamesList); assertEquals(BatchStatus.FAILED, jobExecution.getStatus()); assertEquals(ExitStatus.FAILED, jobExecution.getExitStatus()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/SplitDifferentResultsFailSecondJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/SplitDifferentResultsFailSecondJobParserTests.java index c66a869495..97ece09a08 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/SplitDifferentResultsFailSecondJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/SplitDifferentResultsFailSecondJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,34 +15,31 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dan Garrette * @since 2.0 */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class SplitDifferentResultsFailSecondJobParserTests extends AbstractJobParserTests { +@SpringJUnitConfig +class SplitDifferentResultsFailSecondJobParserTests extends AbstractJobParserTests { @Test - public void testSplitDifferentResultsFailSecond() throws Exception { + void testSplitDifferentResultsFailSecond() throws Exception { JobExecution jobExecution = createJobExecution(); job.execute(jobExecution); - assertEquals("Wrong step names: " + stepNamesList, 3, stepNamesList.size()); - assertTrue("Wrong step names: " + stepNamesList, stepNamesList.contains("s1")); - assertTrue("Wrong step names: " + stepNamesList, stepNamesList.contains("fail")); + assertEquals(3, stepNamesList.size(), "Wrong step names: " + stepNamesList); + assertTrue(stepNamesList.contains("s1"), "Wrong step names: " + stepNamesList); + assertTrue(stepNamesList.contains("fail"), "Wrong step names: " + stepNamesList); assertTrue(stepNamesList.contains("s3")); assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/SplitInterruptedJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/SplitInterruptedJobParserTests.java index 6ba4adea61..fbf838acf2 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/SplitInterruptedJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/SplitInterruptedJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2013 the original author or authors. + * Copyright 2006-2022 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. @@ -15,28 +15,25 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * @since 2.0 */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class SplitInterruptedJobParserTests extends AbstractJobParserTests { +@SpringJUnitConfig +class SplitInterruptedJobParserTests extends AbstractJobParserTests { @Test - public void testSplitInterrupted() throws Exception { + void testSplitInterrupted() throws Exception { final JobExecution jobExecution = createJobExecution(); new Thread(new Runnable() { @@ -53,12 +50,12 @@ public void run() { while (jobExecution.getStatus() == BatchStatus.STOPPING && count++ < 10) { Thread.sleep(200L); } - assertTrue("Timed out waiting for job to stop: " + jobExecution, count < 10); + assertTrue(count < 10, "Timed out waiting for job to stop: " + jobExecution); assertEquals(BatchStatus.STOPPED, jobExecution.getStatus()); assertEquals(ExitStatus.STOPPED.getExitCode(), jobExecution.getExitStatus().getExitCode()); - assertTrue("Wrong step names: " + stepNamesList, stepNamesList.contains("stop")); + assertTrue(stepNamesList.contains("stop"), "Wrong step names: " + stepNamesList); StepExecution stepExecution = getStepExecution(jobExecution, "stop"); assertEquals(BatchStatus.STOPPED, stepExecution.getStatus()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/SplitJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/SplitJobParserTests.java index 83a0298185..85240859b7 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/SplitJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/SplitJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,14 +15,13 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.ArrayList; import java.util.Collections; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -31,16 +30,14 @@ import org.springframework.batch.core.step.StepLocator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class SplitJobParserTests { +@SpringJUnitConfig +class SplitJobParserTests { @Autowired @Qualifier("job") @@ -50,7 +47,7 @@ public class SplitJobParserTests { private JobRepository jobRepository; @Test - public void testSplitJob() throws Exception { + void testSplitJob() throws Exception { assertNotNull(job); JobExecution jobExecution = jobRepository.createJobExecution(job.getName(), new JobParameters()); job.execute(jobExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/SplitNestedJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/SplitNestedJobParserTests.java index d27603e377..ed59f4cb29 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/SplitNestedJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/SplitNestedJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2011 the original author or authors. + * Copyright 2006-2022 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. @@ -15,11 +15,10 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -27,16 +26,14 @@ import org.springframework.batch.core.repository.JobRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Josh Long - * + * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class SplitNestedJobParserTests { +@SpringJUnitConfig +class SplitNestedJobParserTests { @Autowired @Qualifier("job") @@ -46,7 +43,7 @@ public class SplitNestedJobParserTests { private JobRepository jobRepository; @Test - public void testSplitJob() throws Exception { + void testSplitJob() throws Exception { assertNotNull(job); JobExecution jobExecution = jobRepository.createJobExecution(job.getName(), new JobParameters()); job.execute(jobExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepListenerInStepParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepListenerInStepParserTests.java index d696532940..1505c491b1 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepListenerInStepParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepListenerInStepParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2022 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. @@ -15,14 +15,13 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.List; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.aop.framework.Advised; import org.springframework.batch.core.Step; import org.springframework.batch.core.StepListener; @@ -30,8 +29,7 @@ import org.springframework.batch.core.step.tasklet.TaskletStep; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.util.ReflectionTestUtils; /** @@ -39,15 +37,14 @@ * @author Mahmoud Ben Hassine * @since 2.0 */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class StepListenerInStepParserTests { +@SpringJUnitConfig +class StepListenerInStepParserTests { @Autowired private BeanFactory beanFactory; @Test - public void testListenersAtStepLevel() throws Exception { + void testListenersAtStepLevel() throws Exception { Step step = (Step) beanFactory.getBean("s1"); List list = getListeners(step); assertEquals(1, list.size()); @@ -56,7 +53,7 @@ public void testListenersAtStepLevel() throws Exception { @Test // TODO: BATCH-1689 (expected=BeanCreationException.class) - public void testListenersAtStepLevelWrongType() throws Exception { + void testListenersAtStepLevelWrongType() throws Exception { Step step = (Step) beanFactory.getBean("s2"); List list = getListeners(step); assertEquals(1, list.size()); @@ -64,7 +61,7 @@ public void testListenersAtStepLevelWrongType() throws Exception { } @Test - public void testListenersAtTaskletAndStepLevels() throws Exception { + void testListenersAtTaskletAndStepLevels() throws Exception { Step step = (Step) beanFactory.getBean("s3"); List list = getListeners(step); assertEquals(2, list.size()); @@ -73,7 +70,7 @@ public void testListenersAtTaskletAndStepLevels() throws Exception { } @Test - public void testListenersAtChunkAndStepLevels() throws Exception { + void testListenersAtChunkAndStepLevels() throws Exception { Step step = (Step) beanFactory.getBean("s4"); List list = getListeners(step); assertEquals(2, list.size()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepListenerMethodAttributeParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepListenerMethodAttributeParserTests.java index d830259d88..0c82748b05 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepListenerMethodAttributeParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepListenerMethodAttributeParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2008 the original author or authors. + * Copyright 2002-2022 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. @@ -15,38 +15,35 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.List; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.aop.framework.Advised; import org.springframework.batch.core.Step; import org.springframework.batch.core.StepExecutionListener; import org.springframework.batch.core.step.tasklet.TaskletStep; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.util.ReflectionTestUtils; /** * @author Dan Garrette * @since 2.0 */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class StepListenerMethodAttributeParserTests { +@SpringJUnitConfig +class StepListenerMethodAttributeParserTests { @Autowired @Qualifier("s1") private Step step1; @Test - public void testInheritListeners() throws Exception { + void testInheritListeners() throws Exception { List list = getListeners(step1); assertEquals(2, list.size()); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepListenerParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepListenerParserTests.java index c2975350c8..fbb4cf065d 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepListenerParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepListenerParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2022 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. @@ -15,14 +15,13 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.List; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.aop.framework.Advised; import org.springframework.batch.core.Step; import org.springframework.batch.core.StepListener; @@ -31,8 +30,7 @@ import org.springframework.batch.core.step.tasklet.TaskletStep; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.util.ReflectionTestUtils; /** @@ -40,9 +38,8 @@ * @author Mahmoud Ben Hassine * @since 2.0 */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class StepListenerParserTests { +@SpringJUnitConfig +class StepListenerParserTests { @Autowired @Qualifier("s1") @@ -57,7 +54,7 @@ public class StepListenerParserTests { private Step step3; @Test - public void testInheritListeners() throws Exception { + void testInheritListeners() throws Exception { List list = getListeners(step1); @@ -82,7 +79,7 @@ else if (listener instanceof CompositeStepExecutionListener) { } @Test - public void testInheritListenersNoMerge() throws Exception { + void testInheritListenersNoMerge() throws Exception { List list = getListeners(step2); @@ -102,7 +99,7 @@ else if (listener instanceof DummyStepExecutionListener) { } @Test - public void testInheritListenersNoMergeFaultTolerant() throws Exception { + void testInheritListenersNoMergeFaultTolerant() throws Exception { List list = getListeners(step3); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepNameTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepNameTests.java index 41d41ad28e..6932f31c12 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepNameTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepNameTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2008 the original author or authors. + * Copyright 2006-2022 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. @@ -15,19 +15,18 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import java.io.IOException; import java.util.ArrayList; import java.util.Collection; -import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.springframework.batch.core.Job; import org.springframework.batch.core.step.StepLocator; import org.springframework.beans.factory.BeanCreationException; @@ -36,49 +35,45 @@ import org.springframework.context.support.FileSystemXmlApplicationContext; import org.springframework.core.io.Resource; import org.springframework.core.io.support.ResourceArrayPropertyEditor; +import org.springframework.lang.Nullable; import org.springframework.util.ClassUtils; -@RunWith(Parameterized.class) -public class StepNameTests { +class StepNameTests { - private Map stepLocators = new HashMap<>(); - - private ApplicationContext context; - - public StepNameTests(Resource resource) throws Exception { + @Nullable + private ApplicationContext getContextFromResource(Resource resource) throws IOException { try { - context = new FileSystemXmlApplicationContext("file:///" + resource.getFile().getAbsolutePath()); + return new FileSystemXmlApplicationContext("file:///" + resource.getFile().getAbsolutePath()); } - catch (BeanDefinitionParsingException e) { - return; + catch (BeanDefinitionParsingException | BeanCreationException e) { + return null; } - catch (BeanCreationException e) { + } + + @MethodSource + @ParameterizedTest + void testStepNames(Resource resource) throws Exception { + ApplicationContext context = getContextFromResource(resource); + if (context == null) { return; } Map stepLocators = context.getBeansOfType(StepLocator.class); - this.stepLocators = stepLocators; - } - - @Test - public void testStepNames() throws Exception { for (String name : stepLocators.keySet()) { StepLocator stepLocator = stepLocators.get(name); Collection stepNames = stepLocator.getStepNames(); Job job = (Job) context.getBean(name); String jobName = job.getName(); - assertTrue("Job has no steps: " + jobName, !stepNames.isEmpty()); + assertFalse(stepNames.isEmpty(), "Job has no steps: " + jobName); for (String registeredName : stepNames) { String stepName = stepLocator.getStep(registeredName).getName(); - assertEquals( - "Step name not equal to registered value: " + stepName + "!=" + registeredName + ", " + jobName, - stepName, registeredName); + assertEquals(stepName, registeredName, "Step name not equal to registered value: " + stepName + "!=" + + registeredName + ", " + jobName); } } } - @Parameters - public static List data() throws Exception { - List list = new ArrayList<>(); + static List testStepNames() throws Exception { + List list = new ArrayList<>(); ResourceArrayPropertyEditor editor = new ResourceArrayPropertyEditor(); editor.setAsText("classpath*:" + ClassUtils.addResourcePathToPackagePath(StepNameTests.class, "*.xml")); Resource[] resources = (Resource[]) editor.getValue(); @@ -86,7 +81,7 @@ public static List data() throws Exception { if (resource.getFile().getName().contains("WrongSchema")) { continue; } - list.add(new Object[] { resource }); + list.add(Arguments.of(resource)); } return list; } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepParserStepFactoryBeanTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepParserStepFactoryBeanTests.java index 6358d78138..005791906e 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepParserStepFactoryBeanTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepParserStepFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -19,7 +19,7 @@ import java.util.HashMap; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.aop.framework.Advised; import org.springframework.aop.framework.ProxyFactory; @@ -48,25 +48,26 @@ import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Dan Garrette * @author Mahmoud Ben Hassine * @since 2.0 */ -public class StepParserStepFactoryBeanTests { +class StepParserStepFactoryBeanTests { - @Test(expected = StepBuilderException.class) - public void testNothingSet() throws Exception { + @Test + void testNothingSet() { StepParserStepFactoryBean fb = new StepParserStepFactoryBean<>(); - fb.getObject(); + assertThrows(StepBuilderException.class, fb::getObject); } @Test - public void testOnlyTaskletSet() throws Exception { + void testOnlyTaskletSet() throws Exception { StepParserStepFactoryBean fb = new StepParserStepFactoryBean<>(); fb.setName("step"); fb.setTransactionManager(new ResourcelessTransactionManager()); @@ -79,7 +80,7 @@ public void testOnlyTaskletSet() throws Exception { } @Test - public void testOnlyTaskletTaskExecutor() throws Exception { + void testOnlyTaskletTaskExecutor() throws Exception { StepParserStepFactoryBean fb = new StepParserStepFactoryBean<>(); fb.setName("step"); fb.setTransactionManager(new ResourcelessTransactionManager()); @@ -92,16 +93,16 @@ public void testOnlyTaskletTaskExecutor() throws Exception { assertTrue(stepOperations instanceof TaskExecutorRepeatTemplate); } - @Test(expected = StepBuilderException.class) - public void testSkipLimitSet() throws Exception { + @Test + void testSkipLimitSet() { StepParserStepFactoryBean fb = new StepParserStepFactoryBean<>(); fb.setName("step"); fb.setSkipLimit(5); - fb.getObject(); + assertThrows(StepBuilderException.class, fb::getObject); } @Test - public void testTaskletStepAll() throws Exception { + void testTaskletStepAll() throws Exception { StepParserStepFactoryBean fb = new StepParserStepFactoryBean<>(); fb.setBeanName("step1"); fb.setAllowStartIfComplete(true); @@ -121,7 +122,7 @@ public void testTaskletStepAll() throws Exception { } @Test - public void testTaskletStepMissingIsolation() throws Exception { + void testTaskletStepMissingIsolation() throws Exception { StepParserStepFactoryBean fb = new StepParserStepFactoryBean<>(); fb.setBeanName("step1"); fb.setJobRepository(new JobRepositorySupport()); @@ -134,8 +135,8 @@ public void testTaskletStepMissingIsolation() throws Exception { assertTrue(tasklet instanceof DummyTasklet); } - @Test(expected = IllegalStateException.class) - public void testSimpleStepAll() throws Exception { + @Test + void testSimpleStepAll() { StepParserStepFactoryBean fb = new StepParserStepFactoryBean<>(); fb.setBeanName("step1"); fb.setAllowStartIfComplete(true); @@ -155,14 +156,11 @@ public void testSimpleStepAll() throws Exception { fb.setStreams(new ItemStream[] { new FlatFileItemReader<>() }); fb.setHasChunkElement(true); - Object step = fb.getObject(); - assertTrue(step instanceof TaskletStep); - Object tasklet = ReflectionTestUtils.getField(step, "tasklet"); - assertTrue(tasklet instanceof ChunkOrientedTasklet); + assertThrows(IllegalStateException.class, fb::getObject); } - @Test(expected = IllegalArgumentException.class) - public void testFaultTolerantStepAll() throws Exception { + @Test + void testFaultTolerantStepAll() { StepParserStepFactoryBean fb = new StepParserStepFactoryBean<>(); fb.setBeanName("step1"); fb.setAllowStartIfComplete(true); @@ -189,14 +187,11 @@ public void testFaultTolerantStepAll() throws Exception { fb.setRetryableExceptionClasses(new HashMap<>()); fb.setHasChunkElement(true); - Object step = fb.getObject(); - assertTrue(step instanceof TaskletStep); - Object tasklet = ReflectionTestUtils.getField(step, "tasklet"); - assertTrue(tasklet instanceof ChunkOrientedTasklet); + assertThrows(IllegalArgumentException.class, fb::getObject); } @Test - public void testSimpleStep() throws Exception { + void testSimpleStep() throws Exception { StepParserStepFactoryBean fb = new StepParserStepFactoryBean<>(); fb.setHasChunkElement(true); fb.setBeanName("step1"); @@ -223,7 +218,7 @@ public void testSimpleStep() throws Exception { } @Test - public void testFaultTolerantStep() throws Exception { + void testFaultTolerantStep() throws Exception { StepParserStepFactoryBean fb = new StepParserStepFactoryBean<>(); fb.setHasChunkElement(true); fb.setBeanName("step1"); @@ -265,7 +260,7 @@ public void testFaultTolerantStep() throws Exception { } @Test - public void testPartitionStep() throws Exception { + void testPartitionStep() throws Exception { StepParserStepFactoryBean fb = new StepParserStepFactoryBean<>(); fb.setBeanName("step1"); fb.setAllowStartIfComplete(true); @@ -286,7 +281,7 @@ public void testPartitionStep() throws Exception { } @Test - public void testPartitionStepWithProxyHandler() throws Exception { + void testPartitionStepWithProxyHandler() throws Exception { StepParserStepFactoryBean fb = new StepParserStepFactoryBean<>(); fb.setBeanName("step1"); fb.setAllowStartIfComplete(true); @@ -310,7 +305,7 @@ public void testPartitionStepWithProxyHandler() throws Exception { } @Test - public void testFlowStep() throws Exception { + void testFlowStep() throws Exception { StepParserStepFactoryBean fb = new StepParserStepFactoryBean<>(); fb.setBeanName("step1"); fb.setAllowStartIfComplete(true); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepParserTests.java index b57d94c0cf..1bdfd4e395 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepParserTests.java @@ -15,8 +15,10 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Arrays; @@ -27,8 +29,8 @@ import java.util.Map.Entry; import java.util.Set; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.springframework.aop.framework.Advised; import org.springframework.batch.core.Step; import org.springframework.batch.core.StepExecutionListener; @@ -70,15 +72,14 @@ public class StepParserTests { private static ApplicationContext stepParserParentAttributeTestsCtx; - @BeforeClass + @BeforeAll public static void loadAppCtx() { stepParserParentAttributeTestsCtx = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/xml/StepParserParentAttributeTests-context.xml"); } @Test - @SuppressWarnings("resource") - public void testTaskletStepAttributes() throws Exception { + void testTaskletStepAttributes() throws Exception { ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/xml/StepParserTaskletAttributesTests-context.xml"); @SuppressWarnings({ "rawtypes" }) @@ -87,36 +88,33 @@ public void testTaskletStepAttributes() throws Exception { @SuppressWarnings("unchecked") StepParserStepFactoryBean factory = beans.get(factoryName); TaskletStep bean = (TaskletStep) factory.getObject(); - assertEquals("wrong start-limit:", 25, bean.getStartLimit()); + assertEquals(25, bean.getStartLimit(), "wrong start-limit:"); Object throttleLimit = ReflectionTestUtils.getField(factory, "throttleLimit"); assertEquals(Integer.valueOf(10), throttleLimit); } @Test - @SuppressWarnings("resource") - public void testStepParserBeanName() throws Exception { + void testStepParserBeanName() { ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/xml/StepParserBeanNameTests-context.xml"); Map beans = ctx.getBeansOfType(Step.class); - assertTrue("'s1' bean not found", beans.containsKey("s1")); + assertTrue(beans.containsKey("s1"), "'s1' bean not found"); Step s1 = (Step) ctx.getBean("s1"); - assertEquals("wrong name", "s1", s1.getName()); + assertEquals("s1", s1.getName(), "wrong name"); } - @Test(expected = BeanDefinitionParsingException.class) - @SuppressWarnings("resource") - public void testStepParserCommitIntervalCompletionPolicy() throws Exception { - new ClassPathXmlApplicationContext( - "org/springframework/batch/core/configuration/xml/StepParserCommitIntervalCompletionPolicyTests-context.xml"); + @Test + void testStepParserCommitIntervalCompletionPolicy() { + assertThrows(BeanDefinitionParsingException.class, () -> new ClassPathXmlApplicationContext( + "org/springframework/batch/core/configuration/xml/StepParserCommitIntervalCompletionPolicyTests-context.xml")); } @Test - @SuppressWarnings("resource") - public void testStepParserCommitInterval() throws Exception { + void testStepParserCommitInterval() throws Exception { ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/xml/StepParserCommitIntervalTests-context.xml"); Map beans = ctx.getBeansOfType(Step.class); - assertTrue("'s1' bean not found", beans.containsKey("s1")); + assertTrue(beans.containsKey("s1"), "'s1' bean not found"); Step s1 = (Step) ctx.getBean("s1"); CompletionPolicy completionPolicy = getCompletionPolicy(s1); assertTrue(completionPolicy instanceof SimpleCompletionPolicy); @@ -124,12 +122,11 @@ public void testStepParserCommitInterval() throws Exception { } @Test - @SuppressWarnings("resource") - public void testStepParserCompletionPolicy() throws Exception { + void testStepParserCompletionPolicy() throws Exception { ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext( "org/springframework/batch/core/configuration/xml/StepParserCompletionPolicyTests-context.xml"); Map beans = ctx.getBeansOfType(Step.class); - assertTrue("'s1' bean not found", beans.containsKey("s1")); + assertTrue(beans.containsKey("s1"), "'s1' bean not found"); Step s1 = (Step) ctx.getBean("s1"); CompletionPolicy completionPolicy = getCompletionPolicy(s1); assertTrue(completionPolicy instanceof DummyCompletionPolicy); @@ -142,29 +139,26 @@ private CompletionPolicy getCompletionPolicy(Step s1) throws NoSuchFieldExceptio return (CompletionPolicy) ReflectionTestUtils.getField(repeatOperations, "completionPolicy"); } - @Test(expected = BeanDefinitionParsingException.class) - @SuppressWarnings("resource") - public void testStepParserNoCommitIntervalOrCompletionPolicy() throws Exception { - new ClassPathXmlApplicationContext( - "org/springframework/batch/core/configuration/xml/StepParserNoCommitIntervalOrCompletionPolicyTests-context.xml"); + @Test + void testStepParserNoCommitIntervalOrCompletionPolicy() { + assertThrows(BeanDefinitionParsingException.class, () -> new ClassPathXmlApplicationContext( + "org/springframework/batch/core/configuration/xml/StepParserNoCommitIntervalOrCompletionPolicyTests-context.xml")); } - @Test(expected = BeanDefinitionParsingException.class) - @SuppressWarnings("resource") - public void testTaskletStepWithBadStepListener() throws Exception { - new ClassPathXmlApplicationContext( - "org/springframework/batch/core/configuration/xml/StepParserBadStepListenerTests-context.xml"); + @Test + void testTaskletStepWithBadStepListener() { + assertThrows(BeanDefinitionParsingException.class, () -> new ClassPathXmlApplicationContext( + "org/springframework/batch/core/configuration/xml/StepParserBadStepListenerTests-context.xml")); } - @Test(expected = BeanDefinitionParsingException.class) - @SuppressWarnings("resource") - public void testTaskletStepWithBadRetryListener() throws Exception { - new ClassPathXmlApplicationContext( - "org/springframework/batch/core/configuration/xml/StepParserBadRetryListenerTests-context.xml"); + @Test + void testTaskletStepWithBadRetryListener() { + assertThrows(BeanDefinitionParsingException.class, () -> new ClassPathXmlApplicationContext( + "org/springframework/batch/core/configuration/xml/StepParserBadRetryListenerTests-context.xml")); } @Test - public void testParentStep() throws Exception { + void testParentStep() throws Exception { ApplicationContext ctx = stepParserParentAttributeTestsCtx; // Inline Step @@ -181,7 +175,7 @@ public void testParentStep() throws Exception { } @Test - public void testInheritTransactionAttributes() throws Exception { + void testInheritTransactionAttributes() throws Exception { ApplicationContext ctx = stepParserParentAttributeTestsCtx; // On Inline - No Merge @@ -250,7 +244,7 @@ private DefaultTransactionAttribute getTransactionAttribute(ApplicationContext c } @Test - public void testInheritFromBean() throws Exception { + void testInheritFromBean() { ApplicationContext ctx = stepParserParentAttributeTestsCtx; assertTrue(getTasklet("s9", ctx) instanceof DummyTasklet); @@ -267,7 +261,7 @@ private Tasklet getTasklet(String stepName, ApplicationContext ctx) { } @Test - public void testJobRepositoryDefaults() throws Exception { + void testJobRepositoryDefaults() throws Exception { ApplicationContext ctx = stepParserParentAttributeTestsCtx; assertTrue(getJobRepository("defaultRepoStep", ctx) instanceof SimpleJobRepository); @@ -294,7 +288,7 @@ public void testJobRepositoryDefaults() throws Exception { } @Test - public void testTransactionManagerDefaults() throws Exception { + void testTransactionManagerDefaults() throws Exception { ApplicationContext ctx = stepParserParentAttributeTestsCtx; assertTrue(getTransactionManager("defaultTxMgrStep", ctx) instanceof JdbcTransactionManager); @@ -344,7 +338,7 @@ private Object getFieldFromBean(String beanName, String field, ApplicationContex } @Test - public void testNonAbstractStep() { + void testNonAbstractStep() { ApplicationContext ctx = stepParserParentAttributeTestsCtx; assertTrue(ctx.containsBean("s11")); @@ -353,7 +347,7 @@ public void testNonAbstractStep() { } @Test - public void testInlineTaskletElementOverridesParentBeanClass() { + void testInlineTaskletElementOverridesParentBeanClass() { ApplicationContext ctx = stepParserParentAttributeTestsCtx; assertTrue(ctx.containsBean("&s12")); @@ -370,7 +364,7 @@ public void testInlineTaskletElementOverridesParentBeanClass() { } @Test - public void testTaskletElementOverridesChildBeanClass() { + void testTaskletElementOverridesChildBeanClass() { ApplicationContext ctx = stepParserParentAttributeTestsCtx; assertTrue(ctx.containsBean("&s13")); @@ -399,7 +393,7 @@ public void testTaskletElementOverridesChildBeanClass() { } @Test - public void testTaskletElementOverridesParentBeanClass() { + void testTaskletElementOverridesParentBeanClass() { ApplicationContext ctx = stepParserParentAttributeTestsCtx; assertTrue(ctx.containsBean("&s14")); @@ -425,7 +419,7 @@ public void testTaskletElementOverridesParentBeanClass() { @SuppressWarnings("unchecked") @Test - public void testStepWithListsMerge() throws Exception { + void testStepWithListsMerge() throws Exception { ApplicationContext ctx = stepParserParentAttributeTestsCtx; Map, Boolean> skippable = new HashMap<>(); @@ -466,7 +460,7 @@ public void testStepWithListsMerge() throws Exception { @SuppressWarnings("unchecked") @Test - public void testStepWithListsNoMerge() throws Exception { + void testStepWithListsNoMerge() throws Exception { ApplicationContext ctx = stepParserParentAttributeTestsCtx; Map, Boolean> skippable = new HashMap<>(); @@ -501,7 +495,7 @@ public void testStepWithListsNoMerge() throws Exception { @SuppressWarnings("unchecked") @Test - public void testStepWithListsOverrideWithEmpty() throws Exception { + void testStepWithListsOverrideWithEmpty() throws Exception { ApplicationContext ctx = stepParserParentAttributeTestsCtx; StepParserStepFactoryBean fb = (StepParserStepFactoryBean) ctx diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepWithBasicProcessTaskJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepWithBasicProcessTaskJobParserTests.java index d38cac9677..2ad66f701d 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepWithBasicProcessTaskJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepWithBasicProcessTaskJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,14 +15,13 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Set; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -32,17 +31,15 @@ import org.springframework.batch.item.ItemStream; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.util.ReflectionTestUtils; /** * @author Thomas Risberg * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class StepWithBasicProcessTaskJobParserTests { +@SpringJUnitConfig +class StepWithBasicProcessTaskJobParserTests { @Autowired private Job job; @@ -68,14 +65,14 @@ public class StepWithBasicProcessTaskJobParserTests { @SuppressWarnings("unchecked") @Test - public void testStepWithTask() throws Exception { + void testStepWithTask() throws Exception { assertNotNull(job); Object ci = ReflectionTestUtils.getField(factory, "commitInterval"); - assertEquals("wrong chunk-size:", 10, ci); + assertEquals(10, ci, "wrong chunk-size:"); Object listeners = ReflectionTestUtils.getField(factory, "stepExecutionListeners"); - assertEquals("wrong number of listeners:", 2, ((Set) listeners).size()); + assertEquals(2, ((Set) listeners).size(), "wrong number of listeners:"); Object streams = ReflectionTestUtils.getField(factory, "streams"); - assertEquals("wrong number of streams:", 1, ((ItemStream[]) streams).length); + assertEquals(1, ((ItemStream[]) streams).length, "wrong number of streams:"); JobExecution jobExecution = jobRepository.createJobExecution(job.getName(), new JobParameters()); job.execute(jobExecution); assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepWithFaultTolerantProcessTaskJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepWithFaultTolerantProcessTaskJobParserTests.java index e01454b38d..f809f5f7c2 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepWithFaultTolerantProcessTaskJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepWithFaultTolerantProcessTaskJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,14 +15,13 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Set; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -34,8 +33,7 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.retry.RetryListener; import org.springframework.scheduling.concurrent.ConcurrentTaskExecutor; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; @@ -44,9 +42,8 @@ * @author Thomas Risberg * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class StepWithFaultTolerantProcessTaskJobParserTests { +@SpringJUnitConfig +class StepWithFaultTolerantProcessTaskJobParserTests { @Autowired private Job job; @@ -75,31 +72,31 @@ public class StepWithFaultTolerantProcessTaskJobParserTests { @SuppressWarnings("unchecked") @Test - public void testStepWithTask() throws Exception { + void testStepWithTask() throws Exception { assertNotNull(job); Object ci = ReflectionTestUtils.getField(factory, "commitInterval"); - assertEquals("wrong chunk-size:", 10, ci); + assertEquals(10, ci, "wrong chunk-size:"); Object sl = ReflectionTestUtils.getField(factory, "skipLimit"); - assertEquals("wrong skip-limit:", 20, sl); + assertEquals(20, sl, "wrong skip-limit:"); Object rl = ReflectionTestUtils.getField(factory, "retryLimit"); - assertEquals("wrong retry-limit:", 3, rl); + assertEquals(3, rl, "wrong retry-limit:"); Object cc = ReflectionTestUtils.getField(factory, "cacheCapacity"); - assertEquals("wrong cache-capacity:", 100, cc); - assertEquals("wrong transaction-attribute:", Propagation.REQUIRED, - ReflectionTestUtils.getField(factory, "propagation")); - assertEquals("wrong transaction-attribute:", Isolation.DEFAULT, - ReflectionTestUtils.getField(factory, "isolation")); - assertEquals("wrong transaction-attribute:", 10, ReflectionTestUtils.getField(factory, "transactionTimeout")); + assertEquals(100, cc, "wrong cache-capacity:"); + assertEquals(Propagation.REQUIRED, ReflectionTestUtils.getField(factory, "propagation"), + "wrong transaction-attribute:"); + assertEquals(Isolation.DEFAULT, ReflectionTestUtils.getField(factory, "isolation"), + "wrong transaction-attribute:"); + assertEquals(10, ReflectionTestUtils.getField(factory, "transactionTimeout"), "wrong transaction-attribute:"); Object txq = ReflectionTestUtils.getField(factory, "readerTransactionalQueue"); - assertEquals("wrong reader-transactional-queue:", true, txq); + assertEquals(true, txq, "wrong reader-transactional-queue:"); Object te = ReflectionTestUtils.getField(factory, "taskExecutor"); - assertEquals("wrong task-executor:", ConcurrentTaskExecutor.class, te.getClass()); + assertEquals(ConcurrentTaskExecutor.class, te.getClass(), "wrong task-executor:"); Object listeners = ReflectionTestUtils.getField(factory, "stepExecutionListeners"); - assertEquals("wrong number of listeners:", 2, ((Set) listeners).size()); + assertEquals(2, ((Set) listeners).size(), "wrong number of listeners:"); Object retryListeners = ReflectionTestUtils.getField(factory, "retryListeners"); - assertEquals("wrong number of retry-listeners:", 2, ((RetryListener[]) retryListeners).length); + assertEquals(2, ((RetryListener[]) retryListeners).length, "wrong number of retry-listeners:"); Object streams = ReflectionTestUtils.getField(factory, "streams"); - assertEquals("wrong number of streams:", 1, ((ItemStream[]) streams).length); + assertEquals(1, ((ItemStream[]) streams).length, "wrong number of streams:"); JobExecution jobExecution = jobRepository.createJobExecution(job.getName(), new JobParameters()); job.execute(jobExecution); assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepWithPojoListenerJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepWithPojoListenerJobParserTests.java index 6224ca599b..3d50e524d0 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepWithPojoListenerJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepWithPojoListenerJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,12 +15,11 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -28,16 +27,14 @@ import org.springframework.batch.core.repository.JobRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class StepWithPojoListenerJobParserTests { +@SpringJUnitConfig +class StepWithPojoListenerJobParserTests { @Autowired private Job job; @@ -56,7 +53,7 @@ public class StepWithPojoListenerJobParserTests { private TestWriter writer; @Test - public void testStepWithTask() throws Exception { + void testStepWithTask() throws Exception { assertNotNull(job); JobExecution jobExecution = jobRepository.createJobExecution(job.getName(), new JobParameters()); job.execute(jobExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepWithSimpleTaskJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepWithSimpleTaskJobParserTests.java index 1c5c872f47..80db3683a2 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepWithSimpleTaskJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StepWithSimpleTaskJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,12 +15,12 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -31,16 +31,14 @@ import org.springframework.batch.core.step.tasklet.TaskletStep; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.util.ReflectionTestUtils; /** * @author Thomas Risberg */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class StepWithSimpleTaskJobParserTests { +@SpringJUnitConfig +class StepWithSimpleTaskJobParserTests { @Autowired private Job job; @@ -53,7 +51,7 @@ public class StepWithSimpleTaskJobParserTests { private TestListener listener; @Test - public void testJob() throws Exception { + void testJob() throws Exception { assertNotNull(job); assertTrue(job instanceof FlowJob); JobExecution jobExecution = jobRepository.createJobExecution(job.getName(), new JobParameters()); @@ -78,12 +76,12 @@ public void testJob() throws Exception { private TestTasklet assertTasklet(Job job, String stepName, String taskletName) { System.err.println(((FlowJob) job).getStepNames()); Step step = ((FlowJob) job).getStep(stepName); - assertTrue("Wrong type for step name=" + stepName + ": " + step, step instanceof TaskletStep); + assertTrue(step instanceof TaskletStep, "Wrong type for step name=" + stepName + ": " + step); Object tasklet = ReflectionTestUtils.getField(step, "tasklet"); assertTrue(tasklet instanceof TestTasklet); TestTasklet testTasklet = (TestTasklet) tasklet; assertEquals(taskletName, testTasklet.getName()); - assertTrue(!testTasklet.isExecuted()); + assertFalse(testTasklet.isExecuted()); return testTasklet; } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StopAndRestartFailedJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StopAndRestartFailedJobParserTests.java index b8be653d65..b8fe6dedfb 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StopAndRestartFailedJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StopAndRestartFailedJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,10 +15,9 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; @@ -26,22 +25,20 @@ import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException; import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException; import org.springframework.batch.core.repository.JobRestartException; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * @author Mahmoud Ben Hassine * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) +@SpringJUnitConfig // FIXME this test fails when upgrading the batch xsd from 2.2 to 3.0: // https://github.com/spring-projects/spring-batch/issues/1287 -public class StopAndRestartFailedJobParserTests extends AbstractJobParserTests { +class StopAndRestartFailedJobParserTests extends AbstractJobParserTests { @Test - public void testStopRestartOnCompletedStep() throws Exception { + void testStopRestartOnCompletedStep() throws Exception { // // First Launch diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StopAndRestartJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StopAndRestartJobParserTests.java index 58054176d4..1702b6f1a3 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StopAndRestartJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StopAndRestartJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,29 +15,26 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import org.junit.Test; -import org.junit.runner.RunWith; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * @author Mahmoud Ben Hassine * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) +@SpringJUnitConfig // FIXME this test fails when upgrading the batch xsd from 2.2 to 3.0: // https://github.com/spring-projects/spring-batch/issues/1287 -public class StopAndRestartJobParserTests extends AbstractJobParserTests { +class StopAndRestartJobParserTests extends AbstractJobParserTests { @Test - public void testStopIncomplete() throws Exception { + void testStopIncomplete() throws Exception { // // First Launch diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StopCustomStatusJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StopCustomStatusJobParserTests.java index 077c1907d0..f0fe245e14 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StopCustomStatusJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StopCustomStatusJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,29 +15,26 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import org.junit.Test; -import org.junit.runner.RunWith; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * @author Mahmoud Ben Hassine * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) +@SpringJUnitConfig // FIXME this test fails when upgrading the batch xsd from 2.2 to 3.0: // https://github.com/spring-projects/spring-batch/issues/1287 -public class StopCustomStatusJobParserTests extends AbstractJobParserTests { +class StopCustomStatusJobParserTests extends AbstractJobParserTests { @Test - public void testStopCustomStatus() throws Exception { + void testStopCustomStatus() throws Exception { // // First Launch @@ -45,7 +42,7 @@ public void testStopCustomStatus() throws Exception { JobExecution jobExecution = createJobExecution(); job.execute(jobExecution); assertEquals(1, stepNamesList.size()); - assertEquals("Wrong steps executed: " + stepNamesList, "[stop]", stepNamesList.toString()); + assertEquals("[stop]", stepNamesList.toString(), "Wrong steps executed: " + stepNamesList); assertEquals(BatchStatus.STOPPED, jobExecution.getStatus()); assertEquals(ExitStatus.STOPPED.getExitCode(), jobExecution.getExitStatus().getExitCode()); @@ -61,7 +58,7 @@ public void testStopCustomStatus() throws Exception { jobExecution = createJobExecution(); job.execute(jobExecution); assertEquals(1, stepNamesList.size()); // step1 is not executed - assertEquals("Wrong steps executed: " + stepNamesList, "[s2]", stepNamesList.toString()); + assertEquals("[s2]", stepNamesList.toString(), "Wrong steps executed: " + stepNamesList); assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus()); assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StopIncompleteJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StopIncompleteJobParserTests.java index 207aedff8c..e6ddfee766 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StopIncompleteJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StopIncompleteJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,29 +15,26 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import org.junit.Test; -import org.junit.runner.RunWith; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * @author Mahmoud Ben Hassine * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) +@SpringJUnitConfig // FIXME this test fails when upgrading the batch xsd from 2.2 to 3.0: // https://github.com/spring-projects/spring-batch/issues/1287 -public class StopIncompleteJobParserTests extends AbstractJobParserTests { +class StopIncompleteJobParserTests extends AbstractJobParserTests { @Test - public void testStopIncomplete() throws Exception { + void testStopIncomplete() throws Exception { // // First Launch @@ -45,7 +42,7 @@ public void testStopIncomplete() throws Exception { JobExecution jobExecution = createJobExecution(); job.execute(jobExecution); assertEquals(1, stepNamesList.size()); - assertEquals("Wrong steps executed: " + stepNamesList, "[fail]", stepNamesList.toString()); + assertEquals("[fail]", stepNamesList.toString(), "Wrong steps executed: " + stepNamesList); assertEquals(BatchStatus.STOPPED, jobExecution.getStatus()); assertEquals(ExitStatus.STOPPED.getExitCode(), jobExecution.getExitStatus().getExitCode()); @@ -61,7 +58,7 @@ public void testStopIncomplete() throws Exception { jobExecution = createJobExecution(); job.execute(jobExecution); assertEquals(1, stepNamesList.size()); // step1 is not executed - assertEquals("Wrong steps executed: " + stepNamesList, "[s2]", stepNamesList.toString()); + assertEquals("[s2]", stepNamesList.toString(), "Wrong steps executed: " + stepNamesList); assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus()); assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StopJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StopJobParserTests.java index ea4870bd02..b2f0d75c71 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StopJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StopJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,11 +15,10 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; @@ -27,22 +26,20 @@ import org.springframework.batch.core.job.flow.FlowExecutionStatus; import org.springframework.batch.core.job.flow.JobExecutionDecider; import org.springframework.lang.Nullable; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * @author Mahmoud Ben Hassine * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) +@SpringJUnitConfig // FIXME this test fails when upgrading the batch xsd from 2.2 to 3.0: // https://github.com/spring-projects/spring-batch/issues/1287 -public class StopJobParserTests extends AbstractJobParserTests { +class StopJobParserTests extends AbstractJobParserTests { @Test - public void testStopState() throws Exception { + void testStopState() throws Exception { // // First Launch diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StopRestartOnCompletedStepJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StopRestartOnCompletedStepJobParserTests.java index 5c45322e3a..4fa77cfc13 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StopRestartOnCompletedStepJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StopRestartOnCompletedStepJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,10 +15,9 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; @@ -26,19 +25,17 @@ import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException; import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException; import org.springframework.batch.core.repository.JobRestartException; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class StopRestartOnCompletedStepJobParserTests extends AbstractJobParserTests { +@SpringJUnitConfig +class StopRestartOnCompletedStepJobParserTests extends AbstractJobParserTests { @Test - public void testStopRestartOnCompletedStep() throws Exception { + void testStopRestartOnCompletedStep() throws Exception { // // First Launch diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StopRestartOnFailedStepJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StopRestartOnFailedStepJobParserTests.java index cd125b8408..128e018b9b 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StopRestartOnFailedStepJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/StopRestartOnFailedStepJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,10 +15,9 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; @@ -26,19 +25,17 @@ import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException; import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException; import org.springframework.batch.core.repository.JobRestartException; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class StopRestartOnFailedStepJobParserTests extends AbstractJobParserTests { +@SpringJUnitConfig +class StopRestartOnFailedStepJobParserTests extends AbstractJobParserTests { @Test - public void testStopRestartOnCompletedStep() throws Exception { + void testStopRestartOnCompletedStep() throws Exception { // // First Launch diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/TaskletParserAdapterTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/TaskletParserAdapterTests.java index 19b1470ee3..16da4b2237 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/TaskletParserAdapterTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/TaskletParserAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,11 +15,10 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -27,17 +26,15 @@ import org.springframework.batch.core.repository.JobRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * @author Mahmoud Ben Hassine * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class TaskletParserAdapterTests { +@SpringJUnitConfig +class TaskletParserAdapterTests { @Autowired @Qualifier("job1") @@ -51,7 +48,7 @@ public class TaskletParserAdapterTests { private JobRepository jobRepository; @Test - public void testTaskletRef() throws Exception { + void testTaskletRef() throws Exception { assertNotNull(job1); JobExecution jobExecution = jobRepository.createJobExecution(job1.getName(), new JobParameters()); job1.execute(jobExecution); @@ -59,7 +56,7 @@ public void testTaskletRef() throws Exception { } @Test - public void testTaskletInline() throws Exception { + void testTaskletInline() throws Exception { assertNotNull(job2); JobExecution jobExecution = jobRepository.createJobExecution(job2.getName(), new JobParameters()); job2.execute(jobExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/TaskletParserBeanPropertiesTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/TaskletParserBeanPropertiesTests.java index 1ef5187a2d..cc19f41faf 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/TaskletParserBeanPropertiesTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/TaskletParserBeanPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -17,8 +17,7 @@ import java.lang.reflect.Field; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -30,21 +29,19 @@ import org.springframework.batch.core.test.namespace.config.DummyNamespaceHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.util.ReflectionUtils; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; /** * @author Dave Syer * @author Mahmoud Ben Hassine * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class TaskletParserBeanPropertiesTests { +@SpringJUnitConfig +class TaskletParserBeanPropertiesTests { @Autowired @Qualifier("job1") @@ -70,7 +67,7 @@ public class TaskletParserBeanPropertiesTests { private JobRepository jobRepository; @Test - public void testTaskletRef() throws Exception { + void testTaskletRef() throws Exception { assertNotNull(job1); JobExecution jobExecution = jobRepository.createJobExecution(job1.getName(), new JobParameters()); job1.execute(jobExecution); @@ -79,7 +76,7 @@ public void testTaskletRef() throws Exception { } @Test - public void testTaskletInline() throws Exception { + void testTaskletInline() throws Exception { assertNotNull(job2); JobExecution jobExecution = jobRepository.createJobExecution(job2.getName(), new JobParameters()); job2.execute(jobExecution); @@ -90,7 +87,7 @@ public void testTaskletInline() throws Exception { } @Test - public void testTasklet3() throws Exception { + void testTasklet3() throws Exception { assertNotNull(job3); JobExecution jobExecution = jobRepository.createJobExecution(job3.getName(), new JobParameters()); job3.execute(jobExecution); @@ -104,7 +101,7 @@ public void testTasklet3() throws Exception { } @Test - public void testCustomNestedTasklet() throws Exception { + void testCustomNestedTasklet() throws Exception { assertNotNull(job4); JobExecution jobExecution = jobRepository.createJobExecution(job4.getName(), new JobParameters()); job4.execute(jobExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/TaskletStepAllowStartIfCompleteTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/TaskletStepAllowStartIfCompleteTests.java index c2379b2178..6561f228d8 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/TaskletStepAllowStartIfCompleteTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/TaskletStepAllowStartIfCompleteTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2021 the original author or authors. + * Copyright 2013-2022 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. @@ -15,15 +15,14 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Date; import jakarta.annotation.Resource; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParametersBuilder; @@ -31,12 +30,10 @@ import org.springframework.batch.core.step.AbstractStep; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration -public class TaskletStepAllowStartIfCompleteTests { +@SpringJUnitConfig +class TaskletStepAllowStartIfCompleteTests { @Autowired Job job; @@ -48,14 +45,14 @@ public class TaskletStepAllowStartIfCompleteTests { private ApplicationContext context; @Test - public void test() throws Exception { + void test() throws Exception { // retrieve the step from the context and see that it's allow is set AbstractStep abstractStep = (AbstractStep) context.getBean("simpleJob.step1"); assertTrue(abstractStep.isAllowStartIfComplete()); } @Test - public void testRestart() throws Exception { + void testRestart() throws Exception { JobParametersBuilder paramBuilder = new JobParametersBuilder(); paramBuilder.addDate("value", new Date()); JobExecution jobExecution = jobRepository.createJobExecution(job.getName(), paramBuilder.toJobParameters()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/TwoStepJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/TwoStepJobParserTests.java index d92f29d260..c8e8d755e0 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/TwoStepJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/TwoStepJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,27 +15,24 @@ */ package org.springframework.batch.core.configuration.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.repository.JobRepository; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class TwoStepJobParserTests { +@SpringJUnitConfig +class TwoStepJobParserTests { @Autowired private Job job; @@ -44,7 +41,7 @@ public class TwoStepJobParserTests { private JobRepository jobRepository; @Test - public void testTwoStep() throws Exception { + void testTwoStep() throws Exception { assertNotNull(job); JobExecution jobExecution = jobRepository.createJobExecution(job.getName(), new JobParameters()); job.execute(jobExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/converter/DefaultJobParametersConverterTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/converter/DefaultJobParametersConverterTests.java index 37d789369f..a33bf7d740 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/converter/DefaultJobParametersConverterTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/converter/DefaultJobParametersConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,10 +15,10 @@ */ package org.springframework.batch.core.converter; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.text.DateFormat; import java.text.DecimalFormat; @@ -29,7 +29,7 @@ import java.util.Locale; import java.util.Properties; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.JobParametersBuilder; import org.springframework.util.StringUtils; @@ -39,14 +39,14 @@ * @author Michael Minella * */ -public class DefaultJobParametersConverterTests { +class DefaultJobParametersConverterTests { - DefaultJobParametersConverter factory = new DefaultJobParametersConverter(); + private final DefaultJobParametersConverter factory = new DefaultJobParametersConverter(); - DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); + private final DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); @Test - public void testGetParametersIdentifyingWithIdentifyingKey() throws Exception { + void testGetParametersIdentifyingWithIdentifyingKey() { String jobKey = "+job.key=myKey"; String scheduleDate = "+schedule.date(date)=2008/01/23"; String vendorId = "+vendor.id(long)=33243243"; @@ -61,7 +61,7 @@ public void testGetParametersIdentifyingWithIdentifyingKey() throws Exception { } @Test - public void testGetParametersIdentifyingByDefault() throws Exception { + void testGetParametersIdentifyingByDefault() { String jobKey = "job.key=myKey"; String scheduleDate = "schedule.date(date)=2008/01/23"; String vendorId = "vendor.id(long)=33243243"; @@ -76,7 +76,7 @@ public void testGetParametersIdentifyingByDefault() throws Exception { } @Test - public void testGetParametersNonIdentifying() throws Exception { + void testGetParametersNonIdentifying() { String jobKey = "-job.key=myKey"; String scheduleDate = "-schedule.date(date)=2008/01/23"; String vendorId = "-vendor.id(long)=33243243"; @@ -91,7 +91,7 @@ public void testGetParametersNonIdentifying() throws Exception { } @Test - public void testGetParametersMixed() throws Exception { + void testGetParametersMixed() { String jobKey = "+job.key=myKey"; String scheduleDate = "schedule.date(date)=2008/01/23"; String vendorId = "-vendor.id(long)=33243243"; @@ -106,7 +106,7 @@ public void testGetParametersMixed() throws Exception { } @Test - public void testGetParameters() throws Exception { + void testGetParameters() throws Exception { String jobKey = "job.key=myKey"; String scheduleDate = "schedule.date(date)=2008/01/23"; @@ -123,7 +123,7 @@ public void testGetParameters() throws Exception { } @Test - public void testGetParametersWithDateFormat() throws Exception { + void testGetParametersWithDateFormat() throws Exception { String[] args = new String[] { "schedule.date(date)=2008/23/01" }; @@ -135,7 +135,7 @@ public void testGetParametersWithDateFormat() throws Exception { } @Test - public void testGetParametersWithBogusDate() throws Exception { + void testGetParametersWithBogusDate() { String[] args = new String[] { "schedule.date(date)=20080123" }; @@ -144,13 +144,13 @@ public void testGetParametersWithBogusDate() throws Exception { } catch (IllegalArgumentException e) { String message = e.getMessage(); - assertTrue("Message should contain wrong date: " + message, contains(message, "20080123")); - assertTrue("Message should contain format: " + message, contains(message, "yyyy/MM/dd")); + assertTrue(message.contains("20080123"), "Message should contain wrong date: " + message); + assertTrue(message.contains("yyyy/MM/dd"), "Message should contain format: " + message); } } @Test - public void testGetParametersWithNumberFormat() throws Exception { + void testGetParametersWithNumberFormat() { String[] args = new String[] { "value(long)=1,000" }; @@ -161,7 +161,7 @@ public void testGetParametersWithNumberFormat() throws Exception { } @Test - public void testGetParametersWithBogusLong() throws Exception { + void testGetParametersWithBogusLong() { String[] args = new String[] { "value(long)=foo" }; @@ -170,13 +170,13 @@ public void testGetParametersWithBogusLong() throws Exception { } catch (IllegalArgumentException e) { String message = e.getMessage(); - assertTrue("Message should contain wrong number: " + message, contains(message, "foo")); - assertTrue("Message should contain format: " + message, contains(message, "#")); + assertTrue(message.contains("foo"), "Message should contain wrong number: " + message); + assertTrue(message.contains("#"), "Message should contain format: " + message); } } @Test - public void testGetParametersWithDoubleValueDeclaredAsLong() throws Exception { + void testGetParametersWithDoubleValueDeclaredAsLong() { String[] args = new String[] { "value(long)=1.03" }; factory.setNumberFormat(new DecimalFormat("#.#", DecimalFormatSymbols.getInstance(Locale.ENGLISH))); @@ -186,13 +186,13 @@ public void testGetParametersWithDoubleValueDeclaredAsLong() throws Exception { } catch (IllegalArgumentException e) { String message = e.getMessage(); - assertTrue("Message should contain wrong number: " + message, contains(message, "1.03")); - assertTrue("Message should contain 'decimal': " + message, contains(message, "decimal")); + assertTrue(message.contains("1.03"), "Message should contain wrong number: " + message); + assertTrue(message.contains("decimal"), "Message should contain 'decimal': " + message); } } @Test - public void testGetParametersWithBogusDouble() throws Exception { + void testGetParametersWithBogusDouble() { String[] args = new String[] { "value(double)=foo" }; @@ -201,13 +201,13 @@ public void testGetParametersWithBogusDouble() throws Exception { } catch (IllegalArgumentException e) { String message = e.getMessage(); - assertTrue("Message should contain wrong number: " + message, contains(message, "foo")); - assertTrue("Message should contain format: " + message, contains(message, "#")); + assertTrue(message.contains("foo"), "Message should contain wrong number: " + message); + assertTrue(message.contains("#"), "Message should contain format: " + message); } } @Test - public void testGetParametersWithDouble() throws Exception { + void testGetParametersWithDouble() { String[] args = new String[] { "value(double)=1.38" }; @@ -217,7 +217,7 @@ public void testGetParametersWithDouble() throws Exception { } @Test - public void testGetParametersWithDoubleAndLongAndNumberFormat() throws Exception { + void testGetParametersWithDoubleAndLongAndNumberFormat() { String[] args = new String[] { "value(double)=1,23456", "long(long)=123.456" }; NumberFormat format = NumberFormat.getInstance(Locale.GERMAN); @@ -231,7 +231,7 @@ public void testGetParametersWithDoubleAndLongAndNumberFormat() throws Exception } @Test - public void testGetParametersWithRoundDouble() throws Exception { + void testGetParametersWithRoundDouble() { String[] args = new String[] { "value(double)=1.0" }; @@ -241,7 +241,7 @@ public void testGetParametersWithRoundDouble() throws Exception { } @Test - public void testGetParametersWithVeryRoundDouble() throws Exception { + void testGetParametersWithVeryRoundDouble() { String[] args = new String[] { "value(double)=1" }; @@ -251,7 +251,7 @@ public void testGetParametersWithVeryRoundDouble() throws Exception { } @Test - public void testGetProperties() throws Exception { + void testGetProperties() throws Exception { JobParameters parameters = new JobParametersBuilder().addDate("schedule.date", dateFormat.parse("01/23/2008")) .addString("job.key", "myKey").addLong("vendor.id", 33243243L).addDouble("double.key", 1.23) @@ -266,7 +266,7 @@ public void testGetProperties() throws Exception { } @Test - public void testRoundTrip() throws Exception { + void testRoundTrip() { String[] args = new String[] { "schedule.date(date)=2008/01/23", "job.key=myKey", "vendor.id(long)=33243243", "double.key(double)=1.23" }; @@ -282,7 +282,7 @@ public void testRoundTrip() throws Exception { } @Test - public void testRoundTripWithIdentifyingAndNonIdentifying() throws Exception { + void testRoundTripWithIdentifyingAndNonIdentifying() { String[] args = new String[] { "schedule.date(date)=2008/01/23", "+job.key=myKey", "-vendor.id(long)=33243243", "double.key(double)=1.23" }; @@ -298,7 +298,7 @@ public void testRoundTripWithIdentifyingAndNonIdentifying() throws Exception { } @Test - public void testRoundTripWithNumberFormat() throws Exception { + void testRoundTripWithNumberFormat() { String[] args = new String[] { "schedule.date(date)=2008/01/23", "job.key=myKey", "vendor.id(long)=33243243", "double.key(double)=1,23" }; @@ -316,20 +316,16 @@ public void testRoundTripWithNumberFormat() throws Exception { } @Test - public void testEmptyArgs() { + void testEmptyArgs() { JobParameters props = factory.getJobParameters(new Properties()); assertTrue(props.getParameters().isEmpty()); } @Test - public void testNullArgs() { + void testNullArgs() { assertEquals(new JobParameters(), factory.getJobParameters(null)); assertEquals(new Properties(), factory.getProperties(null)); } - private boolean contains(String str, String searchStr) { - return str.indexOf(searchStr) != -1; - } - } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/explore/support/JobExplorerFactoryBeanTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/explore/support/JobExplorerFactoryBeanTests.java index 7a04983f6e..2a5a8788da 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/explore/support/JobExplorerFactoryBeanTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/explore/support/JobExplorerFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2008 the original author or authors. + * Copyright 2006-2022 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. @@ -15,16 +15,16 @@ */ package org.springframework.batch.core.explore.support; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import javax.sql.DataSource; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.explore.JobExplorer; import org.springframework.jdbc.core.JdbcOperations; import org.springframework.jdbc.core.JdbcTemplate; @@ -35,26 +35,24 @@ * @author Will Schipp * */ -public class JobExplorerFactoryBeanTests { +class JobExplorerFactoryBeanTests { private JobExplorerFactoryBean factory; - private DataSource dataSource; + private final String tablePrefix = "TEST_BATCH_PREFIX_"; - private String tablePrefix = "TEST_BATCH_PREFIX_"; - - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { factory = new JobExplorerFactoryBean(); - dataSource = mock(DataSource.class); + DataSource dataSource = mock(DataSource.class); factory.setDataSource(dataSource); factory.setTablePrefix(tablePrefix); } @Test - public void testDefaultJdbcOperations() throws Exception { + void testDefaultJdbcOperations() throws Exception { factory.afterPropertiesSet(); JdbcOperations jdbcOperations = (JdbcOperations) ReflectionTestUtils.getField(factory, "jdbcOperations"); @@ -62,7 +60,7 @@ public void testDefaultJdbcOperations() throws Exception { } @Test - public void testCustomJdbcOperations() throws Exception { + void testCustomJdbcOperations() throws Exception { JdbcOperations customJdbcOperations = mock(JdbcOperations.class); factory.setJdbcOperations(customJdbcOperations); @@ -71,23 +69,17 @@ public void testCustomJdbcOperations() throws Exception { } @Test - public void testMissingDataSource() throws Exception { + void testMissingDataSource() { factory.setDataSource(null); - try { - factory.afterPropertiesSet(); - fail(); - } - catch (IllegalArgumentException ex) { - // expected - String message = ex.getMessage(); - assertTrue("Wrong message: " + message, message.indexOf("DataSource") >= 0); - } + Exception exception = assertThrows(IllegalArgumentException.class, factory::afterPropertiesSet); + String message = exception.getMessage(); + assertTrue(message.contains("DataSource"), "Wrong message: " + message); } @Test - public void testCreateExplorer() throws Exception { + void testCreateExplorer() throws Exception { factory.afterPropertiesSet(); JobExplorer explorer = factory.getObject(); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/explore/support/SimpleJobExplorerIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/explore/support/SimpleJobExplorerIntegrationTests.java index 23b3f67392..42acc89afe 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/explore/support/SimpleJobExplorerIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/explore/support/SimpleJobExplorerIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2021 the original author or authors. + * Copyright 2013-2022 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. @@ -19,8 +19,7 @@ import java.util.List; import org.apache.commons.dbcp2.BasicDataSource; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import test.jdbc.datasource.DataSourceInitializer; import org.springframework.batch.core.BatchStatus; @@ -53,11 +52,10 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Integration test for the BATCH-2034 issue. The {@link FlowStep} execution should not @@ -69,9 +67,8 @@ * @author Sergey Shcherbakov * @author Mahmoud Ben Hassine */ -@ContextConfiguration(classes = { SimpleJobExplorerIntegrationTests.Config.class }) -@RunWith(SpringJUnit4ClassRunner.class) -public class SimpleJobExplorerIntegrationTests { +@SpringJUnitConfig(classes = { SimpleJobExplorerIntegrationTests.Config.class }) +class SimpleJobExplorerIntegrationTests { @Configuration @EnableBatchProcessing @@ -93,7 +90,7 @@ public JobExplorerFactoryBean jobExplorerFactoryBean() { } @Bean - public Step flowStep() throws Exception { + public Step flowStep() { return steps.get("flowStep").flow(simpleFlow()).build(); } @@ -156,7 +153,7 @@ public Job job(JobBuilderFactory jobBuilderFactory) { private Job job; @Test - public void testGetStepExecution() throws JobExecutionAlreadyRunningException, JobRestartException, + void testGetStepExecution() throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobInterruptedException, UnexpectedJobExecutionException { // Prepare the jobRepository for the test @@ -173,7 +170,7 @@ public void testGetStepExecution() throws JobExecutionAlreadyRunningException, J } @Test - public void getLastJobExecutionShouldFetchStepExecutions() throws Exception { + void getLastJobExecutionShouldFetchStepExecutions() throws Exception { this.jobLauncher.run(this.job, new JobParameters()); JobInstance lastJobInstance = this.jobExplorer.getLastJobInstance("job"); JobExecution lastJobExecution = this.jobExplorer.getLastJobExecution(lastJobInstance); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/explore/support/SimpleJobExplorerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/explore/support/SimpleJobExplorerTests.java index 3d9c9ff5fc..cfecd26065 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/explore/support/SimpleJobExplorerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/explore/support/SimpleJobExplorerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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,16 +16,17 @@ package org.springframework.batch.core.explore.support; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Collections; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInstance; import org.springframework.batch.core.JobParameters; @@ -45,7 +46,7 @@ * @author Mahmoud Ben Hassine * */ -public class SimpleJobExplorerTests { +class SimpleJobExplorerTests { private SimpleJobExplorer jobExplorer; @@ -55,14 +56,14 @@ public class SimpleJobExplorerTests { private StepExecutionDao stepExecutionDao; - private JobInstance jobInstance = new JobInstance(111L, "job"); + private final JobInstance jobInstance = new JobInstance(111L, "job"); private ExecutionContextDao ecDao; - private JobExecution jobExecution = new JobExecution(jobInstance, 1234L, new JobParameters()); + private final JobExecution jobExecution = new JobExecution(jobInstance, 1234L, new JobParameters()); - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { jobExecutionDao = mock(JobExecutionDao.class); jobInstanceDao = mock(JobInstanceDao.class); @@ -74,7 +75,7 @@ public void setUp() throws Exception { } @Test - public void testGetJobExecution() throws Exception { + void testGetJobExecution() { when(jobExecutionDao.getJobExecution(123L)).thenReturn(jobExecution); when(jobInstanceDao.getJobInstance(jobExecution)).thenReturn(jobInstance); stepExecutionDao.addStepExecutions(jobExecution); @@ -82,20 +83,20 @@ public void testGetJobExecution() throws Exception { } @Test - public void testGetLastJobExecution() { + void testGetLastJobExecution() { when(jobExecutionDao.getLastJobExecution(jobInstance)).thenReturn(jobExecution); JobExecution lastJobExecution = jobExplorer.getLastJobExecution(jobInstance); assertEquals(jobExecution, lastJobExecution); } @Test - public void testMissingGetJobExecution() throws Exception { + void testMissingGetJobExecution() { when(jobExecutionDao.getJobExecution(123L)).thenReturn(null); assertNull(jobExplorer.getJobExecution(123L)); } @Test - public void testGetStepExecution() throws Exception { + void testGetStepExecution() { when(jobExecutionDao.getJobExecution(jobExecution.getId())).thenReturn(jobExecution); when(jobInstanceDao.getJobInstance(jobExecution)).thenReturn(jobInstance); StepExecution stepExecution = jobExecution.createStepExecution("foo"); @@ -109,20 +110,20 @@ public void testGetStepExecution() throws Exception { } @Test - public void testGetStepExecutionMissing() throws Exception { + void testGetStepExecutionMissing() { when(jobExecutionDao.getJobExecution(jobExecution.getId())).thenReturn(jobExecution); when(stepExecutionDao.getStepExecution(jobExecution, 123L)).thenReturn(null); assertNull(jobExplorer.getStepExecution(jobExecution.getId(), 123L)); } @Test - public void testGetStepExecutionMissingJobExecution() throws Exception { + void testGetStepExecutionMissingJobExecution() { when(jobExecutionDao.getJobExecution(jobExecution.getId())).thenReturn(null); assertNull(jobExplorer.getStepExecution(jobExecution.getId(), 123L)); } @Test - public void testFindRunningJobExecutions() throws Exception { + void testFindRunningJobExecutions() { StepExecution stepExecution = jobExecution.createStepExecution("step"); when(jobExecutionDao.findRunningJobExecutions("job")).thenReturn(Collections.singleton(jobExecution)); when(jobInstanceDao.getJobInstance(jobExecution)).thenReturn(jobInstance); @@ -133,7 +134,7 @@ public void testFindRunningJobExecutions() throws Exception { } @Test - public void testFindJobExecutions() throws Exception { + void testFindJobExecutions() { StepExecution stepExecution = jobExecution.createStepExecution("step"); when(jobExecutionDao.findJobExecutions(jobInstance)).thenReturn(Collections.singletonList(jobExecution)); when(jobInstanceDao.getJobInstance(jobExecution)).thenReturn(jobInstance); @@ -144,42 +145,41 @@ public void testFindJobExecutions() throws Exception { } @Test - public void testGetJobInstance() throws Exception { + void testGetJobInstance() { jobInstanceDao.getJobInstance(111L); jobExplorer.getJobInstance(111L); } @Test - public void testGetLastJobInstances() throws Exception { + void testGetLastJobInstances() { jobInstanceDao.getJobInstances("foo", 0, 1); jobExplorer.getJobInstances("foo", 0, 1); } @Test - public void testGetLastJobInstance() { + void testGetLastJobInstance() { when(jobInstanceDao.getLastJobInstance("foo")).thenReturn(jobInstance); JobInstance lastJobInstance = jobExplorer.getLastJobInstance("foo"); assertEquals(jobInstance, lastJobInstance); } @Test - public void testGetJobNames() throws Exception { + void testGetJobNames() { jobInstanceDao.getJobNames(); jobExplorer.getJobNames(); } @Test - public void testGetJobInstanceCount() throws Exception { + void testGetJobInstanceCount() throws Exception { when(jobInstanceDao.getJobInstanceCount("myJob")).thenReturn(4); assertEquals(4, jobExplorer.getJobInstanceCount("myJob")); } - @Test(expected = NoSuchJobException.class) - public void testGetJobInstanceCountException() throws Exception { + @Test + void testGetJobInstanceCountException() throws Exception { when(jobInstanceDao.getJobInstanceCount("throwException")).thenThrow(new NoSuchJobException("expected")); - - jobExplorer.getJobInstanceCount("throwException"); + assertThrows(NoSuchJobException.class, () -> jobExplorer.getJobInstanceCount("throwException")); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/job/CompositeJobParametersValidatorTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/job/CompositeJobParametersValidatorTests.java index b6427ecd28..8d1274b525 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/job/CompositeJobParametersValidatorTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/job/CompositeJobParametersValidatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2011 the original author or authors. + * Copyright 2011-2022 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. @@ -15,42 +15,43 @@ */ package org.springframework.batch.core.job; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import java.util.ArrayList; import java.util.Arrays; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.JobParametersInvalidException; import org.springframework.batch.core.JobParametersValidator; -public class CompositeJobParametersValidatorTests { +class CompositeJobParametersValidatorTests { private CompositeJobParametersValidator compositeJobParametersValidator; - private JobParameters parameters = new JobParameters(); + private final JobParameters parameters = new JobParameters(); - @Before - public void setUp() { + @BeforeEach + void setUp() { compositeJobParametersValidator = new CompositeJobParametersValidator(); } - @Test(expected = IllegalArgumentException.class) - public void testValidatorsCanNotBeNull() throws Exception { + @Test + void testValidatorsCanNotBeNull() { compositeJobParametersValidator.setValidators(null); - compositeJobParametersValidator.afterPropertiesSet(); + assertThrows(IllegalArgumentException.class, compositeJobParametersValidator::afterPropertiesSet); } - @Test(expected = IllegalArgumentException.class) - public void testValidatorsCanNotBeEmpty() throws Exception { + @Test + void testValidatorsCanNotBeEmpty() { compositeJobParametersValidator.setValidators(new ArrayList<>()); - compositeJobParametersValidator.afterPropertiesSet(); + assertThrows(IllegalArgumentException.class, compositeJobParametersValidator::afterPropertiesSet); } @Test - public void testDelegateIsInvoked() throws JobParametersInvalidException { + void testDelegateIsInvoked() throws JobParametersInvalidException { JobParametersValidator validator = mock(JobParametersValidator.class); validator.validate(parameters); compositeJobParametersValidator.setValidators(Arrays.asList(validator)); @@ -58,7 +59,7 @@ public void testDelegateIsInvoked() throws JobParametersInvalidException { } @Test - public void testDelegatesAreInvoked() throws JobParametersInvalidException { + void testDelegatesAreInvoked() throws JobParametersInvalidException { JobParametersValidator validator = mock(JobParametersValidator.class); validator.validate(parameters); validator.validate(parameters); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/job/DefaultJobParametersValidatorTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/job/DefaultJobParametersValidatorTests.java index fdaeab548b..e4c6f18b6b 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/job/DefaultJobParametersValidatorTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/job/DefaultJobParametersValidatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2009 the original author or authors. + * Copyright 2009-2022 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. @@ -15,62 +15,65 @@ */ package org.springframework.batch.core.job; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.JobParametersBuilder; import org.springframework.batch.core.JobParametersInvalidException; -public class DefaultJobParametersValidatorTests { +import static org.junit.jupiter.api.Assertions.assertThrows; - private DefaultJobParametersValidator validator = new DefaultJobParametersValidator(); +class DefaultJobParametersValidatorTests { - @Test(expected = JobParametersInvalidException.class) - public void testValidateNull() throws Exception { - validator.validate(null); + private final DefaultJobParametersValidator validator = new DefaultJobParametersValidator(); + + @Test + void testValidateNull() { + assertThrows(JobParametersInvalidException.class, () -> validator.validate(null)); } @Test - public void testValidateNoRequiredValues() throws Exception { + void testValidateNoRequiredValues() throws Exception { validator.validate(new JobParametersBuilder().addString("name", "foo").toJobParameters()); } @Test - public void testValidateRequiredValues() throws Exception { + void testValidateRequiredValues() throws Exception { validator.setRequiredKeys(new String[] { "name", "value" }); validator .validate(new JobParametersBuilder().addString("name", "foo").addLong("value", 111L).toJobParameters()); } - @Test(expected = JobParametersInvalidException.class) - public void testValidateRequiredValuesMissing() throws Exception { + @Test + void testValidateRequiredValuesMissing() { validator.setRequiredKeys(new String[] { "name", "value" }); - validator.validate(new JobParameters()); + assertThrows(JobParametersInvalidException.class, () -> validator.validate(new JobParameters())); } @Test - public void testValidateOptionalValues() throws Exception { + void testValidateOptionalValues() throws Exception { validator.setOptionalKeys(new String[] { "name", "value" }); validator.validate(new JobParameters()); } - @Test(expected = JobParametersInvalidException.class) - public void testValidateOptionalWithImplicitRequiredKey() throws Exception { + @Test + void testValidateOptionalWithImplicitRequiredKey() { validator.setOptionalKeys(new String[] { "name", "value" }); - validator.validate(new JobParametersBuilder().addString("foo", "bar").toJobParameters()); + JobParameters jobParameters = new JobParametersBuilder().addString("foo", "bar").toJobParameters(); + assertThrows(JobParametersInvalidException.class, () -> validator.validate(jobParameters)); } @Test - public void testValidateOptionalWithExplicitRequiredKey() throws Exception { + void testValidateOptionalWithExplicitRequiredKey() throws Exception { validator.setOptionalKeys(new String[] { "name", "value" }); validator.setRequiredKeys(new String[] { "foo" }); validator.validate(new JobParametersBuilder().addString("foo", "bar").toJobParameters()); } - @Test(expected = IllegalStateException.class) - public void testOptionalValuesAlsoRequired() throws Exception { + @Test + void testOptionalValuesAlsoRequired() { validator.setOptionalKeys(new String[] { "name", "value" }); validator.setRequiredKeys(new String[] { "foo", "value" }); - validator.afterPropertiesSet(); + assertThrows(IllegalStateException.class, validator::afterPropertiesSet); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/job/ExtendedAbstractJobTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/job/ExtendedAbstractJobTests.java index b151041ddb..e76f0e86d5 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/job/ExtendedAbstractJobTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/job/ExtendedAbstractJobTests.java @@ -15,8 +15,8 @@ */ package org.springframework.batch.core.job; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobExecutionException; @@ -37,25 +37,25 @@ import java.util.Collections; import java.util.Date; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Dave Syer * @author Mahmoud Ben Hassine * */ -public class ExtendedAbstractJobTests { +class ExtendedAbstractJobTests { private AbstractJob job; private JobRepository jobRepository; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { EmbeddedDatabase embeddedDatabase = new EmbeddedDatabaseBuilder() .addScript("/org/springframework/batch/core/schema-drop-hsqldb.sql") .addScript("/org/springframework/batch/core/schema-hsqldb.sql").build(); @@ -71,7 +71,7 @@ public void setUp() throws Exception { * Test method for {@link org.springframework.batch.core.job.AbstractJob#getName()}. */ @Test - public void testGetName() { + void testGetName() { job = new StubJob(); assertNull(job.getName()); } @@ -82,7 +82,7 @@ public void testGetName() { * . */ @Test - public void testSetBeanName() { + void testSetBeanName() { job.setBeanName("foo"); assertEquals("job", job.getName()); } @@ -93,7 +93,7 @@ public void testSetBeanName() { * . */ @Test - public void testSetBeanNameWithNullName() { + void testSetBeanNameWithNullName() { job = new StubJob(null, null); assertEquals(null, job.getName()); job.setBeanName("foo"); @@ -105,39 +105,34 @@ public void testSetBeanNameWithNullName() { * {@link org.springframework.batch.core.job.AbstractJob#setRestartable(boolean)} . */ @Test - public void testSetRestartable() { + void testSetRestartable() { assertTrue(job.isRestartable()); job.setRestartable(false); assertFalse(job.isRestartable()); } @Test - public void testToString() throws Exception { + void testToString() { String value = job.toString(); - assertTrue("Should contain name: " + value, value.indexOf("name=") >= 0); + assertTrue(value.contains("name="), "Should contain name: " + value); } @Test - public void testAfterPropertiesSet() throws Exception { + void testAfterPropertiesSet() { job.setJobRepository(null); - try { - job.afterPropertiesSet(); - fail(); - } - catch (IllegalArgumentException e) { - assertTrue(e.getMessage().contains("JobRepository")); - } + Exception exception = assertThrows(IllegalArgumentException.class, () -> job.afterPropertiesSet()); + assertTrue(exception.getMessage().contains("JobRepository")); } @Test - public void testValidatorWithNotNullParameters() throws Exception { + void testValidatorWithNotNullParameters() throws Exception { JobExecution execution = jobRepository.createJobExecution("job", new JobParameters()); job.execute(execution); // Should be free of side effects } @Test - public void testSetValidator() throws Exception { + void testSetValidator() throws Exception { job.setJobParametersValidator(new DefaultJobParametersValidator() { @Override public void validate(@Nullable JobParameters parameters) throws JobParametersInvalidException { @@ -149,14 +144,14 @@ public void validate(@Nullable JobParameters parameters) throws JobParametersInv assertEquals(BatchStatus.FAILED, execution.getStatus()); assertEquals("FOO", execution.getFailureExceptions().get(0).getMessage()); String description = execution.getExitStatus().getExitDescription(); - assertTrue("Wrong description: " + description, description.contains("FOO")); + assertTrue(description.contains("FOO"), "Wrong description: " + description); } /** * Runs the step and persists job execution context. */ @Test - public void testHandleStep() throws Exception { + void testHandleStep() throws Exception { class StubStep extends StepSupport { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/job/SimpleJobFailureTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/job/SimpleJobFailureTests.java index 1a5419056e..9ff4f52099 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/job/SimpleJobFailureTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/job/SimpleJobFailureTests.java @@ -15,12 +15,12 @@ */ package org.springframework.batch.core.job; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInterruptedException; @@ -43,14 +43,14 @@ * @author Mahmoud Ben Hassine * */ -public class SimpleJobFailureTests { +class SimpleJobFailureTests { - private SimpleJob job = new SimpleJob("job"); + private final SimpleJob job = new SimpleJob("job"); private JobExecution execution; - @Before - public void init() throws Exception { + @BeforeEach + void init() throws Exception { EmbeddedDatabase embeddedDatabase = new EmbeddedDatabaseBuilder() .addScript("/org/springframework/batch/core/schema-drop-hsqldb.sql") .addScript("/org/springframework/batch/core/schema-hsqldb.sql").build(); @@ -64,14 +64,14 @@ public void init() throws Exception { } @Test - public void testStepFailure() throws Exception { + void testStepFailure() { job.setSteps(Arrays.asList(new StepSupport("step"))); job.execute(execution); assertEquals(BatchStatus.FAILED, execution.getStatus()); } @Test - public void testStepStatusUnknown() throws Exception { + void testStepStatusUnknown() { job.setSteps(Arrays.asList(new StepSupport("step1") { @Override public void execute(StepExecution stepExecution) diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/job/SimpleJobTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/job/SimpleJobTests.java index 5f509194f7..76adb1d769 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/job/SimpleJobTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/job/SimpleJobTests.java @@ -27,9 +27,9 @@ import io.micrometer.core.instrument.Tag; import io.micrometer.core.instrument.Tags; import io.micrometer.core.tck.MeterRegistryAssert; -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.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; @@ -53,12 +53,12 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; /** @@ -68,13 +68,13 @@ * @author Will Schipp * @author Mahmoud Ben Hassine */ -public class SimpleJobTests { +class SimpleJobTests { private JobRepository jobRepository; private JobExplorer jobExplorer; - private List list = new ArrayList<>(); + private final List list = new ArrayList<>(); private JobInstance jobInstance; @@ -88,12 +88,12 @@ public class SimpleJobTests { private StubStep step2; - private JobParameters jobParameters = new JobParameters(); + private final JobParameters jobParameters = new JobParameters(); private SimpleJob job; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { EmbeddedDatabase embeddedDatabase = new EmbeddedDatabaseBuilder() .addScript("/org/springframework/batch/core/schema-drop-hsqldb.sql") .addScript("/org/springframework/batch/core/schema-hsqldb.sql").generateUniqueName(true).build(); @@ -143,7 +143,7 @@ public void run() { * Test method for {@link SimpleJob#setSteps(java.util.List)}. */ @Test - public void testSetSteps() { + void testSetSteps() { job.setSteps(Collections.singletonList((Step) new StepSupport("step"))); job.execute(jobExecution); assertEquals(1, jobExecution.getStepExecutions().size()); @@ -153,7 +153,7 @@ public void testSetSteps() { * Test method for {@link SimpleJob#setSteps(java.util.List)}. */ @Test - public void testGetSteps() { + void testGetSteps() { assertEquals(2, job.getStepNames().size()); } @@ -161,7 +161,7 @@ public void testGetSteps() { * Test method for {@link SimpleJob#addStep(org.springframework.batch.core.Step)}. */ @Test - public void testAddStep() { + void testAddStep() { job.setSteps(Collections.emptyList()); job.addStep(new StepSupport("step")); job.execute(jobExecution); @@ -170,7 +170,7 @@ public void testAddStep() { // Test to ensure the exit status returned by the last step is returned @Test - public void testExitStatusReturned() throws JobExecutionException { + void testExitStatusReturned() { final ExitStatus customStatus = new ExitStatus("test"); @@ -204,7 +204,7 @@ public boolean isAllowStartIfComplete() { } @Test - public void testRunNormally() throws Exception { + void testRunNormally() { step1.setStartLimit(5); step2.setStartLimit(5); job.execute(jobExecution); @@ -222,13 +222,13 @@ public void testRunNormally() throws Exception { Tag.of("spring.batch.job.name", "testJob"), Tag.of("spring.batch.job.status", "COMPLETED"))); } - @After - public void cleanup() { + @AfterEach + void cleanup() { Metrics.globalRegistry.clear(); } @Test - public void testRunNormallyWithListener() throws Exception { + void testRunNormallyWithListener() { job.setJobExecutionListeners(new JobExecutionListener[] { new JobExecutionListener() { @Override public void beforeJob(JobExecution jobExecution) { @@ -245,7 +245,7 @@ public void afterJob(JobExecution jobExecution) { } @Test - public void testRunWithSimpleStepExecutor() throws Exception { + void testRunWithSimpleStepExecutor() { job.setJobRepository(jobRepository); // do not set StepExecutorFactory... @@ -258,7 +258,7 @@ public void testRunWithSimpleStepExecutor() throws Exception { } @Test - public void testExecutionContextIsSet() throws Exception { + void testExecutionContextIsSet() { testRunNormally(); assertEquals(jobInstance, jobExecution.getJobInstance()); assertEquals(2, jobExecution.getStepExecutions().size()); @@ -267,7 +267,7 @@ public void testExecutionContextIsSet() throws Exception { } @Test - public void testInterrupted() throws Exception { + void testInterrupted() { step1.setStartLimit(5); step2.setStartLimit(5); final JobInterruptedException exception = new JobInterruptedException("Interrupt!"); @@ -280,7 +280,7 @@ public void testInterrupted() throws Exception { } @Test - public void testInterruptedAfterUnknownStatus() throws Exception { + void testInterruptedAfterUnknownStatus() { step1.setStartLimit(5); step2.setStartLimit(5); final JobInterruptedException exception = new JobInterruptedException("Interrupt!", BatchStatus.UNKNOWN); @@ -293,7 +293,7 @@ public void testInterruptedAfterUnknownStatus() throws Exception { } @Test - public void testFailed() throws Exception { + void testFailed() { step1.setStartLimit(5); step2.setStartLimit(5); final RuntimeException exception = new RuntimeException("Foo!"); @@ -308,7 +308,7 @@ public void testFailed() throws Exception { } @Test - public void testFailedWithListener() throws Exception { + void testFailedWithListener() { job.setJobExecutionListeners(new JobExecutionListener[] { new JobExecutionListener() { @Override public void afterJob(JobExecution jobExecution) { @@ -326,7 +326,7 @@ public void afterJob(JobExecution jobExecution) { } @Test - public void testFailedWithError() throws Exception { + void testFailedWithError() { step1.setStartLimit(5); step2.setStartLimit(5); final Error exception = new Error("Foo!"); @@ -340,7 +340,7 @@ public void testFailedWithError() throws Exception { } @Test - public void testStepShouldNotStart() throws Exception { + void testStepShouldNotStart() { // Start policy will return false, keeping the step from being started. step1.setStartLimit(0); @@ -348,12 +348,11 @@ public void testStepShouldNotStart() throws Exception { assertEquals(1, jobExecution.getFailureExceptions().size()); Throwable ex = jobExecution.getFailureExceptions().get(0); - assertTrue("Wrong message in exception: " + ex.getMessage(), - ex.getMessage().indexOf("start limit exceeded") >= 0); + assertTrue(ex.getMessage().contains("start limit exceeded"), "Wrong message in exception: " + ex.getMessage()); } @Test - public void testStepAlreadyComplete() throws Exception { + void testStepAlreadyComplete() throws Exception { stepExecution1.setStatus(BatchStatus.COMPLETED); jobRepository.add(stepExecution1); jobExecution.setEndTime(new Date()); @@ -366,7 +365,7 @@ public void testStepAlreadyComplete() throws Exception { } @Test - public void testStepAlreadyCompleteInSameExecution() throws Exception { + void testStepAlreadyCompleteInSameExecution() throws Exception { List steps = new ArrayList<>(); steps.add(step1); steps.add(step2); @@ -383,17 +382,17 @@ public void testStepAlreadyCompleteInSameExecution() throws Exception { } @Test - public void testNoSteps() throws Exception { + void testNoSteps() { job.setSteps(new ArrayList<>()); job.execute(jobExecution); ExitStatus exitStatus = jobExecution.getExitStatus(); - assertTrue("Wrong message in execution: " + exitStatus, - exitStatus.getExitDescription().indexOf("no steps configured") >= 0); + assertTrue(exitStatus.getExitDescription().contains("no steps configured"), + "Wrong message in execution: " + exitStatus); } @Test - public void testRestart() throws Exception { + void testRestart() throws Exception { step1.setAllowStartIfComplete(true); final RuntimeException exception = new RuntimeException("Foo!"); step2.setProcessException(exception); @@ -411,7 +410,7 @@ public void testRestart() throws Exception { } @Test - public void testInterruptWithListener() throws Exception { + void testInterruptWithListener() { step1.setProcessException(new JobInterruptedException("job interrupted!")); JobExecutionListener listener = mock(JobExecutionListener.class); @@ -429,7 +428,7 @@ public void testInterruptWithListener() throws Exception { * Execution context should be restored on restart. */ @Test - public void testRestartAndExecutionContextRestored() throws Exception { + void testRestartAndExecutionContextRestored() throws Exception { job.setRestartable(true); @@ -458,7 +457,7 @@ public void testRestartAndExecutionContextRestored() throws Exception { } @Test - public void testGetStepExists() { + void testGetStepExists() { step1 = new StubStep("step1", jobRepository); step2 = new StubStep("step2", jobRepository); job.setSteps(Arrays.asList(new Step[] { step1, step2 })); @@ -468,7 +467,7 @@ public void testGetStepExists() { } @Test - public void testGetStepNotExists() { + void testGetStepNotExists() { step1 = new StubStep("step1", jobRepository); step2 = new StubStep("step2", jobRepository); job.setSteps(Arrays.asList(new Step[] { step1, step2 })); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/job/SimpleStepHandlerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/job/SimpleStepHandlerTests.java index 43e06e4662..5daaac3223 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/job/SimpleStepHandlerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/job/SimpleStepHandlerTests.java @@ -16,10 +16,11 @@ package org.springframework.batch.core.job; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; @@ -38,7 +39,7 @@ * @author Mahmoud Ben Hassine * */ -public class SimpleStepHandlerTests { +class SimpleStepHandlerTests { private JobRepository jobRepository; @@ -46,8 +47,8 @@ public class SimpleStepHandlerTests { private SimpleStepHandler stepHandler; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { EmbeddedDatabase embeddedDatabase = new EmbeddedDatabaseBuilder() .addScript("/org/springframework/batch/core/schema-drop-hsqldb.sql") .addScript("/org/springframework/batch/core/schema-hsqldb.sql").build(); @@ -61,22 +62,14 @@ public void setUp() throws Exception { stepHandler.afterPropertiesSet(); } - /** - * Test method for {@link SimpleStepHandler#afterPropertiesSet()}. - */ - @Test(expected = IllegalStateException.class) - public void testAfterPropertiesSet() throws Exception { + @Test + void testAfterPropertiesSet() { SimpleStepHandler stepHandler = new SimpleStepHandler(); - stepHandler.afterPropertiesSet(); + assertThrows(IllegalStateException.class, stepHandler::afterPropertiesSet); } - /** - * Test method for - * {@link SimpleStepHandler#handleStep(org.springframework.batch.core.Step, org.springframework.batch.core.JobExecution)} - * . - */ @Test - public void testHandleStep() throws Exception { + void testHandleStep() throws Exception { StepExecution stepExecution = stepHandler.handleStep(new StubStep("step"), jobExecution); assertEquals(BatchStatus.COMPLETED, stepExecution.getStatus()); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/job/builder/FlowBuilderTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/job/builder/FlowBuilderTests.java index 4ad5460535..cf92a3cc16 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/job/builder/FlowBuilderTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/job/builder/FlowBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2022 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. @@ -17,7 +17,7 @@ import java.util.Iterator; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; @@ -33,7 +33,7 @@ import org.springframework.batch.core.step.JobRepositorySupport; import org.springframework.batch.core.step.StepSupport; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Dave Syer @@ -41,10 +41,10 @@ * @author Mahmoud Ben Hassine * */ -public class FlowBuilderTests { +class FlowBuilderTests { @Test - public void test() throws Exception { + void test() throws Exception { FlowBuilder builder = new FlowBuilder<>("flow"); JobRepository jobRepository = new JobRepositorySupport(); JobExecution execution = jobRepository.createJobExecution("foo", new JobParameters()); @@ -57,7 +57,7 @@ public void execute(StepExecution stepExecution) } @Test - public void testTransitionOrdering() throws Exception { + void testTransitionOrdering() throws Exception { FlowBuilder builder = new FlowBuilder<>("transitionsFlow"); JobRepository jobRepository = new JobRepositorySupport(); JobExecution execution = jobRepository.createJobExecution("foo", new JobParameters()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/job/builder/FlowJobBuilderTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/job/builder/FlowJobBuilderTests.java index 075f2aa583..7feb030a20 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/job/builder/FlowJobBuilderTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/job/builder/FlowJobBuilderTests.java @@ -19,10 +19,10 @@ import javax.sql.DataSource; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.Job; @@ -61,13 +61,13 @@ * @author Mahmoud Ben Hassine * */ -public class FlowJobBuilderTests { +class FlowJobBuilderTests { private JobRepository jobRepository; private JobExecution execution; - private StepSupport step1 = new StepSupport("step1") { + private final StepSupport step1 = new StepSupport("step1") { @Override public void execute(StepExecution stepExecution) throws JobInterruptedException, UnexpectedJobExecutionException { @@ -77,7 +77,7 @@ public void execute(StepExecution stepExecution) } }; - private StepSupport fails = new StepSupport("fails") { + private final StepSupport fails = new StepSupport("fails") { @Override public void execute(StepExecution stepExecution) throws JobInterruptedException, UnexpectedJobExecutionException { @@ -87,7 +87,7 @@ public void execute(StepExecution stepExecution) } }; - private StepSupport step2 = new StepSupport("step2") { + private final StepSupport step2 = new StepSupport("step2") { @Override public void execute(StepExecution stepExecution) throws JobInterruptedException, UnexpectedJobExecutionException { @@ -97,7 +97,7 @@ public void execute(StepExecution stepExecution) } }; - private StepSupport step3 = new StepSupport("step3") { + private final StepSupport step3 = new StepSupport("step3") { @Override public void execute(StepExecution stepExecution) throws JobInterruptedException, UnexpectedJobExecutionException { @@ -107,8 +107,8 @@ public void execute(StepExecution stepExecution) } }; - @Before - public void init() throws Exception { + @BeforeEach + void init() throws Exception { EmbeddedDatabase embeddedDatabase = new EmbeddedDatabaseBuilder() .addScript("/org/springframework/batch/core/schema-drop-hsqldb.sql") .addScript("/org/springframework/batch/core/schema-hsqldb.sql").build(); @@ -121,7 +121,7 @@ public void init() throws Exception { } @Test - public void testBuildOnOneLine() throws Exception { + void testBuildOnOneLine() { FlowJobBuilder builder = new JobBuilder("flow").repository(jobRepository).start(step1).on("COMPLETED").to(step2) .end().preventRestart(); builder.build().execute(execution); @@ -130,7 +130,7 @@ public void testBuildOnOneLine() throws Exception { } @Test - public void testBuildSingleFlow() throws Exception { + void testBuildSingleFlow() { Flow flow = new FlowBuilder("subflow").from(step1).next(step2).build(); FlowJobBuilder builder = new JobBuilder("flow").repository(jobRepository).start(flow).end().preventRestart(); builder.build().execute(execution); @@ -139,7 +139,7 @@ public void testBuildSingleFlow() throws Exception { } @Test - public void testBuildOverTwoLines() throws Exception { + void testBuildOverTwoLines() { FlowJobBuilder builder = new JobBuilder("flow").repository(jobRepository).start(step1).on("COMPLETED").to(step2) .end(); builder.preventRestart(); @@ -149,7 +149,7 @@ public void testBuildOverTwoLines() throws Exception { } @Test - public void testBuildSubflow() throws Exception { + void testBuildSubflow() { Flow flow = new FlowBuilder("subflow").from(step1).end(); JobFlowBuilder builder = new JobBuilder("flow").repository(jobRepository).start(flow); builder.on("COMPLETED").to(step2); @@ -159,7 +159,7 @@ public void testBuildSubflow() throws Exception { } @Test - public void testBuildSplit() throws Exception { + void testBuildSplit() { Flow flow = new FlowBuilder("subflow").from(step1).end(); SimpleJobBuilder builder = new JobBuilder("flow").repository(jobRepository).start(step2); builder.split(new SimpleAsyncTaskExecutor()).add(flow).end(); @@ -169,7 +169,7 @@ public void testBuildSplit() throws Exception { } @Test - public void testBuildSplitUsingStartAndAdd_BATCH_2346() throws Exception { + void testBuildSplitUsingStartAndAdd_BATCH_2346() { Flow subflow1 = new FlowBuilder("subflow1").from(step2).end(); Flow subflow2 = new FlowBuilder("subflow2").from(step3).end(); Flow splitflow = new FlowBuilder("splitflow").start(subflow1).split(new SimpleAsyncTaskExecutor()) @@ -182,7 +182,7 @@ public void testBuildSplitUsingStartAndAdd_BATCH_2346() throws Exception { } @Test - public void testBuildSplit_BATCH_2282() throws Exception { + void testBuildSplit_BATCH_2282() { Flow flow1 = new FlowBuilder("subflow1").from(step1).end(); Flow flow2 = new FlowBuilder("subflow2").from(step2).end(); Flow splitFlow = new FlowBuilder("splitflow").split(new SimpleAsyncTaskExecutor()).add(flow1, flow2) @@ -194,7 +194,7 @@ public void testBuildSplit_BATCH_2282() throws Exception { } @Test - public void testBuildDecision() throws Exception { + void testBuildDecision() { JobExecutionDecider decider = new JobExecutionDecider() { private int count = 0; @@ -213,7 +213,7 @@ public FlowExecutionStatus decide(JobExecution jobExecution, @Nullable StepExecu } @Test - public void testBuildWithIntermediateSimpleJob() throws Exception { + void testBuildWithIntermediateSimpleJob() { SimpleJobBuilder builder = new JobBuilder("flow").repository(jobRepository).start(step1); builder.on("COMPLETED").to(step2).end(); builder.preventRestart(); @@ -223,7 +223,7 @@ public void testBuildWithIntermediateSimpleJob() throws Exception { } @Test - public void testBuildWithIntermediateSimpleJobTwoSteps() throws Exception { + void testBuildWithIntermediateSimpleJobTwoSteps() { SimpleJobBuilder builder = new JobBuilder("flow").repository(jobRepository).start(step1).next(step2); builder.on("FAILED").to(step3).end(); builder.build().execute(execution); @@ -232,7 +232,7 @@ public void testBuildWithIntermediateSimpleJobTwoSteps() throws Exception { } @Test - public void testBuildWithCustomEndState() throws Exception { + void testBuildWithCustomEndState() { SimpleJobBuilder builder = new JobBuilder("flow").repository(jobRepository).start(step1); builder.on("COMPLETED").end("FOO"); builder.preventRestart(); @@ -243,7 +243,7 @@ public void testBuildWithCustomEndState() throws Exception { } @Test - public void testBuildWithStop() throws Exception { + void testBuildWithStop() { SimpleJobBuilder builder = new JobBuilder("flow").repository(jobRepository).start(step1); builder.on("COMPLETED").stop(); builder.preventRestart(); @@ -254,7 +254,7 @@ public void testBuildWithStop() throws Exception { } @Test - public void testBuildWithStopAndRestart() throws Exception { + void testBuildWithStopAndRestart() throws Exception { SimpleJobBuilder builder = new JobBuilder("flow").repository(jobRepository).start(fails); builder.on("FAILED").stopAndRestart(step2); Job job = builder.build(); @@ -269,7 +269,7 @@ public void testBuildWithStopAndRestart() throws Exception { } @Test - public void testBuildWithJobScopedStep() throws Exception { + void testBuildWithJobScopedStep() throws Exception { // given ApplicationContext context = new AnnotationConfigApplicationContext(JobConfiguration.class); JobLauncher jobLauncher = context.getBean(JobLauncher.class); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/job/builder/JobBuilderTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/job/builder/JobBuilderTests.java index 406b39bbb4..5cd6f159f9 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/job/builder/JobBuilderTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/job/builder/JobBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2021 the original author or authors. + * Copyright 2020-2022 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. @@ -17,8 +17,7 @@ import javax.sql.DataSource; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.Job; @@ -38,15 +37,15 @@ import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Mahmoud Ben Hassine */ -public class JobBuilderTests { +class JobBuilderTests { @Test - public void testListeners() throws Exception { + void testListeners() throws Exception { // given ApplicationContext context = new AnnotationConfigApplicationContext(MyJobConfiguration.class); JobLauncher jobLauncher = context.getBean(JobLauncher.class); @@ -56,7 +55,7 @@ public void testListeners() throws Exception { JobExecution jobExecution = jobLauncher.run(job, new JobParameters()); // then - Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); + assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); assertEquals(1, AnnotationBasedJobExecutionListener.beforeJobCount); assertEquals(1, AnnotationBasedJobExecutionListener.afterJobCount); assertEquals(1, InterfaceBasedJobExecutionListener.beforeJobCount); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/FlowExecutionExceptionTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/FlowExecutionExceptionTests.java index 8f281cf697..845a259b68 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/FlowExecutionExceptionTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/FlowExecutionExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,22 +15,21 @@ */ package org.springframework.batch.core.job.flow; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; -import org.springframework.batch.core.job.flow.FlowExecutionException; +import org.junit.jupiter.api.Test; /** * @author Dave Syer * */ -public class FlowExecutionExceptionTests { +class FlowExecutionExceptionTests { /** * Test method for {@link FlowExecutionException#FlowExecutionException(String)}. */ @Test - public void testFlowExecutionExceptionString() { + void testFlowExecutionExceptionString() { FlowExecutionException exception = new FlowExecutionException("foo"); assertEquals("foo", exception.getMessage()); } @@ -40,7 +39,7 @@ public void testFlowExecutionExceptionString() { * {@link FlowExecutionException#FlowExecutionException(String, Throwable)}. */ @Test - public void testFlowExecutionExceptionStringThrowable() { + void testFlowExecutionExceptionStringThrowable() { FlowExecutionException exception = new FlowExecutionException("foo", new RuntimeException("bar")); assertEquals("foo", exception.getMessage()); assertEquals("bar", exception.getCause().getMessage()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/FlowExecutionTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/FlowExecutionTests.java index 81056435af..be6a108888 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/FlowExecutionTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/FlowExecutionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,63 +15,62 @@ */ package org.springframework.batch.core.job.flow; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; -import org.springframework.batch.core.job.flow.FlowExecution; +import org.junit.jupiter.api.Test; /** * @author Dave Syer * */ -public class FlowExecutionTests { +class FlowExecutionTests { @Test - public void testBasicProperties() throws Exception { + void testBasicProperties() { FlowExecution execution = new FlowExecution("foo", new FlowExecutionStatus("BAR")); assertEquals("foo", execution.getName()); assertEquals("BAR", execution.getStatus().getName()); } @Test - public void testAlphaOrdering() throws Exception { + void testAlphaOrdering() { FlowExecution first = new FlowExecution("foo", new FlowExecutionStatus("BAR")); FlowExecution second = new FlowExecution("foo", new FlowExecutionStatus("SPAM")); - assertTrue("Should be negative", first.compareTo(second) < 0); - assertTrue("Should be positive", second.compareTo(first) > 0); + assertTrue(first.compareTo(second) < 0, "Should be negative"); + assertTrue(second.compareTo(first) > 0, "Should be positive"); } @Test - public void testEnumOrdering() throws Exception { + void testEnumOrdering() { FlowExecution first = new FlowExecution("foo", FlowExecutionStatus.COMPLETED); FlowExecution second = new FlowExecution("foo", FlowExecutionStatus.FAILED); - assertTrue("Should be negative", first.compareTo(second) < 0); - assertTrue("Should be positive", second.compareTo(first) > 0); + assertTrue(first.compareTo(second) < 0, "Should be negative"); + assertTrue(second.compareTo(first) > 0, "Should be positive"); } @Test - public void testEnumStartsWithOrdering() throws Exception { + void testEnumStartsWithOrdering() { FlowExecution first = new FlowExecution("foo", new FlowExecutionStatus("COMPLETED.BAR")); FlowExecution second = new FlowExecution("foo", new FlowExecutionStatus("FAILED.FOO")); - assertTrue("Should be negative", first.compareTo(second) < 0); - assertTrue("Should be positive", second.compareTo(first) > 0); + assertTrue(first.compareTo(second) < 0, "Should be negative"); + assertTrue(second.compareTo(first) > 0, "Should be positive"); } @Test - public void testEnumStartsWithAlphaOrdering() throws Exception { + void testEnumStartsWithAlphaOrdering() { FlowExecution first = new FlowExecution("foo", new FlowExecutionStatus("COMPLETED.BAR")); FlowExecution second = new FlowExecution("foo", new FlowExecutionStatus("COMPLETED.FOO")); - assertTrue("Should be negative", first.compareTo(second) < 0); - assertTrue("Should be positive", second.compareTo(first) > 0); + assertTrue(first.compareTo(second) < 0, "Should be negative"); + assertTrue(second.compareTo(first) > 0, "Should be positive"); } @Test - public void testEnumAndAlpha() throws Exception { + void testEnumAndAlpha() { FlowExecution first = new FlowExecution("foo", new FlowExecutionStatus("ZZZZZ")); FlowExecution second = new FlowExecution("foo", new FlowExecutionStatus("FAILED.FOO")); - assertTrue("Should be negative", first.compareTo(second) < 0); - assertTrue("Should be positive", second.compareTo(first) > 0); + assertTrue(first.compareTo(second) < 0, "Should be negative"); + assertTrue(second.compareTo(first) > 0, "Should be positive"); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/FlowJobFailureTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/FlowJobFailureTests.java index c1c3adb6f7..6f52aba25e 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/FlowJobFailureTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/FlowJobFailureTests.java @@ -15,13 +15,13 @@ */ package org.springframework.batch.core.job.flow; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; 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.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; @@ -48,14 +48,14 @@ * @author Mahmoud Ben Hassine * */ -public class FlowJobFailureTests { +class FlowJobFailureTests { private FlowJob job = new FlowJob(); private JobExecution execution; - @Before - public void init() throws Exception { + @BeforeEach + void init() throws Exception { EmbeddedDatabase embeddedDatabase = new EmbeddedDatabaseBuilder() .addScript("/org/springframework/batch/core/schema-drop-hsqldb.sql") .addScript("/org/springframework/batch/core/schema-hsqldb.sql").build(); @@ -69,7 +69,7 @@ public void init() throws Exception { } @Test - public void testStepFailure() throws Exception { + void testStepFailure() throws Exception { SimpleFlow flow = new SimpleFlow("job"); List transitions = new ArrayList<>(); StepState step = new StepState(new StepSupport("step")); @@ -85,7 +85,7 @@ public void testStepFailure() throws Exception { } @Test - public void testStepStatusUnknown() throws Exception { + void testStepStatusUnknown() throws Exception { SimpleFlow flow = new SimpleFlow("job"); List transitions = new ArrayList<>(); StepState step = new StepState(new StepSupport("step") { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/FlowJobTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/FlowJobTests.java index eab3419fe4..40cbe08db5 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/FlowJobTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/FlowJobTests.java @@ -15,8 +15,8 @@ */ package org.springframework.batch.core.job.flow; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; @@ -48,10 +48,10 @@ import java.util.Collections; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Dave Syer @@ -61,7 +61,7 @@ */ public class FlowJobTests { - private FlowJob job = new FlowJob(); + private final FlowJob job = new FlowJob(); private JobExecution jobExecution; @@ -71,8 +71,8 @@ public class FlowJobTests { private boolean fail = false; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { EmbeddedDatabase embeddedDatabase = new EmbeddedDatabaseBuilder() .addScript("/org/springframework/batch/core/schema-drop-hsqldb.sql") .addScript("/org/springframework/batch/core/schema-hsqldb.sql").build(); @@ -91,7 +91,7 @@ public void setUp() throws Exception { } @Test - public void testGetSteps() throws Exception { + void testGetSteps() throws Exception { SimpleFlow flow = new SimpleFlow("job"); List transitions = new ArrayList<>(); transitions.add(StateTransition.createStateTransition(new StepState(new StubStep("step1")), "step2")); @@ -105,7 +105,7 @@ public void testGetSteps() throws Exception { } @Test - public void testTwoSteps() throws Exception { + void testTwoSteps() throws Exception { SimpleFlow flow = new SimpleFlow("job"); List transitions = new ArrayList<>(); transitions.add(StateTransition.createStateTransition(new StepState(new StubStep("step1")), "step2")); @@ -124,7 +124,7 @@ public void testTwoSteps() throws Exception { } @Test - public void testFailedStep() throws Exception { + void testFailedStep() throws Exception { SimpleFlow flow = new SimpleFlow("job"); List transitions = new ArrayList<>(); transitions.add( @@ -145,7 +145,7 @@ public void testFailedStep() throws Exception { } @Test - public void testFailedStepRestarted() throws Exception { + void testFailedStepRestarted() throws Exception { SimpleFlow flow = new SimpleFlow("job"); List transitions = new ArrayList<>(); transitions.add(StateTransition.createStateTransition(new StepState(new StubStep("step1")), "step2")); @@ -182,7 +182,7 @@ public FlowExecutionStatus handle(FlowExecutor executor) throws Exception { } @Test - public void testStoppingStep() throws Exception { + void testStoppingStep() throws Exception { SimpleFlow flow = new SimpleFlow("job"); List transitions = new ArrayList<>(); transitions.add(StateTransition.createStateTransition(new StepState(new StubStep("step1")), "step2")); @@ -203,7 +203,7 @@ public void testStoppingStep() throws Exception { } @Test - public void testInterrupted() throws Exception { + void testInterrupted() throws Exception { SimpleFlow flow = new SimpleFlow("job"); List transitions = new ArrayList<>(); transitions.add(StateTransition.createStateTransition(new StepState(new StubStep("step1") { @@ -226,7 +226,7 @@ public void execute(StepExecution stepExecution) throws JobInterruptedException } @Test - public void testUnknownStatusStopsJob() throws Exception { + void testUnknownStatusStopsJob() throws Exception { SimpleFlow flow = new SimpleFlow("job"); List transitions = new ArrayList<>(); transitions.add(StateTransition.createStateTransition(new StepState(new StubStep("step1") { @@ -251,7 +251,7 @@ public void execute(StepExecution stepExecution) throws JobInterruptedException } @Test - public void testInterruptedSplit() throws Exception { + void testInterruptedSplit() throws Exception { SimpleFlow flow = new SimpleFlow("job"); SimpleFlow flow1 = new SimpleFlow("flow1"); SimpleFlow flow2 = new SimpleFlow("flow2"); @@ -297,7 +297,7 @@ public void execute(StepExecution stepExecution) throws JobInterruptedException } @Test - public void testInterruptedException() throws Exception { + void testInterruptedException() throws Exception { SimpleFlow flow = new SimpleFlow("job"); List transitions = new ArrayList<>(); transitions.add(StateTransition.createStateTransition(new StepState(new StubStep("step1") { @@ -319,7 +319,7 @@ public void execute(StepExecution stepExecution) throws JobInterruptedException } @Test - public void testInterruptedSplitException() throws Exception { + void testInterruptedSplitException() throws Exception { SimpleFlow flow = new SimpleFlow("job"); SimpleFlow flow1 = new SimpleFlow("flow1"); SimpleFlow flow2 = new SimpleFlow("flow2"); @@ -354,7 +354,7 @@ public void execute(StepExecution stepExecution) throws JobInterruptedException } @Test - public void testEndStateStopped() throws Exception { + void testEndStateStopped() throws Exception { SimpleFlow flow = new SimpleFlow("job"); List transitions = new ArrayList<>(); transitions.add(StateTransition.createStateTransition(new StepState(new StubStep("step1")), "end")); @@ -394,7 +394,7 @@ public void testEndStateFailed() throws Exception { } @Test - public void testEndStateStoppedWithRestart() throws Exception { + void testEndStateStoppedWithRestart() throws Exception { SimpleFlow flow = new SimpleFlow("job"); List transitions = new ArrayList<>(); transitions.add(StateTransition.createStateTransition(new StepState(new StubStep("step1")), "end")); @@ -422,7 +422,7 @@ public void testEndStateStoppedWithRestart() throws Exception { } @Test - public void testBranching() throws Exception { + void testBranching() throws Exception { SimpleFlow flow = new SimpleFlow("job"); List transitions = new ArrayList<>(); StepState step1 = new StepState(new StubStep("step1")); @@ -449,7 +449,7 @@ public void testBranching() throws Exception { } @Test - public void testBasicFlow() throws Throwable { + void testBasicFlow() throws Throwable { SimpleFlow flow = new SimpleFlow("job"); List transitions = new ArrayList<>(); transitions.add(StateTransition.createStateTransition(new StepState(new StubStep("step")), "end0")); @@ -464,7 +464,7 @@ public void testBasicFlow() throws Throwable { } @Test - public void testDecisionFlow() throws Throwable { + void testDecisionFlow() throws Throwable { SimpleFlow flow = new SimpleFlow("job"); JobExecutionDecider decider = new JobExecutionDecider() { @@ -506,7 +506,7 @@ public FlowExecutionStatus decide(JobExecution jobExecution, @Nullable StepExecu } @Test - public void testDecisionFlowWithExceptionInDecider() throws Throwable { + void testDecisionFlowWithExceptionInDecider() throws Throwable { SimpleFlow flow = new SimpleFlow("job"); JobExecutionDecider decider = new JobExecutionDecider() { @@ -550,7 +550,7 @@ public FlowExecutionStatus decide(JobExecution jobExecution, @Nullable StepExecu } @Test - public void testGetStepExists() throws Exception { + void testGetStepExists() throws Exception { SimpleFlow flow = new SimpleFlow("job"); List transitions = new ArrayList<>(); transitions.add(StateTransition.createStateTransition(new StepState(new StubStep("step1")), "step2")); @@ -567,7 +567,7 @@ public void testGetStepExists() throws Exception { } @Test - public void testGetStepExistsWithPrefix() throws Exception { + void testGetStepExistsWithPrefix() throws Exception { SimpleFlow flow = new SimpleFlow("job"); List transitions = new ArrayList<>(); transitions.add(StateTransition.createStateTransition(new StepState("job.step", new StubStep("step")), "end0")); @@ -584,7 +584,7 @@ public void testGetStepExistsWithPrefix() throws Exception { } @Test - public void testGetStepNamesWithPrefix() throws Exception { + void testGetStepNamesWithPrefix() throws Exception { SimpleFlow flow = new SimpleFlow("job"); List transitions = new ArrayList<>(); transitions.add(StateTransition.createStateTransition(new StepState("job.step", new StubStep("step")), "end0")); @@ -599,7 +599,7 @@ public void testGetStepNamesWithPrefix() throws Exception { } @Test - public void testGetStepNotExists() throws Exception { + void testGetStepNotExists() throws Exception { SimpleFlow flow = new SimpleFlow("job"); List transitions = new ArrayList<>(); transitions.add(StateTransition.createStateTransition(new StepState(new StubStep("step1")), "step2")); @@ -615,7 +615,7 @@ public void testGetStepNotExists() throws Exception { } @Test - public void testGetStepNotStepState() throws Exception { + void testGetStepNotStepState() throws Exception { SimpleFlow flow = new SimpleFlow("job"); List transitions = new ArrayList<>(); transitions.add(StateTransition.createStateTransition(new StepState(new StubStep("step1")), "step2")); @@ -631,7 +631,7 @@ public void testGetStepNotStepState() throws Exception { } @Test - public void testGetStepNestedFlow() throws Exception { + void testGetStepNestedFlow() throws Exception { SimpleFlow nested = new SimpleFlow("nested"); List transitions = new ArrayList<>(); transitions.add(StateTransition.createStateTransition(new StepState(new StubStep("step2")), "end1")); @@ -655,7 +655,7 @@ public void testGetStepNestedFlow() throws Exception { } @Test - public void testGetStepSplitFlow() throws Exception { + void testGetStepSplitFlow() throws Exception { SimpleFlow flow = new SimpleFlow("job"); SimpleFlow flow1 = new SimpleFlow("flow1"); SimpleFlow flow2 = new SimpleFlow("flow2"); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/FlowStepTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/FlowStepTests.java index 4c0a3d8e7e..9fcc7d19c0 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/FlowStepTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/FlowStepTests.java @@ -16,14 +16,14 @@ package org.springframework.batch.core.job.flow; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayList; 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.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; @@ -46,14 +46,14 @@ * @author Mahmoud Ben Hassine * */ -public class FlowStepTests { +class FlowStepTests { private JobRepository jobRepository; private JobExecution jobExecution; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { EmbeddedDatabase embeddedDatabase = new EmbeddedDatabaseBuilder() .addScript("/org/springframework/batch/core/schema-drop-hsqldb.sql") .addScript("/org/springframework/batch/core/schema-hsqldb.sql").build(); @@ -65,23 +65,15 @@ public void setUp() throws Exception { jobExecution = jobRepository.createJobExecution("job", new JobParameters()); } - /** - * Test method for - * {@link org.springframework.batch.core.job.flow.FlowStep#afterPropertiesSet()}. - */ - @Test(expected = IllegalStateException.class) - public void testAfterPropertiesSet() throws Exception { + @Test + void testAfterPropertiesSet() { FlowStep step = new FlowStep(); step.setJobRepository(jobRepository); - step.afterPropertiesSet(); + assertThrows(IllegalStateException.class, step::afterPropertiesSet); } - /** - * Test method for - * {@link org.springframework.batch.core.job.flow.FlowStep#doExecute(org.springframework.batch.core.StepExecution)}. - */ @Test - public void testDoExecute() throws Exception { + void testDoExecute() throws Exception { FlowStep step = new FlowStep(); step.setJobRepository(jobRepository); @@ -113,7 +105,7 @@ public void testDoExecute() throws Exception { // BATCH-1620 @Test - public void testDoExecuteAndFail() throws Exception { + void testDoExecuteAndFail() throws Exception { FlowStep step = new FlowStep(); step.setJobRepository(jobRepository); @@ -145,12 +137,8 @@ public void testDoExecuteAndFail() throws Exception { } - /** - * Test method for - * {@link org.springframework.batch.core.job.flow.FlowStep#doExecute(org.springframework.batch.core.StepExecution)}. - */ @Test - public void testExecuteWithParentContext() throws Exception { + void testExecuteWithParentContext() throws Exception { FlowStep step = new FlowStep(); step.setJobRepository(jobRepository); @@ -209,19 +197,13 @@ public void execute(StepExecution stepExecution) throws JobInterruptedException } - /** - * @param jobExecution - * @param stepName - * @return the StepExecution corresponding to the specified step - */ private StepExecution getStepExecution(JobExecution jobExecution, String stepName) { for (StepExecution stepExecution : jobExecution.getStepExecutions()) { if (stepExecution.getStepName().equals(stepName)) { return stepExecution; } } - fail("No stepExecution found with name: [" + stepName + "]"); - return null; + throw new IllegalStateException("No stepExecution found with name: [" + stepName + "]"); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/support/DefaultStateTransitionComparatorTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/support/DefaultStateTransitionComparatorTests.java index 87f167c461..3bb7759a38 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/support/DefaultStateTransitionComparatorTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/support/DefaultStateTransitionComparatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013 the original author or authors. + * Copyright 2013-2022 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. @@ -15,34 +15,28 @@ */ package org.springframework.batch.core.job.flow.support; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Comparator; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.job.flow.State; import org.springframework.batch.core.job.flow.StateSupport; -public class DefaultStateTransitionComparatorTests { +class DefaultStateTransitionComparatorTests { - private State state = new StateSupport("state1"); + private final State state = new StateSupport("state1"); - private Comparator comparator; - - @Before - public void setUp() throws Exception { - comparator = new DefaultStateTransitionComparator(); - } + private final Comparator comparator = new DefaultStateTransitionComparator(); @Test - public void testSimpleOrderingEqual() { + void testSimpleOrderingEqual() { StateTransition transition = StateTransition.createStateTransition(state, "CONTIN???LE", "start"); assertEquals(0, comparator.compare(transition, transition)); } @Test - public void testSimpleOrderingMoreGeneral() { + void testSimpleOrderingMoreGeneral() { StateTransition transition = StateTransition.createStateTransition(state, "CONTIN???LE", "start"); StateTransition other = StateTransition.createStateTransition(state, "CONTINUABLE", "start"); assertEquals(1, comparator.compare(transition, other)); @@ -50,7 +44,7 @@ public void testSimpleOrderingMoreGeneral() { } @Test - public void testSimpleOrderingMostGeneral() { + void testSimpleOrderingMostGeneral() { StateTransition transition = StateTransition.createStateTransition(state, "*", "start"); StateTransition other = StateTransition.createStateTransition(state, "CONTINUABLE", "start"); assertEquals(1, comparator.compare(transition, other)); @@ -58,7 +52,7 @@ public void testSimpleOrderingMostGeneral() { } @Test - public void testSubstringAndWildcard() { + void testSubstringAndWildcard() { StateTransition transition = StateTransition.createStateTransition(state, "CONTIN*", "start"); StateTransition other = StateTransition.createStateTransition(state, "CONTINUABLE", "start"); assertEquals(1, comparator.compare(transition, other)); @@ -66,7 +60,7 @@ public void testSubstringAndWildcard() { } @Test - public void testSimpleOrderingMostToNextGeneral() { + void testSimpleOrderingMostToNextGeneral() { StateTransition transition = StateTransition.createStateTransition(state, "*", "start"); StateTransition other = StateTransition.createStateTransition(state, "C?", "start"); assertEquals(1, comparator.compare(transition, other)); @@ -74,7 +68,7 @@ public void testSimpleOrderingMostToNextGeneral() { } @Test - public void testSimpleOrderingAdjacent() { + void testSimpleOrderingAdjacent() { StateTransition transition = StateTransition.createStateTransition(state, "CON*", "start"); StateTransition other = StateTransition.createStateTransition(state, "CON?", "start"); assertEquals(1, comparator.compare(transition, other)); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/support/SimpleFlowTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/support/SimpleFlowTests.java index e11c3cfac9..bfb931457b 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/support/SimpleFlowTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/support/SimpleFlowTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2013 the original author or authors. + * Copyright 2006-2022 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. @@ -15,18 +15,18 @@ */ package org.springframework.batch.core.job.flow.support; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; 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.springframework.batch.core.ExitStatus; import org.springframework.batch.core.job.flow.FlowExecution; import org.springframework.batch.core.job.flow.FlowExecutionException; @@ -40,32 +40,31 @@ * @author Michael Minella * */ -public class SimpleFlowTests { +class SimpleFlowTests { protected SimpleFlow flow; protected FlowExecutor executor = new JobFlowExecutorSupport(); - @Before - public void setUp() { + @BeforeEach + void setUp() { flow = new SimpleFlow("job"); } - @Test(expected = IllegalArgumentException.class) - public void testEmptySteps() throws Exception { - flow.setStateTransitions(Collections.emptyList()); - flow.afterPropertiesSet(); + @Test + void testEmptySteps() { + flow.setStateTransitions(Collections.emptyList()); + assertThrows(IllegalArgumentException.class, flow::afterPropertiesSet); } - @Test(expected = IllegalArgumentException.class) - public void testNoNextStepSpecified() throws Exception { - flow.setStateTransitions( - Collections.singletonList(StateTransition.createStateTransition(new StateSupport("step"), "foo"))); - flow.afterPropertiesSet(); + @Test + void testNoNextStepSpecified() { + flow.setStateTransitions(List.of(StateTransition.createStateTransition(new StateSupport("step"), "foo"))); + assertThrows(IllegalArgumentException.class, flow::afterPropertiesSet); } @Test - public void testStepLoop() throws Exception { + void testStepLoop() throws Exception { flow.setStateTransitions( collect(StateTransition.createStateTransition(new StateSupport("step"), ExitStatus.FAILED.getExitCode(), "step"), StateTransition.createEndStateTransition(new StateSupport("step")))); @@ -75,15 +74,15 @@ public void testStepLoop() throws Exception { assertEquals("step", execution.getName()); } - @Test(expected = IllegalArgumentException.class) - public void testNoEndStep() throws Exception { - flow.setStateTransitions(Collections.singletonList(StateTransition - .createStateTransition(new StateSupport("step"), ExitStatus.FAILED.getExitCode(), "step"))); - flow.afterPropertiesSet(); + @Test + void testNoEndStep() { + flow.setStateTransitions(List.of(StateTransition.createStateTransition(new StateSupport("step"), + ExitStatus.FAILED.getExitCode(), "step"))); + assertThrows(IllegalArgumentException.class, flow::afterPropertiesSet); } @Test - public void testUnconnectedSteps() throws Exception { + void testUnconnectedSteps() throws Exception { flow.setStateTransitions(collect(StateTransition.createEndStateTransition(new StubState("step1")), StateTransition.createEndStateTransition(new StubState("step2")))); flow.afterPropertiesSet(); @@ -93,23 +92,17 @@ public void testUnconnectedSteps() throws Exception { } @Test - public void testNoMatchForNextStep() throws Exception { + void testNoMatchForNextStep() throws Exception { flow.setStateTransitions(collect(StateTransition.createStateTransition(new StubState("step1"), "FOO", "step2"), StateTransition.createEndStateTransition(new StubState("step2")))); flow.afterPropertiesSet(); - try { - flow.start(executor); - fail("Expected JobExecutionException"); - } - catch (FlowExecutionException e) { - // expected - String message = e.getMessage(); - assertTrue("Wrong message: " + message, message.toLowerCase().contains("next state not found")); - } + Exception exception = assertThrows(FlowExecutionException.class, () -> flow.start(executor)); + String message = exception.getMessage(); + assertTrue(message.toLowerCase().contains("next state not found"), "Wrong message: " + message); } @Test - public void testOneStep() throws Exception { + void testOneStep() throws Exception { flow.setStateTransitions( Collections.singletonList(StateTransition.createEndStateTransition(new StubState("step1")))); flow.afterPropertiesSet(); @@ -119,7 +112,7 @@ public void testOneStep() throws Exception { } @Test - public void testOneStepWithListenerCallsClose() throws Exception { + void testOneStepWithListenerCallsClose() throws Exception { flow.setStateTransitions( Collections.singletonList(StateTransition.createEndStateTransition(new StubState("step1")))); flow.afterPropertiesSet(); @@ -137,7 +130,7 @@ public void close(FlowExecution result) { } @Test - public void testExplicitStartStep() throws Exception { + void testExplicitStartStep() throws Exception { flow.setStateTransitions(collect( StateTransition.createStateTransition(new StubState("step"), ExitStatus.FAILED.getExitCode(), "step"), StateTransition.createEndStateTransition(new StubState("step")))); @@ -148,7 +141,7 @@ public void testExplicitStartStep() throws Exception { } @Test - public void testTwoSteps() throws Exception { + void testTwoSteps() throws Exception { flow.setStateTransitions(collect(StateTransition.createStateTransition(new StubState("step1"), "step2"), StateTransition.createEndStateTransition(new StubState("step2")))); flow.afterPropertiesSet(); @@ -158,7 +151,7 @@ public void testTwoSteps() throws Exception { } @Test - public void testResume() throws Exception { + void testResume() throws Exception { flow.setStateTransitions(collect(StateTransition.createStateTransition(new StubState("step1"), "step2"), StateTransition.createEndStateTransition(new StubState("step2")))); flow.afterPropertiesSet(); @@ -168,7 +161,7 @@ public void testResume() throws Exception { } @Test - public void testFailedStep() throws Exception { + void testFailedStep() throws Exception { flow.setStateTransitions(collect(StateTransition.createStateTransition(new StubState("step1") { @Override public FlowExecutionStatus handle(FlowExecutor executor) { @@ -182,7 +175,7 @@ public FlowExecutionStatus handle(FlowExecutor executor) { } @Test - public void testBranching() throws Exception { + void testBranching() throws Exception { flow.setStateTransitions(collect(StateTransition.createStateTransition(new StubState("step1"), "step2"), StateTransition.createStateTransition(new StubState("step1"), ExitStatus.COMPLETED.getExitCode(), "step3"), @@ -196,7 +189,7 @@ public void testBranching() throws Exception { } @Test - public void testGetStateExists() throws Exception { + void testGetStateExists() throws Exception { flow.setStateTransitions( Collections.singletonList(StateTransition.createEndStateTransition(new StubState("step1")))); flow.afterPropertiesSet(); @@ -206,7 +199,7 @@ public void testGetStateExists() throws Exception { } @Test - public void testGetStateDoesNotExist() throws Exception { + void testGetStateDoesNotExist() throws Exception { flow.setStateTransitions( Collections.singletonList(StateTransition.createEndStateTransition(new StubState("step1")))); flow.afterPropertiesSet(); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/support/StateTransitionTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/support/StateTransitionTests.java index e095a01997..b194b2a5ca 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/support/StateTransitionTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/support/StateTransitionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2013 the original author or authors. + * Copyright 2006-2022 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. @@ -15,10 +15,10 @@ */ package org.springframework.batch.core.job.flow.support; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.job.flow.State; import org.springframework.batch.core.job.flow.StateSupport; @@ -27,61 +27,61 @@ * @author Michael Minella * */ -public class StateTransitionTests { +class StateTransitionTests { State state = new StateSupport("state1"); @Test - public void testIsEnd() { + void testIsEnd() { StateTransition transition = StateTransition.createEndStateTransition(state, ""); assertTrue(transition.isEnd()); assertNull(transition.getNext()); } @Test - public void testMatchesStar() { + void testMatchesStar() { StateTransition transition = StateTransition.createStateTransition(state, "*", "start"); assertTrue(transition.matches("CONTINUABLE")); } @Test - public void testMatchesNull() { + void testMatchesNull() { StateTransition transition = StateTransition.createStateTransition(state, null, "start"); assertTrue(transition.matches("CONTINUABLE")); } @Test - public void testMatchesEmpty() { + void testMatchesEmpty() { StateTransition transition = StateTransition.createStateTransition(state, "", "start"); assertTrue(transition.matches("CONTINUABLE")); } @Test - public void testMatchesExact() { + void testMatchesExact() { StateTransition transition = StateTransition.createStateTransition(state, "CONTINUABLE", "start"); assertTrue(transition.matches("CONTINUABLE")); } @Test - public void testMatchesWildcard() { + void testMatchesWildcard() { StateTransition transition = StateTransition.createStateTransition(state, "CONTIN*", "start"); assertTrue(transition.matches("CONTINUABLE")); } @Test - public void testMatchesPlaceholder() { + void testMatchesPlaceholder() { StateTransition transition = StateTransition.createStateTransition(state, "CONTIN???LE", "start"); assertTrue(transition.matches("CONTINUABLE")); } @Test - public void testToString() { + void testToString() { StateTransition transition = StateTransition.createStateTransition(state, "CONTIN???LE", "start"); String string = transition.toString(); - assertTrue("Wrong string: " + string, string.contains("Transition")); - assertTrue("Wrong string: " + string, string.contains("start")); - assertTrue("Wrong string: " + string, string.contains("CONTIN???LE")); - assertTrue("Wrong string: " + string, string.contains("next=")); + assertTrue(string.contains("Transition"), "Wrong string: " + string); + assertTrue(string.contains("start"), "Wrong string: " + string); + assertTrue(string.contains("CONTIN???LE"), "Wrong string: " + string); + assertTrue(string.contains("next="), "Wrong string: " + string); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/support/state/EndStateTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/support/state/EndStateTests.java index 0bc840961f..5c5a56d4f5 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/support/state/EndStateTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/support/state/EndStateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,10 +15,10 @@ */ package org.springframework.batch.core.job.flow.support.state; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.job.flow.FlowExecutionStatus; @@ -29,12 +29,12 @@ * @author Dave Syer * */ -public class EndStateTests { +class EndStateTests { private JobExecution jobExecution; - @Before - public void setUp() { + @BeforeEach + void setUp() { jobExecution = new JobExecution(0L); } @@ -43,7 +43,7 @@ public void setUp() { * @throws Exception */ @Test - public void testHandleRestartSunnyDay() throws Exception { + void testHandleRestartSunnyDay() throws Exception { BatchStatus status = jobExecution.getStatus(); @@ -64,7 +64,7 @@ public JobExecution getJobExecution() { * @throws Exception */ @Test - public void testHandleOngoingSunnyDay() throws Exception { + void testHandleOngoingSunnyDay() throws Exception { jobExecution.createStepExecution("foo"); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/support/state/SimpleFlowExecutionAggregatorTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/support/state/SimpleFlowExecutionAggregatorTests.java index d6a3cb2267..ba83a7dec0 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/support/state/SimpleFlowExecutionAggregatorTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/support/state/SimpleFlowExecutionAggregatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,13 +15,13 @@ */ package org.springframework.batch.core.job.flow.support.state; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; import java.util.Collections; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.job.flow.FlowExecution; import org.springframework.batch.core.job.flow.FlowExecutionStatus; @@ -29,21 +29,21 @@ * @author Dave Syer * */ -public class SimpleFlowExecutionAggregatorTests { +class SimpleFlowExecutionAggregatorTests { - private MaxValueFlowExecutionAggregator aggregator = new MaxValueFlowExecutionAggregator(); + private final MaxValueFlowExecutionAggregator aggregator = new MaxValueFlowExecutionAggregator(); @Test - public void testFailed() throws Exception { + void testFailed() { FlowExecution first = new FlowExecution("foo", FlowExecutionStatus.COMPLETED); FlowExecution second = new FlowExecution("foo", FlowExecutionStatus.FAILED); - assertTrue("Should be negative", first.compareTo(second) < 0); - assertTrue("Should be positive", second.compareTo(first) > 0); + assertTrue(first.compareTo(second) < 0, "Should be negative"); + assertTrue(second.compareTo(first) > 0, "Should be positive"); assertEquals(FlowExecutionStatus.FAILED, aggregator.aggregate(Arrays.asList(first, second))); } @Test - public void testEmpty() throws Exception { + void testEmpty() { assertEquals(FlowExecutionStatus.UNKNOWN, aggregator.aggregate(Collections.emptySet())); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/support/state/SplitStateTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/support/state/SplitStateTests.java index 810c7bf359..0e89afd8d8 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/support/state/SplitStateTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/support/state/SplitStateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,7 +15,7 @@ */ package org.springframework.batch.core.job.flow.support.state; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -23,7 +23,7 @@ import java.util.Arrays; import java.util.Collection; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.job.flow.Flow; import org.springframework.batch.core.job.flow.FlowExecution; import org.springframework.batch.core.job.flow.FlowExecutionStatus; @@ -35,12 +35,12 @@ * @author Will Schipp * */ -public class SplitStateTests { +class SplitStateTests { - private JobFlowExecutorSupport executor = new JobFlowExecutorSupport(); + private final JobFlowExecutorSupport executor = new JobFlowExecutorSupport(); @Test - public void testBasicHandling() throws Exception { + void testBasicHandling() throws Exception { Collection flows = new ArrayList<>(); Flow flow1 = mock(Flow.class); @@ -59,7 +59,7 @@ public void testBasicHandling() throws Exception { } @Test - public void testConcurrentHandling() throws Exception { + void testConcurrentHandling() throws Exception { Flow flow1 = mock(Flow.class); Flow flow2 = mock(Flow.class); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/launch/JobExecutionNotRunningExceptionTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/launch/JobExecutionNotRunningExceptionTests.java index b81c5db8d3..ecf323fea0 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/launch/JobExecutionNotRunningExceptionTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/launch/JobExecutionNotRunningExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,18 +15,18 @@ */ package org.springframework.batch.core.launch; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author Dave Syer * */ -public class JobExecutionNotRunningExceptionTests { +class JobExecutionNotRunningExceptionTests { @Test - public void testExceptionString() throws Exception { + void testExceptionString() { Exception exception = new JobExecutionNotRunningException("foo"); assertEquals("foo", exception.getMessage()); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/launch/JobExecutionNotStoppedExceptionTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/launch/JobExecutionNotStoppedExceptionTests.java index 5102c1036f..117be1076e 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/launch/JobExecutionNotStoppedExceptionTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/launch/JobExecutionNotStoppedExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,18 +15,18 @@ */ package org.springframework.batch.core.launch; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author Dave Syer * */ -public class JobExecutionNotStoppedExceptionTests { +class JobExecutionNotStoppedExceptionTests { @Test - public void testExceptionString() throws Exception { + void testExceptionString() { Exception exception = new JobExecutionNotStoppedException("foo"); assertEquals("foo", exception.getMessage()); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/launch/JobLauncherIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/launch/JobLauncherIntegrationTests.java index a58590b08b..149dfef132 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/launch/JobLauncherIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/launch/JobLauncherIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2021 the original author or authors. + * Copyright 2009-2022 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. @@ -15,14 +15,13 @@ */ package org.springframework.batch.core.launch; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Calendar; import javax.sql.DataSource; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; @@ -30,12 +29,10 @@ import org.springframework.batch.core.repository.dao.JdbcJobExecutionDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.jdbc.JdbcTestUtils; -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) +@SpringJUnitConfig public class JobLauncherIntegrationTests { private JdbcTemplate jdbcTemplate; @@ -52,7 +49,7 @@ public void setDataSource(DataSource dataSource) { } @Test - public void testLaunchAndRelaunch() throws Exception { + void testLaunchAndRelaunch() throws Exception { int before = JdbcTestUtils.countRowsInTable(jdbcTemplate, "BATCH_JOB_INSTANCE"); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/launch/TaskExecutorJobLauncherTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/launch/TaskExecutorJobLauncherTests.java index 0c8bc896e5..e53ae5acdc 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/launch/TaskExecutorJobLauncherTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/launch/TaskExecutorJobLauncherTests.java @@ -16,9 +16,11 @@ package org.springframework.batch.core.launch; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -26,8 +28,8 @@ import java.util.Arrays; 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.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.Job; @@ -52,7 +54,7 @@ * @author Will Schipp * */ -public class TaskExecutorJobLauncherTests { +class TaskExecutorJobLauncherTests { private TaskExecutorJobLauncher jobLauncher; @@ -60,16 +62,15 @@ public class TaskExecutorJobLauncherTests { @Override public void execute(JobExecution execution) { execution.setExitStatus(ExitStatus.COMPLETED); - return; } }; - private JobParameters jobParameters = new JobParameters(); + private final JobParameters jobParameters = new JobParameters(); private JobRepository jobRepository; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { jobLauncher = new TaskExecutorJobLauncher(); jobRepository = mock(JobRepository.class); @@ -78,12 +79,12 @@ public void setUp() throws Exception { } @Test - public void testRun() throws Exception { + void testRun() throws Exception { run(ExitStatus.COMPLETED); } - @Test(expected = JobParametersInvalidException.class) - public void testRunWithValidator() throws Exception { + @Test + void testRunWithValidator() throws Exception { job.setJobParametersValidator( new DefaultJobParametersValidator(new String[] { "missing-and-required" }, new String[0])); @@ -91,12 +92,12 @@ public void testRunWithValidator() throws Exception { when(jobRepository.getLastJobExecution(job.getName(), jobParameters)).thenReturn(null); jobLauncher.afterPropertiesSet(); - jobLauncher.run(job, jobParameters); + assertThrows(JobParametersInvalidException.class, () -> jobLauncher.run(job, jobParameters)); } @Test - public void testRunRestartableJobInstanceTwice() throws Exception { + void testRunRestartableJobInstanceTwice() throws Exception { job = new JobSupport("foo") { @Override public boolean isRestartable() { @@ -123,7 +124,7 @@ public void execute(JobExecution execution) { * non-restartable JobInstance causes error. */ @Test - public void testRunNonRestartableJobInstanceTwice() throws Exception { + void testRunNonRestartableJobInstanceTwice() throws Exception { job = new JobSupport("foo") { @Override public boolean isRestartable() { @@ -138,19 +139,13 @@ public void execute(JobExecution execution) { }; testRun(); - try { - when(jobRepository.getLastJobExecution(job.getName(), jobParameters)) - .thenReturn(new JobExecution(new JobInstance(1L, job.getName()), jobParameters)); - jobLauncher.run(job, jobParameters); - fail("Expected JobRestartException"); - } - catch (JobRestartException e) { - // expected - } + when(jobRepository.getLastJobExecution(job.getName(), jobParameters)) + .thenReturn(new JobExecution(new JobInstance(1L, job.getName()), jobParameters)); + assertThrows(JobRestartException.class, () -> jobLauncher.run(job, jobParameters)); } @Test - public void testTaskExecutor() throws Exception { + void testTaskExecutor() throws Exception { final List list = new ArrayList<>(); jobLauncher.setTaskExecutor(new TaskExecutor() { @Override @@ -164,7 +159,7 @@ public void execute(Runnable task) { } @Test - public void testTaskExecutorRejects() throws Exception { + void testTaskExecutorRejects() throws Exception { final List list = new ArrayList<>(); jobLauncher.setTaskExecutor(new TaskExecutor() { @@ -195,7 +190,7 @@ public void execute(Runnable task) { } @Test - public void testRunWithException() throws Exception { + void testRunWithException() throws Exception { job = new JobSupport() { @Override public void execute(JobExecution execution) { @@ -203,17 +198,12 @@ public void execute(JobExecution execution) { throw new RuntimeException("foo"); } }; - try { - run(ExitStatus.FAILED); - fail("Expected RuntimeException"); - } - catch (RuntimeException e) { - assertEquals("foo", e.getMessage()); - } + Exception exception = assertThrows(RuntimeException.class, () -> run(ExitStatus.FAILED)); + assertEquals("foo", exception.getMessage()); } @Test - public void testRunWithError() throws Exception { + void testRunWithError() { job = new JobSupport() { @Override public void execute(JobExecution execution) { @@ -221,30 +211,20 @@ public void execute(JobExecution execution) { throw new Error("foo"); } }; - try { - run(ExitStatus.FAILED); - fail("Expected Error"); - } - catch (Error e) { - assertEquals("foo", e.getMessage()); - } + Error error = assertThrows(Error.class, () -> run(ExitStatus.FAILED)); + assertEquals("foo", error.getMessage()); } @Test - public void testInitialiseWithoutRepository() throws Exception { - try { - new TaskExecutorJobLauncher().afterPropertiesSet(); - fail("Expected IllegalArgumentException"); - } - catch (IllegalStateException e) { - // expected - assertTrue("Message did not contain repository: " + e.getMessage(), - contains(e.getMessage().toLowerCase(), "repository")); - } + void testInitialiseWithoutRepository() { + Exception exception = assertThrows(IllegalStateException.class, + () -> new TaskExecutorJobLauncher().afterPropertiesSet()); + assertTrue(exception.getMessage().toLowerCase().contains("repository"), + "Message did not contain repository: " + exception.getMessage()); } @Test - public void testInitialiseWithRepository() throws Exception { + void testInitialiseWithRepository() throws Exception { jobLauncher = new TaskExecutorJobLauncher(); jobLauncher.setJobRepository(jobRepository); jobLauncher.afterPropertiesSet(); // no error @@ -273,24 +253,27 @@ private boolean contains(String str, String searchStr) { * Test to support BATCH-1770 -> throw in parent thread JobRestartException when a * stepExecution is UNKNOWN */ - @Test(expected = JobRestartException.class) - public void testRunStepStatusUnknown() throws Exception { - testRestartStepExecutionInvalidStatus(BatchStatus.UNKNOWN); + @Test + void testRunStepStatusUnknown() { + assertThrows(JobRestartException.class, () -> testRestartStepExecutionInvalidStatus(BatchStatus.UNKNOWN)); } - @Test(expected = JobExecutionAlreadyRunningException.class) - public void testRunStepStatusStarting() throws Exception { - testRestartStepExecutionInvalidStatus(BatchStatus.STARTING); + @Test + void testRunStepStatusStarting() { + assertThrows(JobExecutionAlreadyRunningException.class, + () -> testRestartStepExecutionInvalidStatus(BatchStatus.STARTING)); } - @Test(expected = JobExecutionAlreadyRunningException.class) - public void testRunStepStatusStarted() throws Exception { - testRestartStepExecutionInvalidStatus(BatchStatus.STARTED); + @Test + void testRunStepStatusStarted() { + assertThrows(JobExecutionAlreadyRunningException.class, + () -> testRestartStepExecutionInvalidStatus(BatchStatus.STARTED)); } - @Test(expected = JobExecutionAlreadyRunningException.class) - public void testRunStepStatusStopping() throws Exception { - testRestartStepExecutionInvalidStatus(BatchStatus.STOPPING); + @Test + void testRunStepStatusStopping() { + assertThrows(JobExecutionAlreadyRunningException.class, + () -> testRestartStepExecutionInvalidStatus(BatchStatus.STOPPING)); } private void testRestartStepExecutionInvalidStatus(BatchStatus status) throws Exception { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/launch/support/CommandLineJobRunnerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/launch/support/CommandLineJobRunnerTests.java index 05db886511..92695de889 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/launch/support/CommandLineJobRunnerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/launch/support/CommandLineJobRunnerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,9 +25,9 @@ import java.util.Properties; import java.util.Set; -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.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; @@ -49,33 +49,33 @@ import org.springframework.lang.Nullable; import org.springframework.util.ClassUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Lucas Ward * @author Mahmoud Ben Hassine * */ -public class CommandLineJobRunnerTests { +class CommandLineJobRunnerTests { private String jobPath = ClassUtils.addResourcePathToPackagePath(CommandLineJobRunnerTests.class, "launcher-with-environment.xml"); - private String jobName = "test-job"; + private final String jobName = "test-job"; - private String jobKey = "job.Key=myKey"; + private final String jobKey = "job.Key=myKey"; - private String scheduleDate = "schedule.Date=01/23/2008"; + private final String scheduleDate = "schedule.Date=01/23/2008"; - private String vendorId = "vendor.id=33243243"; + private final String vendorId = "vendor.id=33243243"; - private String[] args = new String[] { jobPath, jobName, jobKey, scheduleDate, vendorId }; + private final String[] args = new String[] { jobPath, jobName, jobKey, scheduleDate, vendorId }; private InputStream stdin; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { JobExecution jobExecution = new JobExecution(null, 1L, null); ExitStatus exitStatus = ExitStatus.COMPLETED; jobExecution.setExitStatus(exitStatus); @@ -89,58 +89,59 @@ public int read() { }); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() { System.setIn(stdin); StubJobLauncher.tearDown(); } @Test - public void testMain() throws Exception { + void testMain() throws Exception { CommandLineJobRunner.main(args); - assertTrue("Injected JobParametersConverter not used instead of default", StubJobParametersConverter.called); + assertTrue(StubJobParametersConverter.called, "Injected JobParametersConverter not used instead of default"); assertEquals(0, StubSystemExiter.getStatus()); } @Test - public void testWithJobLocator() throws Exception { + void testWithJobLocator() throws Exception { jobPath = ClassUtils.addResourcePathToPackagePath(CommandLineJobRunnerTests.class, "launcher-with-locator.xml"); CommandLineJobRunner.main(new String[] { jobPath, jobName, jobKey }); - assertTrue("Injected JobParametersConverter not used instead of default", StubJobParametersConverter.called); + assertTrue(StubJobParametersConverter.called, "Injected JobParametersConverter not used instead of default"); assertEquals(0, StubSystemExiter.getStatus()); } @Test - public void testJobAlreadyRunning() throws Throwable { + void testJobAlreadyRunning() throws Throwable { StubJobLauncher.throwExecutionRunningException = true; CommandLineJobRunner.main(args); assertEquals(1, StubSystemExiter.status); } @Test - public void testInvalidArgs() throws Exception { + void testInvalidArgs() throws Exception { String[] args = new String[] {}; CommandLineJobRunner.presetSystemExiter(new StubSystemExiter()); CommandLineJobRunner.main(args); assertEquals(1, StubSystemExiter.status); String errorMessage = CommandLineJobRunner.getErrorMessage(); - assertTrue("Wrong error message: " + errorMessage, - errorMessage.contains("At least 2 arguments are required: JobPath/JobClass and jobIdentifier.")); + assertTrue(errorMessage.contains("At least 2 arguments are required: JobPath/JobClass and jobIdentifier."), + "Wrong error message: " + errorMessage); } @Test - public void testWrongJobName() throws Exception { + void testWrongJobName() throws Exception { String[] args = new String[] { jobPath, "no-such-job" }; CommandLineJobRunner.main(args); assertEquals(1, StubSystemExiter.status); String errorMessage = CommandLineJobRunner.getErrorMessage(); - assertTrue("Wrong error message: " + errorMessage, + assertTrue( (errorMessage.contains("No bean named 'no-such-job' is defined") - || (errorMessage.contains("No bean named 'no-such-job' available")))); + || (errorMessage.contains("No bean named 'no-such-job' available"))), + "Wrong error message: " + errorMessage); } @Test - public void testWithNoParameters() throws Throwable { + void testWithNoParameters() throws Throwable { String[] args = new String[] { jobPath, jobName }; CommandLineJobRunner.main(args); assertEquals(0, StubSystemExiter.status); @@ -148,7 +149,7 @@ public void testWithNoParameters() throws Throwable { } @Test - public void testWithInvalidStdin() throws Throwable { + void testWithInvalidStdin() throws Throwable { System.setIn(new InputStream() { @Override public int available() throws IOException { @@ -166,7 +167,7 @@ public int read() { } @Test - public void testWithStdinCommandLine() throws Throwable { + void testWithStdinCommandLine() throws Throwable { System.setIn(new InputStream() { char[] input = (jobPath + "\n" + jobName + "\nfoo=bar\nspam=bucket").toCharArray(); @@ -188,7 +189,7 @@ public int read() { } @Test - public void testWithStdinCommandLineWithEmptyLines() throws Throwable { + void testWithStdinCommandLineWithEmptyLines() throws Throwable { System.setIn(new InputStream() { char[] input = (jobPath + "\n" + jobName + "\nfoo=bar\n\nspam=bucket\n\n").toCharArray(); @@ -210,7 +211,7 @@ public int read() { } @Test - public void testWithStdinParameters() throws Throwable { + void testWithStdinParameters() throws Throwable { String[] args = new String[] { jobPath, jobName }; System.setIn(new InputStream() { char[] input = ("foo=bar\nspam=bucket").toCharArray(); @@ -233,16 +234,16 @@ public int read() { } @Test - public void testWithInvalidParameters() throws Throwable { + void testWithInvalidParameters() throws Throwable { String[] args = new String[] { jobPath, jobName, "foo" }; CommandLineJobRunner.main(args); assertEquals(1, StubSystemExiter.status); String errorMessage = CommandLineJobRunner.getErrorMessage(); - assertTrue("Wrong error message: " + errorMessage, errorMessage.contains("in the form name=value")); + assertTrue(errorMessage.contains("in the form name=value"), "Wrong error message: " + errorMessage); } @Test - public void testStop() throws Throwable { + void testStop() throws Throwable { String[] args = new String[] { jobPath, "-stop", jobName }; StubJobExplorer.jobInstances = Arrays.asList(new JobInstance(3L, jobName)); CommandLineJobRunner.main(args); @@ -250,7 +251,7 @@ public void testStop() throws Throwable { } @Test - public void testStopFailed() throws Throwable { + void testStopFailed() throws Throwable { String[] args = new String[] { jobPath, "-stop", jobName }; StubJobExplorer.jobInstances = Arrays.asList(new JobInstance(0L, jobName)); CommandLineJobRunner.main(args); @@ -258,7 +259,7 @@ public void testStopFailed() throws Throwable { } @Test - public void testStopFailedAndRestarted() throws Throwable { + void testStopFailedAndRestarted() throws Throwable { String[] args = new String[] { jobPath, "-stop", jobName }; StubJobExplorer.jobInstances = Arrays.asList(new JobInstance(5L, jobName)); CommandLineJobRunner.main(args); @@ -266,7 +267,7 @@ public void testStopFailedAndRestarted() throws Throwable { } @Test - public void testStopRestarted() throws Throwable { + void testStopRestarted() throws Throwable { String[] args = new String[] { jobPath, "-stop", jobName }; JobInstance jobInstance = new JobInstance(3L, jobName); StubJobExplorer.jobInstances = Arrays.asList(jobInstance); @@ -275,7 +276,7 @@ public void testStopRestarted() throws Throwable { } @Test - public void testAbandon() throws Throwable { + void testAbandon() throws Throwable { String[] args = new String[] { jobPath, "-abandon", jobName }; StubJobExplorer.jobInstances = Arrays.asList(new JobInstance(2L, jobName)); CommandLineJobRunner.main(args); @@ -283,7 +284,7 @@ public void testAbandon() throws Throwable { } @Test - public void testAbandonRunning() throws Throwable { + void testAbandonRunning() throws Throwable { String[] args = new String[] { jobPath, "-abandon", jobName }; StubJobExplorer.jobInstances = Arrays.asList(new JobInstance(3L, jobName)); CommandLineJobRunner.main(args); @@ -291,7 +292,7 @@ public void testAbandonRunning() throws Throwable { } @Test - public void testAbandonAbandoned() throws Throwable { + void testAbandonAbandoned() throws Throwable { String[] args = new String[] { jobPath, "-abandon", jobName }; StubJobExplorer.jobInstances = Arrays.asList(new JobInstance(4L, jobName)); CommandLineJobRunner.main(args); @@ -299,7 +300,7 @@ public void testAbandonAbandoned() throws Throwable { } @Test - public void testRestart() throws Throwable { + void testRestart() throws Throwable { String[] args = new String[] { jobPath, "-restart", jobName }; JobParameters jobParameters = new JobParametersBuilder().addString("foo", "bar").toJobParameters(); JobInstance jobInstance = new JobInstance(0L, jobName); @@ -312,7 +313,7 @@ public void testRestart() throws Throwable { } @Test - public void testRestartExecution() throws Throwable { + void testRestartExecution() throws Throwable { String[] args = new String[] { jobPath, "-restart", "11" }; JobParameters jobParameters = new JobParametersBuilder().addString("foo", "bar").toJobParameters(); JobExecution jobExecution = new JobExecution(new JobInstance(0L, jobName), 11L, jobParameters); @@ -324,7 +325,7 @@ public void testRestartExecution() throws Throwable { } @Test - public void testRestartExecutionNotFailed() throws Throwable { + void testRestartExecutionNotFailed() throws Throwable { String[] args = new String[] { jobPath, "-restart", "11" }; JobParameters jobParameters = new JobParametersBuilder().addString("foo", "bar").toJobParameters(); JobExecution jobExecution = new JobExecution(new JobInstance(0L, jobName), 11L, jobParameters); @@ -336,18 +337,18 @@ public void testRestartExecutionNotFailed() throws Throwable { } @Test - public void testRestartNotFailed() throws Throwable { + void testRestartNotFailed() throws Throwable { String[] args = new String[] { jobPath, "-restart", jobName }; StubJobExplorer.jobInstances = Arrays.asList(new JobInstance(123L, jobName)); CommandLineJobRunner.main(args); assertEquals(1, StubSystemExiter.status); String errorMessage = CommandLineJobRunner.getErrorMessage(); - assertTrue("Wrong error message: " + errorMessage, - errorMessage.contains("No failed or stopped execution found")); + assertTrue(errorMessage.contains("No failed or stopped execution found"), + "Wrong error message: " + errorMessage); } @Test - public void testNext() throws Throwable { + void testNext() throws Throwable { String[] args = new String[] { jobPath, "-next", jobName, "bar=foo" }; JobParameters jobParameters = new JobParametersBuilder().addString("foo", "bar").addString("bar", "foo") .toJobParameters(); @@ -359,7 +360,7 @@ public void testNext() throws Throwable { } @Test - public void testNextFirstInSequence() throws Throwable { + void testNextFirstInSequence() throws Throwable { String[] args = new String[] { jobPath, "-next", jobName }; StubJobExplorer.jobInstances = new ArrayList<>(); CommandLineJobRunner.main(args); @@ -369,24 +370,24 @@ public void testNextFirstInSequence() throws Throwable { } @Test - public void testNextWithNoParameters() throws Exception { + void testNextWithNoParameters() throws Exception { jobPath = ClassUtils.addResourcePathToPackagePath(CommandLineJobRunnerTests.class, "launcher-with-locator.xml"); CommandLineJobRunner.main(new String[] { jobPath, "-next", "test-job2", jobKey }); assertEquals(1, StubSystemExiter.getStatus()); String errorMessage = CommandLineJobRunner.getErrorMessage(); - assertTrue("Wrong error message: " + errorMessage, - errorMessage.contains(" No job parameters incrementer found")); + assertTrue(errorMessage.contains(" No job parameters incrementer found"), + "Wrong error message: " + errorMessage); } @Test - public void testDestroyCallback() throws Throwable { + void testDestroyCallback() throws Throwable { String[] args = new String[] { jobPath, jobName }; CommandLineJobRunner.main(args); assertTrue(StubJobLauncher.destroyed); } @Test - public void testJavaConfig() throws Exception { + void testJavaConfig() throws Exception { String[] args = new String[] { "org.springframework.batch.core.launch.support.CommandLineJobRunnerTests$Configuration1", "invalidJobName" }; @@ -394,8 +395,8 @@ public void testJavaConfig() throws Exception { CommandLineJobRunner.main(args); assertEquals(1, StubSystemExiter.status); String errorMessage = CommandLineJobRunner.getErrorMessage(); - assertTrue("Wrong error message: " + errorMessage, - errorMessage.contains("A JobLauncher must be provided. Please add one to the configuration.")); + assertTrue(errorMessage.contains("A JobLauncher must be provided. Please add one to the configuration."), + "Wrong error message: " + errorMessage); } public static class StubSystemExiter implements SystemExiter { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/launch/support/DataFieldMaxValueJobParametersIncrementerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/launch/support/DataFieldMaxValueJobParametersIncrementerTests.java index 4e07d2fdc0..60d55e1680 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/launch/support/DataFieldMaxValueJobParametersIncrementerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/launch/support/DataFieldMaxValueJobParametersIncrementerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2021 the original author or authors. + * Copyright 2020-2022 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. @@ -15,50 +15,41 @@ */ package org.springframework.batch.core.launch.support; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.JobParametersBuilder; import org.springframework.jdbc.support.incrementer.DataFieldMaxValueIncrementer; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * @author Mahmoud Ben Hassine */ -public class DataFieldMaxValueJobParametersIncrementerTests { +class DataFieldMaxValueJobParametersIncrementerTests { private final DataFieldMaxValueIncrementer incrementer = mock(DataFieldMaxValueIncrementer.class); @Test - public void testInvalidKey() { + void testInvalidKey() { DataFieldMaxValueJobParametersIncrementer jobParametersIncrementer = new DataFieldMaxValueJobParametersIncrementer( this.incrementer); - try { - jobParametersIncrementer.setKey(""); - fail("Must fail if the key is empty"); - } - catch (IllegalArgumentException exception) { - Assert.assertEquals("key must not be null or empty", exception.getMessage()); - } + Exception exception = assertThrows(IllegalArgumentException.class, () -> jobParametersIncrementer.setKey("")); + assertEquals("key must not be null or empty", exception.getMessage()); } @Test - public void testInvalidDataFieldMaxValueIncrementer() { - try { - new DataFieldMaxValueJobParametersIncrementer(null); - fail("Must fail if the incrementer is null"); - } - catch (IllegalArgumentException exception) { - Assert.assertEquals("dataFieldMaxValueIncrementer must not be null", exception.getMessage()); - } + void testInvalidDataFieldMaxValueIncrementer() { + Exception exception = assertThrows(IllegalArgumentException.class, + () -> new DataFieldMaxValueJobParametersIncrementer(null)); + assertEquals("dataFieldMaxValueIncrementer must not be null", exception.getMessage()); } @Test - public void testGetNext() { + void testGetNext() { // given JobParameters jobParameters = new JobParameters(); when(this.incrementer.nextLongValue()).thenReturn(10L); @@ -70,11 +61,11 @@ public void testGetNext() { // then Long runId = nextParameters.getLong("run.id"); - Assert.assertEquals(Long.valueOf(10L), runId); + assertEquals(Long.valueOf(10L), runId); } @Test - public void testGetNextAppend() { + void testGetNextAppend() { // given JobParameters jobParameters = new JobParametersBuilder().addString("foo", "bar").toJobParameters(); when(this.incrementer.nextLongValue()).thenReturn(10L); @@ -87,12 +78,12 @@ public void testGetNextAppend() { // then Long runId = nextParameters.getLong("run.id"); String foo = nextParameters.getString("foo"); - Assert.assertEquals(Long.valueOf(10L), runId); - Assert.assertEquals("bar", foo); + assertEquals(Long.valueOf(10L), runId); + assertEquals("bar", foo); } @Test - public void testGetNextOverride() { + void testGetNextOverride() { // given JobParameters jobParameters = new JobParametersBuilder().addLong("run.id", 1L).toJobParameters(); when(this.incrementer.nextLongValue()).thenReturn(10L); @@ -104,7 +95,7 @@ public void testGetNextOverride() { // then Long runId = nextParameters.getLong("run.id"); - Assert.assertEquals(Long.valueOf(10L), runId); + assertEquals(Long.valueOf(10L), runId); } } \ No newline at end of file diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/launch/support/JobRegistryBackgroundJobRunnerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/launch/support/JobRegistryBackgroundJobRunnerTests.java index 0e32545629..6643bd60e6 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/launch/support/JobRegistryBackgroundJobRunnerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/launch/support/JobRegistryBackgroundJobRunnerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,25 +15,25 @@ */ package org.springframework.batch.core.launch.support; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -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.util.ClassUtils; /** * @author Dave Syer * */ -public class JobRegistryBackgroundJobRunnerTests { +class JobRegistryBackgroundJobRunnerTests { /** * Test method for * {@link org.springframework.batch.core.launch.support.JobRegistryBackgroundJobRunner#main(java.lang.String[])}. */ @Test - public void testMain() throws Exception { + void testMain() throws Exception { JobRegistryBackgroundJobRunner.main( ClassUtils.addResourcePathToPackagePath(getClass(), "test-environment-with-registry.xml"), ClassUtils.addResourcePathToPackagePath(getClass(), "job.xml")); @@ -41,7 +41,7 @@ public void testMain() throws Exception { } @Test - public void testMainWithAutoRegister() throws Exception { + void testMainWithAutoRegister() throws Exception { JobRegistryBackgroundJobRunner.main( ClassUtils.addResourcePathToPackagePath(getClass(), "test-environment-with-registry-and-auto-register.xml"), @@ -50,21 +50,21 @@ public void testMainWithAutoRegister() throws Exception { } @Test - public void testMainWithJobLoader() throws Exception { + void testMainWithJobLoader() throws Exception { JobRegistryBackgroundJobRunner.main( ClassUtils.addResourcePathToPackagePath(getClass(), "test-environment-with-loader.xml"), ClassUtils.addResourcePathToPackagePath(getClass(), "job.xml")); assertEquals(0, JobRegistryBackgroundJobRunner.getErrors().size()); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { JobRegistryBackgroundJobRunner.getErrors().clear(); System.setProperty(JobRegistryBackgroundJobRunner.EMBEDDED, ""); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() { System.clearProperty(JobRegistryBackgroundJobRunner.EMBEDDED); JobRegistryBackgroundJobRunner.getErrors().clear(); JobRegistryBackgroundJobRunner.stop(); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/launch/support/RunIdIncrementerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/launch/support/RunIdIncrementerTests.java index 63dd977873..e14eb0b65e 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/launch/support/RunIdIncrementerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/launch/support/RunIdIncrementerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2020 the original author or authors. + * Copyright 2006-2022 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. @@ -15,9 +15,10 @@ */ package org.springframework.batch.core.launch.support; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.JobParametersBuilder; @@ -27,33 +28,33 @@ * @author Mahmoud Ben Hassine * */ -public class RunIdIncrementerTests { +class RunIdIncrementerTests { - private RunIdIncrementer incrementer = new RunIdIncrementer(); + private final RunIdIncrementer incrementer = new RunIdIncrementer(); @Test - public void testGetNext() { + void testGetNext() { JobParameters next = incrementer.getNext(null); assertEquals(1, next.getLong("run.id").intValue()); assertEquals(2, incrementer.getNext(next).getLong("run.id").intValue()); } @Test - public void testGetNextAppends() { + void testGetNextAppends() { JobParameters next = incrementer.getNext(new JobParametersBuilder().addString("foo", "bar").toJobParameters()); assertEquals(1, next.getLong("run.id").intValue()); assertEquals("bar", next.getString("foo")); } @Test - public void testGetNextNamed() { + void testGetNextNamed() { incrementer.setKey("foo"); JobParameters next = incrementer.getNext(null); assertEquals(1, next.getLong("foo").intValue()); } @Test - public void testGetNextWhenRunIdIsString() { + void testGetNextWhenRunIdIsString() { // given JobParameters parameters = new JobParametersBuilder().addString("run.id", "5").toJobParameters(); @@ -64,9 +65,10 @@ public void testGetNextWhenRunIdIsString() { assertEquals(Long.valueOf(6), next.getLong("run.id")); } - @Test(expected = IllegalArgumentException.class) - public void testGetNextWhenRunIdIsInvalidString() { - this.incrementer.getNext(new JobParametersBuilder().addString("run.id", "foo").toJobParameters()); + @Test + void testGetNextWhenRunIdIsInvalidString() { + JobParameters jobParameters = new JobParametersBuilder().addString("run.id", "foo").toJobParameters(); + assertThrows(IllegalArgumentException.class, () -> this.incrementer.getNext(jobParameters)); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/launch/support/SimpleJobOperatorTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/launch/support/SimpleJobOperatorTests.java index 7a57928f3f..2c9d0212bf 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/launch/support/SimpleJobOperatorTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/launch/support/SimpleJobOperatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,8 +24,8 @@ import java.util.Properties; 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.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; @@ -55,10 +55,10 @@ import org.springframework.batch.support.PropertiesConverter; import org.springframework.lang.Nullable; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -71,7 +71,7 @@ * @author Mahmoud Ben Hassine * */ -public class SimpleJobOperatorTests { +class SimpleJobOperatorTests { private SimpleJobOperator jobOperator; @@ -83,8 +83,8 @@ public class SimpleJobOperatorTests { private JobParameters jobParameters; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { job = new JobSupport("foo") { @Nullable @@ -124,7 +124,7 @@ public Set getJobNames() { jobOperator.setJobParametersConverter(new DefaultJobParametersConverter() { @Override public JobParameters getJobParameters(@Nullable Properties props) { - assertTrue("Wrong properties", props.containsKey("a")); + assertTrue(props.containsKey("a"), "Wrong properties"); return jobParameters; } @@ -139,15 +139,9 @@ public Properties getProperties(@Nullable JobParameters params) { } @Test - public void testMandatoryProperties() throws Exception { + void testMandatoryProperties() { jobOperator = new SimpleJobOperator(); - try { - jobOperator.afterPropertiesSet(); - fail("Expected IllegalArgumentException"); - } - catch (IllegalArgumentException e) { - // expected - } + assertThrows(IllegalArgumentException.class, jobOperator::afterPropertiesSet); } /** @@ -156,7 +150,7 @@ public void testMandatoryProperties() throws Exception { * . */ @Test - public void testStartNextInstanceSunnyDay() throws Exception { + void testStartNextInstanceSunnyDay() throws Exception { jobParameters = new JobParameters(); JobInstance jobInstance = new JobInstance(321L, "foo"); when(jobExplorer.getJobInstances("foo", 0, 1)).thenReturn(Collections.singletonList(jobInstance)); @@ -167,7 +161,7 @@ public void testStartNextInstanceSunnyDay() throws Exception { } @Test - public void testStartNewInstanceSunnyDay() throws Exception { + void testStartNewInstanceSunnyDay() throws Exception { jobParameters = new JobParameters(); jobRepository.isJobInstanceExists("foo", jobParameters); Long value = jobOperator.start("foo", "a=b"); @@ -175,21 +169,15 @@ public void testStartNewInstanceSunnyDay() throws Exception { } @Test - public void testStartNewInstanceAlreadyExists() throws Exception { + void testStartNewInstanceAlreadyExists() { jobParameters = new JobParameters(); when(jobRepository.isJobInstanceExists("foo", jobParameters)).thenReturn(true); jobRepository.isJobInstanceExists("foo", jobParameters); - try { - jobOperator.start("foo", "a=b"); - fail("Expected JobInstanceAlreadyExistsException"); - } - catch (JobInstanceAlreadyExistsException e) { - // expected - } + assertThrows(JobInstanceAlreadyExistsException.class, () -> jobOperator.start("foo", "a=b")); } @Test - public void testResumeSunnyDay() throws Exception { + void testResumeSunnyDay() throws Exception { jobParameters = new JobParameters(); when(jobExplorer.getJobExecution(111L)) .thenReturn(new JobExecution(new JobInstance(123L, job.getName()), 111L, jobParameters)); @@ -199,7 +187,7 @@ public void testResumeSunnyDay() throws Exception { } @Test - public void testGetSummarySunnyDay() throws Exception { + void testGetSummarySunnyDay() throws Exception { jobParameters = new JobParameters(); JobExecution jobExecution = new JobExecution(new JobInstance(123L, job.getName()), 111L, jobParameters); when(jobExplorer.getJobExecution(111L)).thenReturn(jobExecution); @@ -209,20 +197,14 @@ public void testGetSummarySunnyDay() throws Exception { } @Test - public void testGetSummaryNoSuchExecution() throws Exception { + void testGetSummaryNoSuchExecution() { jobParameters = new JobParameters(); jobExplorer.getJobExecution(111L); - try { - jobOperator.getSummary(111L); - fail("Expected NoSuchJobExecutionException"); - } - catch (NoSuchJobExecutionException e) { - // expected - } + assertThrows(NoSuchJobExecutionException.class, () -> jobOperator.getSummary(111L)); } @Test - public void testGetStepExecutionSummariesSunnyDay() throws Exception { + void testGetStepExecutionSummariesSunnyDay() throws Exception { jobParameters = new JobParameters(); JobExecution jobExecution = new JobExecution(new JobInstance(123L, job.getName()), 111L, jobParameters); @@ -235,20 +217,14 @@ public void testGetStepExecutionSummariesSunnyDay() throws Exception { } @Test - public void testGetStepExecutionSummariesNoSuchExecution() throws Exception { + void testGetStepExecutionSummariesNoSuchExecution() { jobParameters = new JobParameters(); jobExplorer.getJobExecution(111L); - try { - jobOperator.getStepExecutionSummaries(111L); - fail("Expected NoSuchJobExecutionException"); - } - catch (NoSuchJobExecutionException e) { - // expected - } + assertThrows(NoSuchJobExecutionException.class, () -> jobOperator.getStepExecutionSummaries(111L)); } @Test - public void testFindRunningExecutionsSunnyDay() throws Exception { + void testFindRunningExecutionsSunnyDay() throws Exception { jobParameters = new JobParameters(); JobExecution jobExecution = new JobExecution(new JobInstance(123L, job.getName()), 111L, jobParameters); when(jobExplorer.findRunningJobExecutions("foo")).thenReturn(Collections.singleton(jobExecution)); @@ -258,20 +234,14 @@ public void testFindRunningExecutionsSunnyDay() throws Exception { @Test @SuppressWarnings("unchecked") - public void testFindRunningExecutionsNoSuchJob() throws Exception { + void testFindRunningExecutionsNoSuchJob() { jobParameters = new JobParameters(); when(jobExplorer.findRunningJobExecutions("no-such-job")).thenReturn(Collections.EMPTY_SET); - try { - jobOperator.getRunningExecutions("no-such-job"); - fail("Expected NoSuchJobException"); - } - catch (NoSuchJobException e) { - // expected - } + assertThrows(NoSuchJobException.class, () -> jobOperator.getRunningExecutions("no-such-job")); } @Test - public void testGetJobParametersSunnyDay() throws Exception { + void testGetJobParametersSunnyDay() throws Exception { final JobParameters jobParameters = new JobParameters(); when(jobExplorer.getJobExecution(111L)) .thenReturn(new JobExecution(new JobInstance(123L, job.getName()), 111L, jobParameters)); @@ -280,19 +250,13 @@ public void testGetJobParametersSunnyDay() throws Exception { } @Test - public void testGetJobParametersNoSuchExecution() throws Exception { + void testGetJobParametersNoSuchExecution() { jobExplorer.getJobExecution(111L); - try { - jobOperator.getParameters(111L); - fail("Expected NoSuchJobExecutionException"); - } - catch (NoSuchJobExecutionException e) { - // expected - } + assertThrows(NoSuchJobExecutionException.class, () -> jobOperator.getParameters(111L)); } @Test - public void testGetLastInstancesSunnyDay() throws Exception { + void testGetLastInstancesSunnyDay() throws Exception { jobParameters = new JobParameters(); JobInstance jobInstance = new JobInstance(123L, job.getName()); when(jobExplorer.getJobInstances("foo", 0, 2)).thenReturn(Collections.singletonList(jobInstance)); @@ -302,27 +266,21 @@ public void testGetLastInstancesSunnyDay() throws Exception { } @Test - public void testGetLastInstancesNoSuchJob() throws Exception { + void testGetLastInstancesNoSuchJob() { jobParameters = new JobParameters(); jobExplorer.getJobInstances("no-such-job", 0, 2); - try { - jobOperator.getJobInstances("no-such-job", 0, 2); - fail("Expected NoSuchJobException"); - } - catch (NoSuchJobException e) { - // expected - } + assertThrows(NoSuchJobException.class, () -> jobOperator.getJobInstances("no-such-job", 0, 2)); } @Test - public void testGetJobNames() throws Exception { + void testGetJobNames() { Set names = jobOperator.getJobNames(); assertEquals(2, names.size()); - assertTrue("Wrong names: " + names, names.contains("foo")); + assertTrue(names.contains("foo"), "Wrong names: " + names); } @Test - public void testGetExecutionsSunnyDay() throws Exception { + void testGetExecutionsSunnyDay() throws Exception { JobInstance jobInstance = new JobInstance(123L, job.getName()); when(jobExplorer.getJobInstance(123L)).thenReturn(jobInstance); @@ -333,19 +291,13 @@ public void testGetExecutionsSunnyDay() throws Exception { } @Test - public void testGetExecutionsNoSuchInstance() throws Exception { + void testGetExecutionsNoSuchInstance() { jobExplorer.getJobInstance(123L); - try { - jobOperator.getExecutions(123L); - fail("Expected NoSuchJobInstanceException"); - } - catch (NoSuchJobInstanceException e) { - // expected - } + assertThrows(NoSuchJobInstanceException.class, () -> jobOperator.getExecutions(123L)); } @Test - public void testStop() throws Exception { + void testStop() throws Exception { JobInstance jobInstance = new JobInstance(123L, job.getName()); JobExecution jobExecution = new JobExecution(jobInstance, 111L, jobParameters); when(jobExplorer.getJobExecution(111L)).thenReturn(jobExecution); @@ -356,7 +308,7 @@ public void testStop() throws Exception { } @Test - public void testStopTasklet() throws Exception { + void testStopTasklet() throws Exception { JobInstance jobInstance = new JobInstance(123L, job.getName()); JobExecution jobExecution = new JobExecution(jobInstance, 111L, jobParameters); StoppableTasklet tasklet = mock(StoppableTasklet.class); @@ -381,7 +333,7 @@ public void testStopTasklet() throws Exception { } @Test - public void testStopTaskletWhenJobNotRegistered() throws Exception { + void testStopTaskletWhenJobNotRegistered() throws Exception { JobInstance jobInstance = new JobInstance(123L, job.getName()); JobExecution jobExecution = new JobExecution(jobInstance, 111L, jobParameters); StoppableTasklet tasklet = mock(StoppableTasklet.class); @@ -399,7 +351,7 @@ public void testStopTaskletWhenJobNotRegistered() throws Exception { } @Test - public void testStopTaskletException() throws Exception { + void testStopTaskletException() throws Exception { JobInstance jobInstance = new JobInstance(123L, job.getName()); JobExecution jobExecution = new JobExecution(jobInstance, 111L, jobParameters); StoppableTasklet tasklet = new StoppableTasklet() { @@ -436,7 +388,7 @@ public void stop() { } @Test - public void testAbort() throws Exception { + void testAbort() throws Exception { JobInstance jobInstance = new JobInstance(123L, job.getName()); JobExecution jobExecution = new JobExecution(jobInstance, 111L, jobParameters); jobExecution.setStatus(BatchStatus.STOPPING); @@ -447,17 +399,17 @@ public void testAbort() throws Exception { assertNotNull(jobExecution.getEndTime()); } - @Test(expected = JobExecutionAlreadyRunningException.class) - public void testAbortNonStopping() throws Exception { + @Test + void testAbortNonStopping() { JobInstance jobInstance = new JobInstance(123L, job.getName()); JobExecution jobExecution = new JobExecution(jobInstance, 111L, jobParameters); jobExecution.setStatus(BatchStatus.STARTED); when(jobExplorer.getJobExecution(123L)).thenReturn(jobExecution); jobRepository.update(jobExecution); - jobOperator.abandon(123L); + assertThrows(JobExecutionAlreadyRunningException.class, () -> jobOperator.abandon(123L)); } - class MockJob extends AbstractJob { + static class MockJob extends AbstractJob { private TaskletStep taskletStep; diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/launch/support/SimpleJvmExitCodeMapperTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/launch/support/SimpleJvmExitCodeMapperTests.java index 61d0107dc4..077673db3f 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/launch/support/SimpleJvmExitCodeMapperTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/launch/support/SimpleJvmExitCodeMapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -19,18 +19,20 @@ import java.util.HashMap; import java.util.Map; -import junit.framework.TestCase; - +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.ExitStatus; -public class SimpleJvmExitCodeMapperTests extends TestCase { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class SimpleJvmExitCodeMapperTests { private SimpleJvmExitCodeMapper ecm; private SimpleJvmExitCodeMapper ecm2; - @Override - protected void setUp() throws Exception { + @BeforeEach + void setUp() { ecm = new SimpleJvmExitCodeMapper(); Map ecmMap = new HashMap<>(); ecmMap.put("MY_CUSTOM_CODE", 3); @@ -45,19 +47,16 @@ protected void setUp() throws Exception { ecm2.setMapping(ecm2Map); } - @Override - protected void tearDown() throws Exception { - super.tearDown(); - } - - public void testGetExitCodeWithPredefinedCodes() { + @Test + void testGetExitCodeWithPredefinedCodes() { assertEquals(ecm.intValue(ExitStatus.COMPLETED.getExitCode()), ExitCodeMapper.JVM_EXITCODE_COMPLETED); assertEquals(ecm.intValue(ExitStatus.FAILED.getExitCode()), ExitCodeMapper.JVM_EXITCODE_GENERIC_ERROR); assertEquals(ecm.intValue(ExitCodeMapper.JOB_NOT_PROVIDED), ExitCodeMapper.JVM_EXITCODE_JOB_ERROR); assertEquals(ecm.intValue(ExitCodeMapper.NO_SUCH_JOB), ExitCodeMapper.JVM_EXITCODE_JOB_ERROR); } - public void testGetExitCodeWithPredefinedCodesOverridden() { + @Test + void testGetExitCodeWithPredefinedCodesOverridden() { System.out.println(ecm2.intValue(ExitStatus.COMPLETED.getExitCode())); assertEquals(ecm2.intValue(ExitStatus.COMPLETED.getExitCode()), -1); assertEquals(ecm2.intValue(ExitStatus.FAILED.getExitCode()), -2); @@ -65,11 +64,13 @@ public void testGetExitCodeWithPredefinedCodesOverridden() { assertEquals(ecm2.intValue(ExitCodeMapper.NO_SUCH_JOB), -3); } - public void testGetExitCodeWithCustomCode() { + @Test + void testGetExitCodeWithCustomCode() { assertEquals(ecm.intValue("MY_CUSTOM_CODE"), 3); } - public void testGetExitCodeWithDefaultCode() { + @Test + void testGetExitCodeWithDefaultCode() { assertEquals(ecm.intValue("UNDEFINED_CUSTOM_CODE"), ExitCodeMapper.JVM_EXITCODE_GENERIC_ERROR); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/AbstractDoubleExceptionTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/AbstractDoubleExceptionTests.java index 7da346d3fa..75e46a6bcc 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/AbstractDoubleExceptionTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/AbstractDoubleExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,9 +15,9 @@ */ package org.springframework.batch.core.listener; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author Dave Syer @@ -26,7 +26,7 @@ public abstract class AbstractDoubleExceptionTests { @Test - public void testExceptionStringThrowable() throws Exception { + void testExceptionStringThrowable() throws Exception { Exception exception = getException("foo", new IllegalStateException(), new RuntimeException("bar")); assertEquals("foo", exception.getMessage().substring(0, 3)); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeChunkListenerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeChunkListenerTests.java index 31a0344817..3d1284b060 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeChunkListenerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeChunkListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2013 the original author or authors. + * Copyright 2006-2022 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. @@ -17,8 +17,8 @@ import static org.mockito.Mockito.mock; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.ChunkListener; import org.springframework.batch.core.scope.context.ChunkContext; @@ -28,7 +28,7 @@ * @author Will Schipp * */ -public class CompositeChunkListenerTests { +class CompositeChunkListenerTests { ChunkListener listener; @@ -36,8 +36,8 @@ public class CompositeChunkListenerTests { ChunkContext chunkContext; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { chunkContext = new ChunkContext(null); listener = mock(ChunkListener.class); compositeListener = new CompositeChunkListener(); @@ -45,20 +45,19 @@ public void setUp() throws Exception { } @Test - public void testBeforeChunk() { + void testBeforeChunk() { listener.beforeChunk(chunkContext); compositeListener.beforeChunk(chunkContext); } @Test - public void testAfterChunk() { - + void testAfterChunk() { listener.afterChunk(chunkContext); compositeListener.afterChunk(chunkContext); } @Test - public void testAfterChunkFailed() { + void testAfterChunkFailed() { ChunkContext context = new ChunkContext(null); listener.afterChunkError(context); compositeListener.afterChunkError(context); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeItemProcessListenerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeItemProcessListenerTests.java index fccfb23cf8..513e51cdd9 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeItemProcessListenerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeItemProcessListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2008 the original author or authors. + * Copyright 2006-2022 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. @@ -19,8 +19,8 @@ import java.util.Collections; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.ItemProcessListener; /** @@ -28,29 +28,29 @@ * @author Will Schipp * */ -public class CompositeItemProcessListenerTests { +class CompositeItemProcessListenerTests { private ItemProcessListener listener; private CompositeItemProcessListener compositeListener; @SuppressWarnings("unchecked") - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { listener = mock(ItemProcessListener.class); compositeListener = new CompositeItemProcessListener<>(); compositeListener.register(listener); } @Test - public void testBeforeRProcess() { + void testBeforeRProcess() { Object item = new Object(); listener.beforeProcess(item); compositeListener.beforeProcess(item); } @Test - public void testAfterRead() { + void testAfterRead() { Object item = new Object(); Object result = new Object(); listener.afterProcess(item, result); @@ -58,7 +58,7 @@ public void testAfterRead() { } @Test - public void testOnReadError() { + void testOnReadError() { Object item = new Object(); Exception ex = new Exception(); listener.onProcessError(item, ex); @@ -66,7 +66,7 @@ public void testOnReadError() { } @Test - public void testSetListeners() throws Exception { + void testSetListeners() { compositeListener .setListeners(Collections.>singletonList(listener)); listener.beforeProcess(null); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeItemReadListenerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeItemReadListenerTests.java index adeeb7dfe4..4eac6ade07 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeItemReadListenerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeItemReadListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2008 the original author or authors. + * Copyright 2006-2022 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. @@ -19,8 +19,8 @@ import java.util.ArrayList; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.ItemReadListener; /** @@ -28,45 +28,44 @@ * @author Will Schipp * */ -public class CompositeItemReadListenerTests { +class CompositeItemReadListenerTests { ItemReadListener listener; CompositeItemReadListener compositeListener; @SuppressWarnings("unchecked") - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { listener = mock(ItemReadListener.class); compositeListener = new CompositeItemReadListener<>(); compositeListener.register(listener); } @Test - public void testBeforeRead() { + void testBeforeRead() { listener.beforeRead(); compositeListener.beforeRead(); } @Test - public void testAfterRead() { + void testAfterRead() { Object item = new Object(); listener.afterRead(item); compositeListener.afterRead(item); } @Test - public void testOnReadError() { + void testOnReadError() { Exception ex = new Exception(); listener.onReadError(ex); compositeListener.onReadError(ex); } - @SuppressWarnings("serial") @Test - public void testSetListeners() throws Exception { + void testSetListeners() { compositeListener.setListeners(new ArrayList>() { { add(listener); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeItemWriteListenerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeItemWriteListenerTests.java index 1fe68e8010..f576830615 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeItemWriteListenerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeItemWriteListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2008 the original author or authors. + * Copyright 2006-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,54 +21,53 @@ 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.springframework.batch.core.ItemWriteListener; /** * @author Lucas Ward * @author Will Schipp - * + * */ -public class CompositeItemWriteListenerTests { +class CompositeItemWriteListenerTests { ItemWriteListener listener; CompositeItemWriteListener compositeListener; @SuppressWarnings("unchecked") - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { listener = mock(ItemWriteListener.class); compositeListener = new CompositeItemWriteListener<>(); compositeListener.register(listener); } @Test - public void testBeforeWrite() { + void testBeforeWrite() { List item = Collections.singletonList(new Object()); listener.beforeWrite(item); compositeListener.beforeWrite(item); } @Test - public void testAfterWrite() { + void testAfterWrite() { List item = Collections.singletonList(new Object()); listener.afterWrite(item); compositeListener.afterWrite(item); } @Test - public void testOnWriteError() { + void testOnWriteError() { List item = Collections.singletonList(new Object()); Exception ex = new Exception(); listener.onWriteError(ex, item); compositeListener.onWriteError(ex, item); } - @SuppressWarnings("serial") @Test - public void testSetListeners() throws Exception { + void testSetListeners() { compositeListener.setListeners(new ArrayList>() { { add(listener); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeJobExecutionListenerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeJobExecutionListenerTests.java index b9d4999824..0ee3e43c1a 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeJobExecutionListenerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeJobExecutionListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -19,28 +19,26 @@ import java.util.Arrays; import java.util.List; -import junit.framework.TestCase; - +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobExecutionListener; import org.springframework.batch.core.JobInstance; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * @author Dave Syer * @author Mahmoud Ben Hassine * */ -public class CompositeJobExecutionListenerTests extends TestCase { +class CompositeJobExecutionListenerTests { - private CompositeJobExecutionListener listener = new CompositeJobExecutionListener(); + private final CompositeJobExecutionListener listener = new CompositeJobExecutionListener(); - private List list = new ArrayList<>(); + private final List list = new ArrayList<>(); - /** - * Test method for - * {@link org.springframework.batch.core.listener.CompositeJobExecutionListener#setListeners(List)} - */ - public void testSetListeners() { + @Test + void testSetListeners() { listener.setListeners(Arrays.asList(new JobExecutionListener() { @Override public void afterJob(JobExecution jobExecution) { @@ -56,12 +54,8 @@ public void afterJob(JobExecution jobExecution) { assertEquals(2, list.size()); } - /** - * Test method for - * {@link org.springframework.batch.core.listener.CompositeJobExecutionListener#register(org.springframework.batch.core.JobExecutionListener)} - * . - */ - public void testSetListener() { + @Test + void testSetListener() { listener.register(new JobExecutionListener() { @Override public void afterJob(JobExecution jobExecution) { @@ -72,12 +66,8 @@ public void afterJob(JobExecution jobExecution) { assertEquals(1, list.size()); } - /** - * Test method for - * {@link org.springframework.batch.core.listener.CompositeJobExecutionListener#beforeJob(JobExecution)} - * . - */ - public void testOpen() { + @Test + void testOpen() { listener.register(new JobExecutionListener() { @Override public void beforeJob(JobExecution stepExecution) { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeStepExecutionListenerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeStepExecutionListenerTests.java index 33408c19b1..e705523169 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeStepExecutionListenerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeStepExecutionListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -18,31 +18,28 @@ import java.util.ArrayList; import java.util.List; -import junit.framework.TestCase; - +import org.junit.jupiter.api.Test; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.StepExecutionListener; import org.springframework.lang.Nullable; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * @author Dave Syer * @author Mahmoud Ben Hassine * */ -public class CompositeStepExecutionListenerTests extends TestCase { +class CompositeStepExecutionListenerTests { - private CompositeStepExecutionListener listener = new CompositeStepExecutionListener(); + private final CompositeStepExecutionListener listener = new CompositeStepExecutionListener(); - private List list = new ArrayList<>(); + private final List list = new ArrayList<>(); - /** - * Test method for - * {@link org.springframework.batch.core.listener.CompositeStepExecutionListener#setListeners(org.springframework.batch.core.StepExecutionListener[])} - * . - */ - public void testSetListeners() { + @Test + void testSetListeners() { JobExecution jobExecution = new JobExecution(1L); StepExecution stepExecution = new StepExecution("s1", jobExecution); listener.setListeners(new StepExecutionListener[] { new StepExecutionListener() { @@ -65,12 +62,8 @@ public ExitStatus afterStep(StepExecution stepExecution) { assertEquals(2, list.size()); } - /** - * Test method for - * {@link org.springframework.batch.core.listener.CompositeStepExecutionListener#register(org.springframework.batch.core.StepExecutionListener)} - * . - */ - public void testSetListener() { + @Test + void testSetListener() { JobExecution jobExecution = new JobExecution(1L); StepExecution stepExecution = new StepExecution("s1", jobExecution); listener.register(new StepExecutionListener() { @@ -85,12 +78,8 @@ public ExitStatus afterStep(StepExecution stepExecution) { assertEquals(1, list.size()); } - /** - * Test method for - * {@link org.springframework.batch.core.listener.CompositeStepExecutionListener#beforeStep(StepExecution)} - * . - */ - public void testOpen() { + @Test + void testOpen() { listener.register(new StepExecutionListener() { @Override public void beforeStep(StepExecution stepExecution) { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/ExecutionContextPromotionListenerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/ExecutionContextPromotionListenerTests.java index 3b4ec3d963..10621d5cc8 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/ExecutionContextPromotionListenerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/ExecutionContextPromotionListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2010 the original author or authors. + * Copyright 2009-2022 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. @@ -15,20 +15,21 @@ */ package org.springframework.batch.core.listener; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; import org.springframework.util.Assert; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * Tests for {@link ExecutionContextPromotionListener}. */ -public class ExecutionContextPromotionListenerTests { +class ExecutionContextPromotionListenerTests { private static final String key = "testKey"; @@ -51,7 +52,7 @@ public class ExecutionContextPromotionListenerTests { * EXPECTED: key is promoted. key2 is not. */ @Test - public void promoteEntryNullStatuses() throws Exception { + void promoteEntryNullStatuses() throws Exception { ExecutionContextPromotionListener listener = new ExecutionContextPromotionListener(); JobExecution jobExecution = new JobExecution(1L); @@ -80,7 +81,7 @@ public void promoteEntryNullStatuses() throws Exception { * EXPECTED: key is promoted. key2 is not. */ @Test - public void promoteEntryStatusFound() throws Exception { + void promoteEntryStatusFound() throws Exception { ExecutionContextPromotionListener listener = new ExecutionContextPromotionListener(); listener.setStrict(true); @@ -111,7 +112,7 @@ public void promoteEntryStatusFound() throws Exception { * EXPECTED: no promotions. */ @Test - public void promoteEntryStatusNotFound() throws Exception { + void promoteEntryStatusNotFound() throws Exception { ExecutionContextPromotionListener listener = new ExecutionContextPromotionListener(); JobExecution jobExecution = new JobExecution(1L); @@ -140,7 +141,7 @@ public void promoteEntryStatusNotFound() throws Exception { * EXPECTED: key is promoted. key2 is not. */ @Test - public void promoteEntryStatusWildcardFound() throws Exception { + void promoteEntryStatusWildcardFound() throws Exception { ExecutionContextPromotionListener listener = new ExecutionContextPromotionListener(); JobExecution jobExecution = new JobExecution(1L); @@ -169,7 +170,7 @@ public void promoteEntryStatusWildcardFound() throws Exception { * EXPECTED: key is promoted. key2 is not. */ @Test - public void promoteEntriesKeyNotFound() throws Exception { + void promoteEntriesKeyNotFound() throws Exception { ExecutionContextPromotionListener listener = new ExecutionContextPromotionListener(); JobExecution jobExecution = new JobExecution(1L); @@ -196,7 +197,7 @@ public void promoteEntriesKeyNotFound() throws Exception { * EXPECTED: key is not erased. */ @Test - public void promoteEntriesKeyNotFoundInStep() throws Exception { + void promoteEntriesKeyNotFoundInStep() throws Exception { ExecutionContextPromotionListener listener = new ExecutionContextPromotionListener(); JobExecution jobExecution = new JobExecution(1L); @@ -222,8 +223,8 @@ public void promoteEntriesKeyNotFoundInStep() throws Exception { * * EXPECTED: IllegalArgumentException */ - @Test(expected = IllegalArgumentException.class) - public void promoteEntriesKeyNotFoundStrict() throws Exception { + @Test + void promoteEntriesKeyNotFoundStrict() throws Exception { ExecutionContextPromotionListener listener = new ExecutionContextPromotionListener(); listener.setStrict(true); @@ -239,22 +240,14 @@ public void promoteEntriesKeyNotFoundStrict() throws Exception { listener.setKeys(new String[] { key, key2 }); listener.afterPropertiesSet(); - listener.afterStep(stepExecution); - - assertEquals(value, jobExecution.getExecutionContext().getString(key)); - assertFalse(jobExecution.getExecutionContext().containsKey(key2)); + assertThrows(IllegalArgumentException.class, () -> listener.afterStep(stepExecution)); } - /** - * CONDITION: keys = NULL - * - * EXPECTED: IllegalArgumentException - */ - @Test(expected = IllegalArgumentException.class) - public void keysMustBeSet() throws Exception { + @Test + void keysMustBeSet() { ExecutionContextPromotionListener listener = new ExecutionContextPromotionListener(); // didn't set the keys, same as listener.setKeys(null); - listener.afterPropertiesSet(); + assertThrows(IllegalArgumentException.class, listener::afterPropertiesSet); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/ItemListenerErrorTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/ItemListenerErrorTests.java index fd7d765a94..25d6c8cb41 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/ItemListenerErrorTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/ItemListenerErrorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2021 the original author or authors. + * Copyright 2015-2022 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. @@ -15,16 +15,15 @@ */ package org.springframework.batch.core.listener; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Collections; import java.util.List; import javax.sql.DataSource; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ItemProcessListener; @@ -48,8 +47,7 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.lang.Nullable; import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * BATCH-2322 @@ -57,9 +55,8 @@ * @author Michael Minella * @author Mahmoud Ben Hassine */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { ItemListenerErrorTests.BatchConfiguration.class }) -public class ItemListenerErrorTests { +@SpringJUnitConfig(classes = { ItemListenerErrorTests.BatchConfiguration.class }) +class ItemListenerErrorTests { @Autowired private FailingListener listener; @@ -79,8 +76,8 @@ public class ItemListenerErrorTests { @Autowired private Job job; - @Before - public void setUp() { + @BeforeEach + void setUp() { listener.setMethodToThrowExceptionFrom(""); reader.setGoingToFail(false); processor.setGoingToFail(false); @@ -89,7 +86,7 @@ public void setUp() { @Test @DirtiesContext - public void testOnWriteError() throws Exception { + void testOnWriteError() throws Exception { listener.setMethodToThrowExceptionFrom("onWriteError"); writer.setGoingToFail(true); @@ -99,7 +96,7 @@ public void testOnWriteError() throws Exception { @Test @DirtiesContext - public void testOnReadError() throws Exception { + void testOnReadError() throws Exception { listener.setMethodToThrowExceptionFrom("onReadError"); reader.setGoingToFail(true); @@ -118,7 +115,7 @@ public void testOnReadError() throws Exception { @Test @DirtiesContext - public void testOnProcessError() throws Exception { + void testOnProcessError() throws Exception { listener.setMethodToThrowExceptionFrom("onProcessError"); processor.setGoingToFail(true); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/JobListenerFactoryBeanTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/JobListenerFactoryBeanTests.java index 3f92116bfe..ad365e1b9d 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/JobListenerFactoryBeanTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/JobListenerFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2022 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. @@ -15,8 +15,9 @@ */ package org.springframework.batch.core.listener; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.springframework.batch.core.listener.JobListenerMetaData.AFTER_JOB; import java.util.HashMap; @@ -24,8 +25,8 @@ import java.util.Map; 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.springframework.aop.framework.ProxyFactory; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobExecutionListener; @@ -38,17 +39,17 @@ * @author Lucas Ward * */ -public class JobListenerFactoryBeanTests { +class JobListenerFactoryBeanTests { JobListenerFactoryBean factoryBean; - @Before - public void setUp() { + @BeforeEach + void setUp() { factoryBean = new JobListenerFactoryBean(); } @Test - public void testWithInterface() throws Exception { + void testWithInterface() { JobListenerWithInterface delegate = new JobListenerWithInterface(); factoryBean.setDelegate(delegate); JobExecutionListener listener = (JobExecutionListener) factoryBean.getObject(); @@ -60,7 +61,7 @@ public void testWithInterface() throws Exception { } @Test - public void testWithAnnotations() throws Exception { + void testWithAnnotations() { AnnotatedTestClass delegate = new AnnotatedTestClass(); factoryBean.setDelegate(delegate); JobExecutionListener listener = (JobExecutionListener) factoryBean.getObject(); @@ -72,7 +73,7 @@ public void testWithAnnotations() throws Exception { } @Test - public void testFactoryMethod() throws Exception { + void testFactoryMethod() { JobListenerWithInterface delegate = new JobListenerWithInterface(); Object listener = JobListenerFactoryBean.getListener(delegate); assertTrue(listener instanceof JobExecutionListener); @@ -81,7 +82,7 @@ public void testFactoryMethod() throws Exception { } @Test - public void testVanillaInterfaceWithProxy() throws Exception { + void testVanillaInterfaceWithProxy() { JobListenerWithInterface delegate = new JobListenerWithInterface(); ProxyFactory factory = new ProxyFactory(delegate); factoryBean.setDelegate(factory.getProxy()); @@ -90,7 +91,7 @@ public void testVanillaInterfaceWithProxy() throws Exception { } @Test - public void testUseInHashSet() throws Exception { + void testUseInHashSet() { JobListenerWithInterface delegate = new JobListenerWithInterface(); Object listener = JobListenerFactoryBean.getListener(delegate); Object other = JobListenerFactoryBean.getListener(delegate); @@ -103,7 +104,7 @@ public void testUseInHashSet() throws Exception { } @Test - public void testAnnotationsIsListener() throws Exception { + void testAnnotationsIsListener() { assertTrue(JobListenerFactoryBean.isListener(new Object() { @BeforeJob public void foo(JobExecution execution) { @@ -112,12 +113,12 @@ public void foo(JobExecution execution) { } @Test - public void testInterfaceIsListener() throws Exception { + void testInterfaceIsListener() { assertTrue(JobListenerFactoryBean.isListener(new JobListenerWithInterface())); } @Test - public void testAnnotationsWithOrdered() throws Exception { + void testAnnotationsWithOrdered() { Object delegate = new Ordered() { @BeforeJob public void foo(JobExecution execution) { @@ -129,12 +130,12 @@ public int getOrder() { } }; JobExecutionListener listener = JobListenerFactoryBean.getListener(delegate); - assertTrue("Listener is not of correct type", listener instanceof Ordered); + assertTrue(listener instanceof Ordered, "Listener is not of correct type"); assertEquals(3, ((Ordered) listener).getOrder()); } @Test - public void testEqualityOfProxies() throws Exception { + void testEqualityOfProxies() { JobListenerWithInterface delegate = new JobListenerWithInterface(); Object listener1 = JobListenerFactoryBean.getListener(delegate); Object listener2 = JobListenerFactoryBean.getListener(delegate); @@ -142,7 +143,7 @@ public void testEqualityOfProxies() throws Exception { } @Test - public void testEmptySignatureAnnotation() { + void testEmptySignatureAnnotation() { AbstractTestComponent delegate = new AbstractTestComponent() { @AfterJob public void aMethod() { @@ -156,7 +157,7 @@ public void aMethod() { } @Test - public void testRightSignatureAnnotation() { + void testRightSignatureAnnotation() { AbstractTestComponent delegate = new AbstractTestComponent() { @AfterJob public void aMethod(JobExecution jobExecution) { @@ -170,8 +171,8 @@ public void aMethod(JobExecution jobExecution) { assertTrue(delegate.isExecuted()); } - @Test(expected = IllegalArgumentException.class) - public void testWrongSignatureAnnotation() { + @Test + void testWrongSignatureAnnotation() { AbstractTestComponent delegate = new AbstractTestComponent() { @AfterJob public void aMethod(Integer item) { @@ -179,11 +180,11 @@ public void aMethod(Integer item) { } }; factoryBean.setDelegate(delegate); - factoryBean.getObject(); + assertThrows(IllegalArgumentException.class, factoryBean::getObject); } @Test - public void testEmptySignatureNamedMethod() { + void testEmptySignatureNamedMethod() { AbstractTestComponent delegate = new AbstractTestComponent() { @SuppressWarnings("unused") public void aMethod() { @@ -200,7 +201,7 @@ public void aMethod() { } @Test - public void testRightSignatureNamedMethod() { + void testRightSignatureNamedMethod() { AbstractTestComponent delegate = new AbstractTestComponent() { @SuppressWarnings("unused") public void aMethod(JobExecution jobExecution) { @@ -217,8 +218,8 @@ public void aMethod(JobExecution jobExecution) { assertTrue(delegate.isExecuted()); } - @Test(expected = IllegalArgumentException.class) - public void testWrongSignatureNamedMethod() { + @Test + void testWrongSignatureNamedMethod() { AbstractTestComponent delegate = new AbstractTestComponent() { @SuppressWarnings("unused") public void aMethod(Integer item) { @@ -229,7 +230,7 @@ public void aMethod(Integer item) { Map metaDataMap = new HashMap<>(); metaDataMap.put(AFTER_JOB.getPropertyName(), "aMethod"); factoryBean.setMetaDataMap(metaDataMap); - factoryBean.getObject(); + assertThrows(IllegalArgumentException.class, factoryBean::getObject); } private class JobListenerWithInterface implements JobExecutionListener { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/JobParameterExecutionContextCopyListenerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/JobParameterExecutionContextCopyListenerTests.java index 03bbc5419f..a3d29cd071 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/JobParameterExecutionContextCopyListenerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/JobParameterExecutionContextCopyListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,11 +15,11 @@ */ package org.springframework.batch.core.listener; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInstance; import org.springframework.batch.core.JobParameters; @@ -30,26 +30,26 @@ * @author Dave Syer * */ -public class JobParameterExecutionContextCopyListenerTests { +class JobParameterExecutionContextCopyListenerTests { - private JobParameterExecutionContextCopyListener listener = new JobParameterExecutionContextCopyListener(); + private final JobParameterExecutionContextCopyListener listener = new JobParameterExecutionContextCopyListener(); private StepExecution stepExecution; - @Before - public void createExecution() { + @BeforeEach + void createExecution() { JobParameters jobParameters = new JobParametersBuilder().addString("foo", "bar").toJobParameters(); stepExecution = new StepExecution("foo", new JobExecution(new JobInstance(123L, "job"), jobParameters)); } @Test - public void testBeforeStep() { + void testBeforeStep() { listener.beforeStep(stepExecution); assertEquals("bar", stepExecution.getExecutionContext().get("foo")); } @Test - public void testSetKeys() { + void testSetKeys() { listener.setKeys(new String[] {}); listener.beforeStep(stepExecution); assertFalse(stepExecution.getExecutionContext().containsKey("foo")); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/MulticasterBatchListenerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/MulticasterBatchListenerTests.java index 51167118ce..63bcb291f0 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/MulticasterBatchListenerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/MulticasterBatchListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,15 +15,15 @@ */ package org.springframework.batch.core.listener; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; 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.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.SkipListener; @@ -45,21 +45,21 @@ * @author Mahmoud Ben Hassine * */ -public class MulticasterBatchListenerTests { +class MulticasterBatchListenerTests { - private MulticasterBatchListener multicast = new MulticasterBatchListener<>(); + private final MulticasterBatchListener multicast = new MulticasterBatchListener<>(); private int count = 0; private boolean error = false; - @Before - public void setUp() { + @BeforeEach + void setUp() { multicast.register(new CountingStepListenerSupport()); } @Test - public void testSetListeners() { + void testSetListeners() { JobExecution jobExecution = new JobExecution(1L); StepExecution stepExecution = new StepExecution("s1", jobExecution); multicast.setListeners(Arrays.asList(new StepListenerSupport() { @@ -81,7 +81,7 @@ public ExitStatus afterStep(StepExecution stepExecution) { * . */ @Test - public void testRegister() { + void testRegister() { JobExecution jobExecution = new JobExecution(1L); StepExecution stepExecution = new StepExecution("s1", jobExecution); multicast.register(new StepListenerSupport() { @@ -102,17 +102,11 @@ public ExitStatus afterStep(StepExecution stepExecution) { * . */ @Test - public void testAfterStepFails() { + void testAfterStepFails() { error = true; - try { - multicast.afterStep(null); - fail("Expected StepListenerFailedException"); - } - catch (StepListenerFailedException e) { - // expected - String message = e.getCause().getMessage(); - assertEquals("Wrong message: " + message, "listener error", message); - } + Exception exception = assertThrows(StepListenerFailedException.class, () -> multicast.afterStep(null)); + String message = exception.getCause().getMessage(); + assertEquals("listener error", message, "Wrong message: " + message); assertEquals(1, count); } @@ -122,7 +116,7 @@ public void testAfterStepFails() { * . */ @Test - public void testBeforeStep() { + void testBeforeStep() { multicast.beforeStep(null); assertEquals(1, count); } @@ -133,17 +127,11 @@ public void testBeforeStep() { * . */ @Test - public void testBeforeStepFails() { + void testBeforeStepFails() { error = true; - try { - multicast.beforeStep(null); - fail("Expected StepListenerFailedException"); - } - catch (StepListenerFailedException e) { - // expected - String message = e.getCause().getMessage(); - assertEquals("Wrong message: " + message, "listener error", message); - } + Exception exception = assertThrows(StepListenerFailedException.class, () -> multicast.beforeStep(null)); + String message = exception.getCause().getMessage(); + assertEquals("listener error", message, "Wrong message: " + message); assertEquals(1, count); } @@ -153,7 +141,7 @@ public void testBeforeStepFails() { * . */ @Test - public void testAfterChunk() { + void testAfterChunk() { multicast.afterChunk(null); assertEquals(1, count); } @@ -164,17 +152,11 @@ public void testAfterChunk() { * . */ @Test - public void testAfterChunkFails() { + void testAfterChunkFails() { error = true; - try { - multicast.afterChunk(null); - fail("Expected StepListenerFailedException"); - } - catch (StepListenerFailedException e) { - // expected - String message = e.getCause().getMessage(); - assertEquals("Wrong message: " + message, "listener error", message); - } + Exception exception = assertThrows(StepListenerFailedException.class, () -> multicast.afterChunk(null)); + String message = exception.getCause().getMessage(); + assertEquals("listener error", message, "Wrong message: " + message); assertEquals(1, count); } @@ -184,7 +166,7 @@ public void testAfterChunkFails() { * . */ @Test - public void testBeforeChunk() { + void testBeforeChunk() { multicast.beforeChunk(null); assertEquals(1, count); } @@ -195,17 +177,11 @@ public void testBeforeChunk() { * . */ @Test - public void testBeforeChunkFails() { + void testBeforeChunkFails() { error = true; - try { - multicast.beforeChunk(null); - fail("Expected StepListenerFailedException"); - } - catch (StepListenerFailedException e) { - // expected - String message = e.getCause().getMessage(); - assertEquals("Wrong message: " + message, "listener error", message); - } + Exception exception = assertThrows(StepListenerFailedException.class, () -> multicast.beforeChunk(null)); + String message = exception.getCause().getMessage(); + assertEquals("listener error", message, "Wrong message: " + message); assertEquals(1, count); } @@ -215,7 +191,7 @@ public void testBeforeChunkFails() { * . */ @Test - public void testAfterRead() { + void testAfterRead() { multicast.afterRead(null); assertEquals(1, count); } @@ -226,17 +202,11 @@ public void testAfterRead() { * . */ @Test - public void testAfterReadFails() { + void testAfterReadFails() { error = true; - try { - multicast.afterRead(null); - fail("Expected StepListenerFailedException"); - } - catch (StepListenerFailedException e) { - // expected - String message = e.getCause().getMessage(); - assertEquals("Wrong message: " + message, "listener error", message); - } + Exception exception = assertThrows(StepListenerFailedException.class, () -> multicast.afterRead(null)); + String message = exception.getCause().getMessage(); + assertEquals("listener error", message, "Wrong message: " + message); assertEquals(1, count); } @@ -246,7 +216,7 @@ public void testAfterReadFails() { * . */ @Test - public void testBeforeRead() { + void testBeforeRead() { multicast.beforeRead(); assertEquals(1, count); } @@ -257,17 +227,11 @@ public void testBeforeRead() { * . */ @Test - public void testBeforeReadFails() { + void testBeforeReadFails() { error = true; - try { - multicast.beforeRead(); - fail("Expected StepListenerFailedException"); - } - catch (StepListenerFailedException e) { - // expected - String message = e.getCause().getMessage(); - assertEquals("Wrong message: " + message, "listener error", message); - } + Exception exception = assertThrows(StepListenerFailedException.class, () -> multicast.beforeRead()); + String message = exception.getCause().getMessage(); + assertEquals("listener error", message, "Wrong message: " + message); assertEquals(1, count); } @@ -277,7 +241,7 @@ public void testBeforeReadFails() { * . */ @Test - public void testOnReadError() { + void testOnReadError() { multicast.onReadError(new RuntimeException("foo")); assertEquals(1, count); } @@ -288,17 +252,12 @@ public void testOnReadError() { * . */ @Test - public void testOnReadErrorFails() { + void testOnReadErrorFails() { error = true; - try { - multicast.onReadError(new RuntimeException("foo")); - fail("Expected StepListenerFailedException"); - } - catch (StepListenerFailedException e) { - // expected - String message = e.getCause().getMessage(); - assertEquals("Wrong message: " + message, "listener error", message); - } + Exception exception = assertThrows(StepListenerFailedException.class, + () -> multicast.onReadError(new RuntimeException("foo"))); + String message = exception.getCause().getMessage(); + assertEquals("listener error", message, "Wrong message: " + message); assertEquals(1, count); } @@ -308,7 +267,7 @@ public void testOnReadErrorFails() { * . */ @Test - public void testAfterWrite() { + void testAfterWrite() { multicast.afterWrite(null); assertEquals(1, count); } @@ -319,17 +278,11 @@ public void testAfterWrite() { * . */ @Test - public void testAfterWriteFails() { + void testAfterWriteFails() { error = true; - try { - multicast.afterWrite(null); - fail("Expected StepListenerFailedException"); - } - catch (StepListenerFailedException e) { - // expected - String message = e.getCause().getMessage(); - assertEquals("Wrong message: " + message, "listener error", message); - } + Exception exception = assertThrows(StepListenerFailedException.class, () -> multicast.afterWrite(null)); + String message = exception.getCause().getMessage(); + assertEquals("listener error", message, "Wrong message: " + message); assertEquals(1, count); } @@ -339,7 +292,7 @@ public void testAfterWriteFails() { * . */ @Test - public void testBeforeWrite() { + void testBeforeWrite() { multicast.beforeWrite(null); assertEquals(1, count); } @@ -350,17 +303,11 @@ public void testBeforeWrite() { * . */ @Test - public void testBeforeWriteFails() { + void testBeforeWriteFails() { error = true; - try { - multicast.beforeWrite(null); - fail("Expected StepListenerFailedException"); - } - catch (StepListenerFailedException e) { - // expected - String message = e.getCause().getMessage(); - assertEquals("Wrong message: " + message, "listener error", message); - } + Exception exception = assertThrows(StepListenerFailedException.class, () -> multicast.beforeWrite(null)); + String message = exception.getCause().getMessage(); + assertEquals("listener error", message, "Wrong message: " + message); assertEquals(1, count); } @@ -370,7 +317,7 @@ public void testBeforeWriteFails() { * . */ @Test - public void testOnWriteError() { + void testOnWriteError() { multicast.onWriteError(new RuntimeException("foo"), null); assertEquals(1, count); } @@ -381,17 +328,12 @@ public void testOnWriteError() { * . */ @Test - public void testOnWriteErrorFails() { + void testOnWriteErrorFails() { error = true; - try { - multicast.onWriteError(new RuntimeException("foo"), null); - fail("Expected StepListenerFailedException"); - } - catch (StepListenerFailedException e) { - // expected - String message = e.getCause().getMessage(); - assertEquals("Wrong message: " + message, "listener error", message); - } + Exception exception = assertThrows(StepListenerFailedException.class, + () -> multicast.onWriteError(new RuntimeException("foo"), null)); + String message = exception.getCause().getMessage(); + assertEquals("listener error", message, "Wrong message: " + message); assertEquals(1, count); } @@ -401,7 +343,7 @@ public void testOnWriteErrorFails() { * . */ @Test - public void testOnSkipInRead() { + void testOnSkipInRead() { multicast.register(new SkipListener() { @Override public void onSkipInRead(Throwable t) { @@ -418,7 +360,7 @@ public void onSkipInRead(Throwable t) { * . */ @Test - public void testOnSkipInReadFails() { + void testOnSkipInReadFails() { multicast.register(new SkipListener() { @Override public void onSkipInRead(Throwable t) { @@ -426,15 +368,10 @@ public void onSkipInRead(Throwable t) { throw new RuntimeException("foo"); } }); - try { - multicast.onSkipInRead(new RuntimeException("bar")); - fail("Expected RuntimeException"); - } - catch (RuntimeException e) { - // expected - String message = e.getMessage(); - assertEquals("Wrong message: " + message, "foo", message); - } + Exception exception = assertThrows(RuntimeException.class, + () -> multicast.onSkipInRead(new RuntimeException("bar"))); + String message = exception.getMessage(); + assertEquals("foo", message, "Wrong message: " + message); assertEquals(1, count); } @@ -444,7 +381,7 @@ public void onSkipInRead(Throwable t) { * . */ @Test - public void testOnSkipInWrite() { + void testOnSkipInWrite() { multicast.register(new SkipListener() { @Override public void onSkipInWrite(Object item, Throwable t) { @@ -461,7 +398,7 @@ public void onSkipInWrite(Object item, Throwable t) { * . */ @Test - public void testOnSkipInWriteFails() { + void testOnSkipInWriteFails() { multicast.register(new SkipListener() { @Override public void onSkipInWrite(Object item, Throwable t) { @@ -469,15 +406,10 @@ public void onSkipInWrite(Object item, Throwable t) { throw new RuntimeException("foo"); } }); - try { - multicast.onSkipInWrite(null, new RuntimeException("bar")); - fail("Expected RuntimeException"); - } - catch (RuntimeException e) { - // expected - String message = e.getMessage(); - assertEquals("Wrong message: " + message, "foo", message); - } + Exception exception = assertThrows(RuntimeException.class, + () -> multicast.onSkipInWrite(null, new RuntimeException("bar"))); + String message = exception.getMessage(); + assertEquals("foo", message, "Wrong message: " + message); assertEquals(1, count); } @@ -487,7 +419,7 @@ public void onSkipInWrite(Object item, Throwable t) { * . */ @Test - public void testOnSkipInProcess() { + void testOnSkipInProcess() { multicast.register(new SkipListener() { @Override public void onSkipInProcess(Object item, Throwable t) { @@ -504,7 +436,7 @@ public void onSkipInProcess(Object item, Throwable t) { * . */ @Test - public void testOnSkipInProcessFails() { + void testOnSkipInProcessFails() { multicast.register(new SkipListener() { @Override public void onSkipInProcess(Object item, Throwable t) { @@ -512,160 +444,107 @@ public void onSkipInProcess(Object item, Throwable t) { throw new RuntimeException("foo"); } }); - try { - multicast.onSkipInProcess(null, new RuntimeException("bar")); - fail("Expected RuntimeException"); - } - catch (RuntimeException e) { - // expected - String message = e.getMessage(); - assertEquals("Wrong message: " + message, "foo", message); - } + Exception exception = assertThrows(RuntimeException.class, + () -> multicast.onSkipInProcess(null, new RuntimeException("bar"))); + String message = exception.getMessage(); + assertEquals("foo", message, "Wrong message: " + message); assertEquals(1, count); } @Test - public void testBeforeReadFails_withAnnotatedListener() { + void testBeforeReadFails_withAnnotatedListener() { StepListener listener = StepListenerFactoryBean.getListener(new AnnotationBasedStepListener()); multicast.register(listener); - try { - multicast.beforeRead(); - fail("Expected StepListenerFailedException"); - } - catch (StepListenerFailedException e) { - // expected - Throwable cause = e.getCause(); - String message = cause.getMessage(); - assertTrue(cause instanceof IllegalStateException); - assertEquals("Wrong message: " + message, "listener error", message); - } + Exception exception = assertThrows(StepListenerFailedException.class, () -> multicast.beforeRead()); + Throwable cause = exception.getCause(); + String message = cause.getMessage(); + assertTrue(cause instanceof IllegalStateException); + assertEquals("listener error", message, "Wrong message: " + message); } @Test - public void testAfterReadFails_withAnnotatedListener() { + void testAfterReadFails_withAnnotatedListener() { StepListener listener = StepListenerFactoryBean.getListener(new AnnotationBasedStepListener()); multicast.register(listener); - try { - multicast.afterRead(null); - fail("Expected StepListenerFailedException"); - } - catch (StepListenerFailedException e) { - // expected - Throwable cause = e.getCause(); - String message = cause.getMessage(); - assertTrue(cause instanceof IllegalStateException); - assertEquals("Wrong message: " + message, "listener error", message); - } + Exception exception = assertThrows(StepListenerFailedException.class, () -> multicast.afterRead(null)); + Throwable cause = exception.getCause(); + String message = cause.getMessage(); + assertTrue(cause instanceof IllegalStateException); + assertEquals("listener error", message, "Wrong message: " + message); } @Test - public void testBeforeProcessFails_withAnnotatedListener() { + void testBeforeProcessFails_withAnnotatedListener() { StepListener listener = StepListenerFactoryBean.getListener(new AnnotationBasedStepListener()); multicast.register(listener); - try { - multicast.beforeProcess(null); - fail("Expected StepListenerFailedException"); - } - catch (StepListenerFailedException e) { - // expected - Throwable cause = e.getCause(); - String message = cause.getMessage(); - assertTrue(cause instanceof IllegalStateException); - assertEquals("Wrong message: " + message, "listener error", message); - } + Exception exception = assertThrows(StepListenerFailedException.class, () -> multicast.beforeProcess(null)); + Throwable cause = exception.getCause(); + String message = cause.getMessage(); + assertTrue(cause instanceof IllegalStateException); + assertEquals("listener error", message, "Wrong message: " + message); } @Test - public void testAfterProcessFails_withAnnotatedListener() { + void testAfterProcessFails_withAnnotatedListener() { StepListener listener = StepListenerFactoryBean.getListener(new AnnotationBasedStepListener()); multicast.register(listener); - try { - multicast.afterProcess(null, null); - fail("Expected StepListenerFailedException"); - } - catch (StepListenerFailedException e) { - // expected - Throwable cause = e.getCause(); - String message = cause.getMessage(); - assertTrue(cause instanceof IllegalStateException); - assertEquals("Wrong message: " + message, "listener error", message); - } + Exception exception = assertThrows(StepListenerFailedException.class, () -> multicast.afterProcess(null, null)); + Throwable cause = exception.getCause(); + String message = cause.getMessage(); + assertTrue(cause instanceof IllegalStateException); + assertEquals("listener error", message, "Wrong message: " + message); } @Test - public void testBeforeWriteFails_withAnnotatedListener() { + void testBeforeWriteFails_withAnnotatedListener() { StepListener listener = StepListenerFactoryBean.getListener(new AnnotationBasedStepListener()); multicast.register(listener); - try { - multicast.beforeWrite(null); - fail("Expected StepListenerFailedException"); - } - catch (StepListenerFailedException e) { - // expected - Throwable cause = e.getCause(); - String message = cause.getMessage(); - assertTrue(cause instanceof IllegalStateException); - assertEquals("Wrong message: " + message, "listener error", message); - } + Exception exception = assertThrows(StepListenerFailedException.class, () -> multicast.beforeWrite(null)); + Throwable cause = exception.getCause(); + String message = cause.getMessage(); + assertTrue(cause instanceof IllegalStateException); + assertEquals("listener error", message, "Wrong message: " + message); } @Test - public void testAfterWriteFails_withAnnotatedListener() { + void testAfterWriteFails_withAnnotatedListener() { StepListener listener = StepListenerFactoryBean.getListener(new AnnotationBasedStepListener()); multicast.register(listener); - try { - multicast.afterWrite(null); - fail("Expected StepListenerFailedException"); - } - catch (StepListenerFailedException e) { - // expected - Throwable cause = e.getCause(); - String message = cause.getMessage(); - assertTrue(cause instanceof IllegalStateException); - assertEquals("Wrong message: " + message, "listener error", message); - } + Exception exception = assertThrows(StepListenerFailedException.class, () -> multicast.afterWrite(null)); + Throwable cause = exception.getCause(); + String message = cause.getMessage(); + assertTrue(cause instanceof IllegalStateException); + assertEquals("listener error", message, "Wrong message: " + message); } @Test - public void testBeforeChunkFails_withAnnotatedListener() { + void testBeforeChunkFails_withAnnotatedListener() { StepListener listener = StepListenerFactoryBean.getListener(new AnnotationBasedStepListener()); multicast.register(listener); - try { - multicast.beforeChunk(null); - fail("Expected StepListenerFailedException"); - } - catch (StepListenerFailedException e) { - // expected - Throwable cause = e.getCause(); - String message = cause.getMessage(); - assertTrue(cause instanceof IllegalStateException); - assertEquals("Wrong message: " + message, "listener error", message); - } + Exception exception = assertThrows(StepListenerFailedException.class, () -> multicast.beforeChunk(null)); + Throwable cause = exception.getCause(); + String message = cause.getMessage(); + assertTrue(cause instanceof IllegalStateException); + assertEquals("listener error", message, "Wrong message: " + message); } @Test - public void testAfterChunkFails_withAnnotatedListener() { + void testAfterChunkFails_withAnnotatedListener() { StepListener listener = StepListenerFactoryBean.getListener(new AnnotationBasedStepListener()); multicast.register(listener); - try { - multicast.afterChunk(null); - fail("Expected StepListenerFailedException"); - } - catch (StepListenerFailedException e) { - // expected - Throwable cause = e.getCause(); - String message = cause.getMessage(); - assertTrue(cause instanceof IllegalStateException); - assertEquals("Wrong message: " + message, "listener error", message); - } + Exception exception = assertThrows(StepListenerFailedException.class, () -> multicast.afterChunk(null)); + Throwable cause = exception.getCause(); + String message = cause.getMessage(); + assertTrue(cause instanceof IllegalStateException); + assertEquals("listener error", message, "Wrong message: " + message); } private final class AnnotationBasedStepListener { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/OrderedCompositeTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/OrderedCompositeTests.java index 2648b343fb..c4db988959 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/OrderedCompositeTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/OrderedCompositeTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2013 the original author or authors. + * Copyright 2006-2022 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. @@ -15,13 +15,13 @@ */ package org.springframework.batch.core.listener; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import java.util.Arrays; import java.util.Iterator; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; @@ -29,12 +29,12 @@ * @author Dave Syer * */ -public class OrderedCompositeTests { +class OrderedCompositeTests { - private OrderedComposite list = new OrderedComposite<>(); + private final OrderedComposite list = new OrderedComposite<>(); @Test - public void testSetItems() { + void testSetItems() { list.setItems(Arrays.asList(new Object[] { "1", "2" })); Iterator iterator = list.iterator(); assertEquals("1", iterator.next()); @@ -42,7 +42,7 @@ public void testSetItems() { } @Test - public void testSetSameObject() { + void testSetSameObject() { list.setItems(Arrays.asList(new Object[] { "1", "1" })); Iterator iterator = list.iterator(); assertEquals("1", iterator.next()); @@ -50,7 +50,7 @@ public void testSetSameObject() { } @Test - public void testAdd() { + void testAdd() { list.setItems(Arrays.asList((Object) "1")); list.add("3"); Iterator iterator = list.iterator(); @@ -59,7 +59,7 @@ public void testAdd() { } @Test - public void testAddOrdered() { + void testAddOrdered() { list.setItems(Arrays.asList((Object) "1")); list.add(new Ordered() { @Override @@ -73,7 +73,7 @@ public int getOrder() { } @Test - public void testAddMultipleOrdered() { + void testAddMultipleOrdered() { list.setItems(Arrays.asList((Object) "1")); list.add(new Ordered() { @Override @@ -94,7 +94,7 @@ public int getOrder() { } @Test - public void testAddDuplicateOrdered() { + void testAddDuplicateOrdered() { list.setItems(Arrays.asList((Object) "1")); list.add(new Ordered() { @Override @@ -115,7 +115,7 @@ public int getOrder() { } @Test - public void testAddAnnotationOrdered() { + void testAddAnnotationOrdered() { list.add(new Ordered() { @Override public int getOrder() { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/StepListenerFactoryBeanTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/StepListenerFactoryBeanTests.java index d216d66ae2..44bb58098f 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/StepListenerFactoryBeanTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/StepListenerFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2022 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. @@ -23,8 +23,7 @@ import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.aop.framework.ProxyFactory; import org.springframework.batch.core.ChunkListener; @@ -58,9 +57,10 @@ import org.springframework.lang.Nullable; import org.springframework.util.Assert; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.springframework.batch.core.listener.StepListenerMetaData.AFTER_STEP; import static org.springframework.batch.core.listener.StepListenerMetaData.AFTER_WRITE; @@ -68,22 +68,17 @@ * @author Lucas Ward * */ -public class StepListenerFactoryBeanTests { +class StepListenerFactoryBeanTests { - private StepListenerFactoryBean factoryBean; + private final StepListenerFactoryBean factoryBean = new StepListenerFactoryBean(); - private JobExecution jobExecution = new JobExecution(11L); + private final JobExecution jobExecution = new JobExecution(11L); - private StepExecution stepExecution = new StepExecution("testStep", jobExecution); - - @Before - public void setUp() { - factoryBean = new StepListenerFactoryBean(); - } + private final StepExecution stepExecution = new StepExecution("testStep", jobExecution); @Test @SuppressWarnings("unchecked") - public void testStepAndChunk() throws Exception { + void testStepAndChunk() { TestListener testListener = new TestListener(); factoryBean.setDelegate(testListener); // Map metaDataMap = new HashMap(); @@ -130,7 +125,7 @@ public void testStepAndChunk() throws Exception { } @Test - public void testAllThreeTypes() throws Exception { + void testAllThreeTypes() { // Test to make sure if someone has annotated a method, implemented the // interface, and given a string // method name, that all three will be called @@ -145,7 +140,7 @@ public void testAllThreeTypes() throws Exception { } @Test - public void testAnnotatingInterfaceResultsInOneCall() throws Exception { + void testAnnotatingInterfaceResultsInOneCall() { MultipleAfterStep delegate = new MultipleAfterStep(); factoryBean.setDelegate(delegate); Map metaDataMap = new HashMap<>(); @@ -157,7 +152,7 @@ public void testAnnotatingInterfaceResultsInOneCall() throws Exception { } @Test - public void testVanillaInterface() throws Exception { + void testVanillaInterface() { MultipleAfterStep delegate = new MultipleAfterStep(); factoryBean.setDelegate(delegate); Object listener = factoryBean.getObject(); @@ -167,7 +162,7 @@ public void testVanillaInterface() throws Exception { } @Test - public void testVanillaInterfaceWithProxy() throws Exception { + void testVanillaInterfaceWithProxy() { MultipleAfterStep delegate = new MultipleAfterStep(); ProxyFactory factory = new ProxyFactory(delegate); factoryBean.setDelegate(factory.getProxy()); @@ -178,7 +173,7 @@ public void testVanillaInterfaceWithProxy() throws Exception { } @Test - public void testFactoryMethod() throws Exception { + void testFactoryMethod() { MultipleAfterStep delegate = new MultipleAfterStep(); Object listener = StepListenerFactoryBean.getListener(delegate); assertTrue(listener instanceof StepExecutionListener); @@ -188,7 +183,7 @@ public void testFactoryMethod() throws Exception { } @Test - public void testAnnotationsWithOrdered() throws Exception { + void testAnnotationsWithOrdered() { Object delegate = new Ordered() { @BeforeStep public void foo(StepExecution execution) { @@ -200,12 +195,12 @@ public int getOrder() { } }; StepListener listener = StepListenerFactoryBean.getListener(delegate); - assertTrue("Listener is not of correct type", listener instanceof Ordered); + assertTrue(listener instanceof Ordered, "Listener is not of correct type"); assertEquals(3, ((Ordered) listener).getOrder()); } @Test - public void testProxiedAnnotationsFactoryMethod() throws Exception { + void testProxiedAnnotationsFactoryMethod() { Object delegate = new InitializingBean() { @BeforeStep public void foo(StepExecution execution) { @@ -216,17 +211,17 @@ public void afterPropertiesSet() throws Exception { } }; ProxyFactory factory = new ProxyFactory(delegate); - assertTrue("Listener is not of correct type", - StepListenerFactoryBean.getListener(factory.getProxy()) instanceof StepExecutionListener); + assertTrue(StepListenerFactoryBean.getListener(factory.getProxy()) instanceof StepExecutionListener, + "Listener is not of correct type"); } @Test - public void testInterfaceIsListener() throws Exception { + void testInterfaceIsListener() { assertTrue(StepListenerFactoryBean.isListener(new ThreeStepExecutionListener())); } @Test - public void testAnnotationsIsListener() throws Exception { + void testAnnotationsIsListener() { assertTrue(StepListenerFactoryBean.isListener(new Object() { @BeforeStep public void foo(StepExecution execution) { @@ -235,7 +230,7 @@ public void foo(StepExecution execution) { } @Test - public void testProxyWithNoTarget() throws Exception { + void testProxyWithNoTarget() { ProxyFactory factory = new ProxyFactory(); factory.addInterface(DataSource.class); factory.addAdvice(new MethodInterceptor() { @@ -249,7 +244,7 @@ public Object invoke(MethodInvocation invocation) throws Throwable { } @Test - public void testProxiedAnnotationsIsListener() throws Exception { + void testProxiedAnnotationsIsListener() { Object delegate = new InitializingBean() { @BeforeStep public void foo(StepExecution execution) { @@ -266,19 +261,19 @@ public void afterPropertiesSet() throws Exception { } @Test - public void testMixedIsListener() throws Exception { + void testMixedIsListener() { assertTrue(StepListenerFactoryBean.isListener(new MultipleAfterStep())); } @Test - public void testNonListener() throws Exception { + void testNonListener() { Object delegate = new Object(); factoryBean.setDelegate(delegate); assertTrue(factoryBean.getObject() instanceof StepListener); } @Test - public void testEmptySignatureAnnotation() { + void testEmptySignatureAnnotation() { AbstractTestComponent delegate = new AbstractTestComponent() { @AfterWrite public void aMethod() { @@ -293,7 +288,7 @@ public void aMethod() { } @Test - public void testRightSignatureAnnotation() { + void testRightSignatureAnnotation() { AbstractTestComponent delegate = new AbstractTestComponent() { @AfterWrite public void aMethod(List items) { @@ -309,8 +304,8 @@ public void aMethod(List items) { assertTrue(delegate.isExecuted()); } - @Test(expected = IllegalArgumentException.class) - public void testWrongSignatureAnnotation() { + @Test + void testWrongSignatureAnnotation() { AbstractTestComponent delegate = new AbstractTestComponent() { @AfterWrite public void aMethod(Integer item) { @@ -318,11 +313,11 @@ public void aMethod(Integer item) { } }; factoryBean.setDelegate(delegate); - factoryBean.getObject(); + assertThrows(IllegalArgumentException.class, factoryBean::getObject); } @Test - public void testEmptySignatureNamedMethod() { + void testEmptySignatureNamedMethod() { AbstractTestComponent delegate = new AbstractTestComponent() { @SuppressWarnings("unused") public void aMethod() { @@ -340,7 +335,7 @@ public void aMethod() { } @Test - public void testRightSignatureNamedMethod() { + void testRightSignatureNamedMethod() { AbstractTestComponent delegate = new AbstractTestComponent() { @SuppressWarnings("unused") public void aMethod(List items) { @@ -359,8 +354,8 @@ public void aMethod(List items) { assertTrue(delegate.isExecuted()); } - @Test(expected = IllegalArgumentException.class) - public void testWrongSignatureNamedMethod() { + @Test + void testWrongSignatureNamedMethod() { AbstractTestComponent delegate = new AbstractTestComponent() { @SuppressWarnings("unused") public void aMethod(Integer item) { @@ -371,7 +366,7 @@ public void aMethod(Integer item) { Map metaDataMap = new HashMap<>(); metaDataMap.put(AFTER_WRITE.getPropertyName(), "aMethod"); factoryBean.setMetaDataMap(metaDataMap); - factoryBean.getObject(); + assertThrows(IllegalArgumentException.class, factoryBean::getObject); } private class MultipleAfterStep implements StepExecutionListener { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/StepListenerFailedExceptionTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/StepListenerFailedExceptionTests.java index 0bcc6d365c..b2cf8dffcc 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/StepListenerFailedExceptionTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/StepListenerFailedExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2012 the original author or authors. + * Copyright 2006-2022 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. @@ -15,19 +15,19 @@ */ package org.springframework.batch.core.listener; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author Dave Syer * @author Michael Minella * */ -public class StepListenerFailedExceptionTests { +class StepListenerFailedExceptionTests { @Test - public void testExceptionStringThrowable() throws Exception { + void testExceptionStringThrowable() { Exception exception = new StepListenerFailedException("foo", new IllegalStateException("bar")); assertEquals("foo", exception.getMessage().substring(0, 3)); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/StepListenerMethodInterceptorTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/StepListenerMethodInterceptorTests.java index 77041cfee9..07b9477056 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/StepListenerMethodInterceptorTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/StepListenerMethodInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2012 the original author or authors. + * Copyright 2008-2022 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. @@ -15,7 +15,7 @@ */ package org.springframework.batch.core.listener; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Method; @@ -25,8 +25,7 @@ import java.util.Set; import org.aopalliance.intercept.MethodInvocation; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.support.MethodInvoker; import org.springframework.batch.support.MethodInvokerUtils; @@ -36,15 +35,10 @@ public class StepListenerMethodInterceptorTests { MethodInvokerMethodInterceptor interceptor; - TestClass testClass; - - @Before - public void setUp() { - testClass = new TestClass(); - } + private final TestClass testClass = new TestClass(); @Test - public void testNormalCase() throws Throwable { + void testNormalCase() throws Throwable { Map> invokerMap = new HashMap<>(); for (Method method : TestClass.class.getMethods()) { @@ -58,7 +52,7 @@ public void testNormalCase() throws Throwable { } @Test - public void testMultipleInvokersPerName() throws Throwable { + void testMultipleInvokersPerName() throws Throwable { Map> invokerMap = new HashMap<>(); Set invokers = asSet(MethodInvokerUtils.getMethodInvokerByName(testClass, "method1", false)); @@ -72,7 +66,7 @@ public void testMultipleInvokersPerName() throws Throwable { } @Test - public void testExitStatusReturn() throws Throwable { + void testExitStatusReturn() throws Throwable { Map> invokerMap = new HashMap<>(); Set invokers = asSet(MethodInvokerUtils.getMethodInvokerByName(testClass, "method3", false)); invokers.add(MethodInvokerUtils.getMethodInvokerByName(testClass, "method3", false)); @@ -89,7 +83,7 @@ public Set asSet(MethodInvoker methodInvoker) { } @SuppressWarnings("unused") - private class TestClass { + private static class TestClass { int method1Count = 0; @@ -113,7 +107,7 @@ public ExitStatus method3() { } @SuppressWarnings("unused") - private class StubMethodInvocation implements MethodInvocation { + private static class StubMethodInvocation implements MethodInvocation { Method method; diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/observability/BatchMetricsTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/observability/BatchMetricsTests.java index 40306f34f4..5aee7586ae 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/observability/BatchMetricsTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/observability/BatchMetricsTests.java @@ -27,7 +27,7 @@ import io.micrometer.core.instrument.Meter; import io.micrometer.core.instrument.Metrics; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.Job; @@ -47,20 +47,20 @@ import org.springframework.context.annotation.Import; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Mahmoud Ben Hassine */ -public class BatchMetricsTests { +class BatchMetricsTests { private static final int EXPECTED_SPRING_BATCH_METRICS = 10; @Test - public void testCalculateDuration() { + void testCalculateDuration() { LocalDateTime startTime = LocalDateTime.now(); LocalDateTime endTime = startTime.plus(2, ChronoUnit.HOURS).plus(31, ChronoUnit.MINUTES) .plus(12, ChronoUnit.SECONDS).plus(42, ChronoUnit.MILLIS); @@ -71,13 +71,13 @@ public void testCalculateDuration() { } @Test - public void testCalculateDurationWhenNoStartTime() { + void testCalculateDurationWhenNoStartTime() { Duration duration = BatchMetrics.calculateDuration(null, toDate(LocalDateTime.now())); assertNull(duration); } @Test - public void testCalculateDurationWhenNoEndTime() { + void testCalculateDurationWhenNoEndTime() { Duration duration = BatchMetrics.calculateDuration(toDate(LocalDateTime.now()), null); assertNull(duration); } @@ -87,54 +87,54 @@ private Date toDate(LocalDateTime localDateTime) { } @Test - public void testFormatValidDuration() { + void testFormatValidDuration() { Duration duration = Duration.ofMillis(42).plusSeconds(12).plusMinutes(31).plusHours(2); String formattedDuration = BatchMetrics.formatDuration(duration); assertEquals("2h31m12s42ms", formattedDuration); } @Test - public void testFormatValidDurationWithoutHours() { + void testFormatValidDurationWithoutHours() { Duration duration = Duration.ofMillis(42).plusSeconds(12).plusMinutes(31); String formattedDuration = BatchMetrics.formatDuration(duration); assertEquals("31m12s42ms", formattedDuration); } @Test - public void testFormatValidDurationWithoutMinutes() { + void testFormatValidDurationWithoutMinutes() { Duration duration = Duration.ofMillis(42).plusSeconds(12); String formattedDuration = BatchMetrics.formatDuration(duration); assertEquals("12s42ms", formattedDuration); } @Test - public void testFormatValidDurationWithoutSeconds() { + void testFormatValidDurationWithoutSeconds() { Duration duration = Duration.ofMillis(42); String formattedDuration = BatchMetrics.formatDuration(duration); assertEquals("42ms", formattedDuration); } @Test - public void testFormatNegativeDuration() { + void testFormatNegativeDuration() { Duration duration = Duration.ofMillis(-1); String formattedDuration = BatchMetrics.formatDuration(duration); assertTrue(formattedDuration.isEmpty()); } @Test - public void testFormatZeroDuration() { + void testFormatZeroDuration() { String formattedDuration = BatchMetrics.formatDuration(Duration.ZERO); assertTrue(formattedDuration.isEmpty()); } @Test - public void testFormatNullDuration() { + void testFormatNullDuration() { String formattedDuration = BatchMetrics.formatDuration(null); assertTrue(formattedDuration.isEmpty()); } @Test - public void testBatchMetrics() throws Exception { + void testBatchMetrics() throws Exception { // given ApplicationContext context = new AnnotationConfigApplicationContext(MyJobConfiguration.class); JobLauncher jobLauncher = context.getBean(JobLauncher.class); @@ -150,116 +150,69 @@ public void testBatchMetrics() throws Exception { // Job metrics - try { - Metrics.globalRegistry.get("spring.batch.job").tag("spring.batch.job.name", "job") - .tag("spring.batch.job.status", "COMPLETED").timer(); - } - catch (Exception e) { - fail("There should be a meter of type TIMER named spring.batch.job " + "registered in the global registry: " - + e.getMessage()); - } + assertDoesNotThrow( + () -> Metrics.globalRegistry.get("spring.batch.job").tag("spring.batch.job.name", "job") + .tag("spring.batch.job.status", "COMPLETED").timer(), + "There should be a meter of type TIMER named spring.batch.job registered in the global registry"); - try { - Metrics.globalRegistry.get("spring.batch.job.active").tag("spring.batch.job.active.name", "job") - .longTaskTimer(); - } - catch (Exception e) { - fail("There should be a meter of type LONG_TASK_TIMER named spring.batch.job.active" - + " registered in the global registry: " + e.getMessage()); - } + assertDoesNotThrow( + () -> Metrics.globalRegistry.get("spring.batch.job.active").tag("spring.batch.job.active.name", "job") + .longTaskTimer(), + "There should be a meter of type LONG_TASK_TIMER named spring.batch.job.active" + + " registered in the global registry"); // Step 1 (tasklet) metrics - try { - Metrics.globalRegistry.get("spring.batch.step").tag("spring.batch.step.name", "step1") - .tag("spring.batch.step.job.name", "job").tag("spring.batch.step.status", "COMPLETED").timer(); - } - catch (Exception e) { - fail("There should be a meter of type TIMER named spring.batch.step" - + " registered in the global registry: " + e.getMessage()); - } + assertDoesNotThrow( + () -> Metrics.globalRegistry.get("spring.batch.step").tag("spring.batch.step.name", "step1") + .tag("spring.batch.step.job.name", "job").tag("spring.batch.step.status", "COMPLETED").timer(), + "There should be a meter of type TIMER named spring.batch.step registered in the global registry"); // Step 2 (simple chunk-oriented) metrics - try { - Metrics.globalRegistry.get("spring.batch.step").tag("spring.batch.step.name", "step2") - .tag("spring.batch.step.job.name", "job").tag("spring.batch.step.status", "COMPLETED").timer(); - } - catch (Exception e) { - fail("There should be a meter of type TIMER named spring.batch.step" - + " registered in the global registry: " + e.getMessage()); - } + assertDoesNotThrow( + () -> Metrics.globalRegistry.get("spring.batch.step").tag("spring.batch.step.name", "step2") + .tag("spring.batch.step.job.name", "job").tag("spring.batch.step.status", "COMPLETED").timer(), + "There should be a meter of type TIMER named spring.batch.step registered in the global registry"); - try { - Metrics.globalRegistry.get("spring.batch.item.read").tag("spring.batch.item.read.job.name", "job") - .tag("spring.batch.item.read.step.name", "step2").tag("spring.batch.item.read.status", "SUCCESS") - .timer(); - } - catch (Exception e) { - fail("There should be a meter of type TIMER named spring.batch.item.read" - + " registered in the global registry: " + e.getMessage()); - } + assertDoesNotThrow( + () -> Metrics.globalRegistry.get("spring.batch.item.read").tag("spring.batch.item.read.job.name", "job") + .tag("spring.batch.item.read.step.name", "step2") + .tag("spring.batch.item.read.status", "SUCCESS").timer(), + "There should be a meter of type TIMER named spring.batch.item.read registered in the global registry"); - try { - Metrics.globalRegistry.get("spring.batch.item.process").tag("spring.batch.item.process.job.name", "job") - .tag("spring.batch.item.process.step.name", "step2") - .tag("spring.batch.item.process.status", "SUCCESS").timer(); - } - catch (Exception e) { - fail("There should be a meter of type TIMER named spring.batch.item.process" - + " registered in the global registry: " + e.getMessage()); - } + assertDoesNotThrow(() -> Metrics.globalRegistry.get("spring.batch.item.process") + .tag("spring.batch.item.process.job.name", "job").tag("spring.batch.item.process.step.name", "step2") + .tag("spring.batch.item.process.status", "SUCCESS").timer(), + "There should be a meter of type TIMER named spring.batch.item.process registered in the global registry"); - try { - Metrics.globalRegistry.get("spring.batch.chunk.write").tag("spring.batch.chunk.write.job.name", "job") - .tag("spring.batch.chunk.write.step.name", "step2") - .tag("spring.batch.chunk.write.status", "SUCCESS").timer(); - } - catch (Exception e) { - fail("There should be a meter of type TIMER named spring.batch.chunk.write" - + " registered in the global registry: " + e.getMessage()); - } + assertDoesNotThrow(() -> Metrics.globalRegistry.get("spring.batch.chunk.write") + .tag("spring.batch.chunk.write.job.name", "job").tag("spring.batch.chunk.write.step.name", "step2") + .tag("spring.batch.chunk.write.status", "SUCCESS").timer(), + "There should be a meter of type TIMER named spring.batch.chunk.write registered in the global registry"); // Step 3 (fault-tolerant chunk-oriented) metrics - try { - Metrics.globalRegistry.get("spring.batch.step").tag("spring.batch.step.name", "step3") - .tag("spring.batch.step.job.name", "job").tag("spring.batch.step.status", "COMPLETED").timer(); - } - catch (Exception e) { - fail("There should be a meter of type TIMER named spring.batch.step" - + " registered in the global registry: " + e.getMessage()); - } - - try { - Metrics.globalRegistry.get("spring.batch.item.read").tag("spring.batch.item.read.job.name", "job") - .tag("spring.batch.item.read.step.name", "step3").tag("spring.batch.item.read.status", "SUCCESS") - .timer(); - } - catch (Exception e) { - fail("There should be a meter of type TIMER named spring.batch.item.read" - + " registered in the global registry: " + e.getMessage()); - } - - try { - Metrics.globalRegistry.get("spring.batch.item.process").tag("spring.batch.item.process.job.name", "job") - .tag("spring.batch.item.process.step.name", "step3") - .tag("spring.batch.item.process.status", "SUCCESS").timer(); - } - catch (Exception e) { - fail("There should be a meter of type TIMER named spring.batch.item.process" - + " registered in the global registry: " + e.getMessage()); - } - - try { - Metrics.globalRegistry.get("spring.batch.chunk.write").tag("spring.batch.chunk.write.job.name", "job") - .tag("spring.batch.chunk.write.step.name", "step3") - .tag("spring.batch.chunk.write.status", "SUCCESS").timer(); - } - catch (Exception e) { - fail("There should be a meter of type TIMER named spring.batch.chunk.write" - + " registered in the global registry: " + e.getMessage()); - } + assertDoesNotThrow( + () -> Metrics.globalRegistry.get("spring.batch.step").tag("spring.batch.step.name", "step3") + .tag("spring.batch.step.job.name", "job").tag("spring.batch.step.status", "COMPLETED").timer(), + "There should be a meter of type TIMER named spring.batch.step registered in the global registry"); + + assertDoesNotThrow( + () -> Metrics.globalRegistry.get("spring.batch.item.read").tag("spring.batch.item.read.job.name", "job") + .tag("spring.batch.item.read.step.name", "step3") + .tag("spring.batch.item.read.status", "SUCCESS").timer(), + "There should be a meter of type TIMER named spring.batch.item.read registered in the global registry"); + + assertDoesNotThrow(() -> Metrics.globalRegistry.get("spring.batch.item.process") + .tag("spring.batch.item.process.job.name", "job").tag("spring.batch.item.process.step.name", "step3") + .tag("spring.batch.item.process.status", "SUCCESS").timer(), + "There should be a meter of type TIMER named spring.batch.item.process registered in the global registry"); + + assertDoesNotThrow(() -> Metrics.globalRegistry.get("spring.batch.chunk.write") + .tag("spring.batch.chunk.write.job.name", "job").tag("spring.batch.chunk.write.step.name", "step3") + .tag("spring.batch.chunk.write.status", "SUCCESS").timer(), + "There should be a meter of type TIMER named spring.batch.chunk.write registered in the global registry"); } @Configuration diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/ExampleItemReaderTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/ExampleItemReaderTests.java index afc2495e7d..f83f17b85a 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/ExampleItemReaderTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/ExampleItemReaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008 the original author or authors. + * Copyright 2008-2022 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. @@ -15,25 +15,25 @@ */ package org.springframework.batch.core.partition; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; -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.batch.item.ExecutionContext; -public class ExampleItemReaderTests { +class ExampleItemReaderTests { - private ExampleItemReader reader = new ExampleItemReader(); + private final ExampleItemReader reader = new ExampleItemReader(); - @Before - @After - public void ensureFailFlagUnset() { + @BeforeEach + @AfterEach + void ensureFailFlagUnset() { ExampleItemReader.fail = false; } @Test - public void testRead() throws Exception { + void testRead() throws Exception { int count = 0; while (reader.read() != null) { count++; @@ -42,7 +42,7 @@ public void testRead() throws Exception { } @Test - public void testOpen() throws Exception { + void testOpen() throws Exception { ExecutionContext context = new ExecutionContext(); for (int i = 0; i < 4; i++) { reader.read(); @@ -57,22 +57,15 @@ public void testOpen() throws Exception { } @Test - public void testFailAndRestart() throws Exception { + void testFailAndRestart() throws Exception { ExecutionContext context = new ExecutionContext(); ExampleItemReader.fail = true; for (int i = 0; i < 4; i++) { reader.read(); reader.update(context); } - try { - reader.read(); - reader.update(context); - fail("Expected Exception"); - } - catch (Exception e) { - // expected - assertEquals("Planned failure", e.getMessage()); - } + Exception exception = assertThrows(Exception.class, reader::read); + assertEquals("Planned failure", exception.getMessage()); assertFalse(ExampleItemReader.fail); reader.open(context); int count = 0; diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/RestartIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/RestartIntegrationTests.java index 95cbee1877..1ef92483da 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/RestartIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/RestartIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,15 +15,14 @@ */ package org.springframework.batch.core.partition; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import javax.sql.DataSource; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -32,8 +31,7 @@ import org.springframework.batch.core.launch.JobLauncher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.jdbc.JdbcTestUtils; /** @@ -41,8 +39,7 @@ * @author Mahmoud Ben Hassine * */ -@ContextConfiguration(locations = "launch-context.xml") -@RunWith(SpringJUnit4ClassRunner.class) +@SpringJUnitConfig(locations = "launch-context.xml") public class RestartIntegrationTests { @Autowired @@ -59,18 +56,18 @@ public void setDataSource(DataSource dataSource) { } @Test - public void testSimpleProperties() throws Exception { + void testSimpleProperties() { assertNotNull(jobLauncher); } - @Before - @After - public void start() { + @BeforeEach + @AfterEach + void start() { ExampleItemReader.fail = false; } @Test - public void testLaunchJob() throws Exception { + void testLaunchJob() throws Exception { // Force failure in one of the parallel steps ExampleItemReader.fail = true; diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/VanillaIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/VanillaIntegrationTests.java index 12cd966a94..735436b439 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/VanillaIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/VanillaIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,20 +15,18 @@ */ package org.springframework.batch.core.partition; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import javax.sql.DataSource; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.jdbc.JdbcTestUtils; /** @@ -36,8 +34,7 @@ * @author Mahmoud Ben Hassine * */ -@ContextConfiguration(locations = "launch-context.xml") -@RunWith(SpringJUnit4ClassRunner.class) +@SpringJUnitConfig(locations = "launch-context.xml") public class VanillaIntegrationTests { @Autowired @@ -54,12 +51,12 @@ public void setDataSource(DataSource dataSource) { } @Test - public void testSimpleProperties() throws Exception { + void testSimpleProperties() { assertNotNull(jobLauncher); } @Test - public void testLaunchJob() throws Exception { + void testLaunchJob() throws Exception { int beforeManager = JdbcTestUtils.countRowsInTableWhere(jdbcTemplate, "BATCH_STEP_EXECUTION", "STEP_NAME='step1:manager'"); int beforePartition = JdbcTestUtils.countRowsInTableWhere(jdbcTemplate, "BATCH_STEP_EXECUTION", diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/DefaultStepExecutionAggregatorTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/DefaultStepExecutionAggregatorTests.java index d37be340c0..83b422f17e 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/DefaultStepExecutionAggregatorTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/DefaultStepExecutionAggregatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2010 the original author or authors. + * Copyright 2009-2022 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. @@ -15,7 +15,7 @@ */ package org.springframework.batch.core.partition.support; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; @@ -24,33 +24,33 @@ import java.util.Arrays; import java.util.Collections; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -public class DefaultStepExecutionAggregatorTests { +class DefaultStepExecutionAggregatorTests { - private StepExecutionAggregator aggregator = new DefaultStepExecutionAggregator(); + private final StepExecutionAggregator aggregator = new DefaultStepExecutionAggregator(); - private JobExecution jobExecution = new JobExecution(11L); + private final JobExecution jobExecution = new JobExecution(11L); - private StepExecution result = jobExecution.createStepExecution("aggregate"); + private final StepExecution result = jobExecution.createStepExecution("aggregate"); - private StepExecution stepExecution1 = jobExecution.createStepExecution("foo:1"); + private final StepExecution stepExecution1 = jobExecution.createStepExecution("foo:1"); - private StepExecution stepExecution2 = jobExecution.createStepExecution("foo:2"); + private final StepExecution stepExecution2 = jobExecution.createStepExecution("foo:2"); @Test - public void testAggregateEmpty() { + void testAggregateEmpty() { aggregator.aggregate(result, Collections.emptySet()); } @Test - public void testAggregateNull() { + void testAggregateNull() { aggregator.aggregate(result, null); } @Test - public void testAggregateStatusSunnyDay() { + void testAggregateStatusSunnyDay() { stepExecution1.setStatus(BatchStatus.COMPLETED); stepExecution2.setStatus(BatchStatus.COMPLETED); aggregator.aggregate(result, Arrays.asList(stepExecution1, stepExecution2)); @@ -59,7 +59,7 @@ public void testAggregateStatusSunnyDay() { } @Test - public void testAggregateStatusFromFailure() { + void testAggregateStatusFromFailure() { result.setStatus(BatchStatus.FAILED); stepExecution1.setStatus(BatchStatus.COMPLETED); stepExecution2.setStatus(BatchStatus.COMPLETED); @@ -69,7 +69,7 @@ public void testAggregateStatusFromFailure() { } @Test - public void testAggregateStatusIncomplete() { + void testAggregateStatusIncomplete() { stepExecution1.setStatus(BatchStatus.COMPLETED); stepExecution2.setStatus(BatchStatus.FAILED); aggregator.aggregate(result, Arrays.asList(stepExecution1, stepExecution2)); @@ -78,7 +78,7 @@ public void testAggregateStatusIncomplete() { } @Test - public void testAggregateExitStatusSunnyDay() { + void testAggregateExitStatusSunnyDay() { stepExecution1.setExitStatus(ExitStatus.EXECUTING); stepExecution2.setExitStatus(ExitStatus.FAILED); aggregator.aggregate(result, Arrays.asList(stepExecution1, stepExecution2)); @@ -87,7 +87,7 @@ public void testAggregateExitStatusSunnyDay() { } @Test - public void testAggregateCountsSunnyDay() { + void testAggregateCountsSunnyDay() { stepExecution1.setCommitCount(1); stepExecution1.setFilterCount(2); stepExecution1.setProcessSkipCount(3); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/MultiResourcePartitionerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/MultiResourcePartitionerTests.java index abc939fc1c..58048b94af 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/MultiResourcePartitionerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/MultiResourcePartitionerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2021 the original author or authors. + * Copyright 2009-2022 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. @@ -17,8 +17,8 @@ import java.util.Map; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.item.ExecutionContext; import org.springframework.core.io.FileSystemResource; @@ -26,42 +26,43 @@ import org.springframework.core.io.UrlResource; import org.springframework.core.io.support.ResourceArrayPropertyEditor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class MultiResourcePartitionerTests { +class MultiResourcePartitionerTests { - private MultiResourcePartitioner partitioner = new MultiResourcePartitioner(); + private final MultiResourcePartitioner partitioner = new MultiResourcePartitioner(); - @Before - public void setUp() { + @BeforeEach + void setUp() { ResourceArrayPropertyEditor editor = new ResourceArrayPropertyEditor(); editor.setAsText("classpath:simple-job-launcher-context.xml"); partitioner.setResources((Resource[]) editor.getValue()); } - @Test(expected = IllegalStateException.class) - public void testMissingResource() { + @Test + void testMissingResource() { partitioner.setResources(new Resource[] { new FileSystemResource("does-not-exist") }); - partitioner.partition(0); + assertThrows(IllegalStateException.class, () -> partitioner.partition(0)); } @Test - public void testPartitionSizeAndKey() { + void testPartitionSizeAndKey() { Map partition = partitioner.partition(0); assertEquals(1, partition.size()); assertTrue(partition.containsKey("partition0")); } @Test - public void testReadFile() throws Exception { + void testReadFile() throws Exception { Map partition = partitioner.partition(0); String url = partition.get("partition0").getString("fileName"); assertTrue(new UrlResource(url).exists()); } @Test - public void testSetKeyName() { + void testSetKeyName() { partitioner.setKeyName("foo"); Map partition = partitioner.partition(0); assertTrue(partition.get("partition0").containsKey("foo")); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/PartitionStepTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/PartitionStepTests.java index 833a16c958..ecbcd721b4 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/PartitionStepTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/PartitionStepTests.java @@ -21,8 +21,8 @@ import java.util.Set; 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.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; @@ -37,21 +37,21 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Dave Syer * @author Mahmoud Ben Hassine * */ -public class PartitionStepTests { +class PartitionStepTests { private PartitionStep step = new PartitionStep(); private JobRepository jobRepository; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { EmbeddedDatabase embeddedDatabase = new EmbeddedDatabaseBuilder() .addScript("/org/springframework/batch/core/schema-drop-hsqldb.sql") .addScript("/org/springframework/batch/core/schema-hsqldb.sql").build(); @@ -65,7 +65,7 @@ public void setUp() throws Exception { } @Test - public void testVanillaStepExecution() throws Exception { + void testVanillaStepExecution() throws Exception { step.setStepExecutionSplitter( new SimpleStepExecutionSplitter(jobRepository, true, step.getName(), new SimplePartitioner())); step.setPartitionHandler(new PartitionHandler() { @@ -91,7 +91,7 @@ public Collection handle(StepExecutionSplitter stepSplitter, Step } @Test - public void testFailedStepExecution() throws Exception { + void testFailedStepExecution() throws Exception { step.setStepExecutionSplitter( new SimpleStepExecutionSplitter(jobRepository, true, step.getName(), new SimplePartitioner())); step.setPartitionHandler(new PartitionHandler() { @@ -117,7 +117,7 @@ public Collection handle(StepExecutionSplitter stepSplitter, Step } @Test - public void testRestartStepExecution() throws Exception { + void testRestartStepExecution() throws Exception { final AtomicBoolean started = new AtomicBoolean(false); step.setStepExecutionSplitter( new SimpleStepExecutionSplitter(jobRepository, true, step.getName(), new SimplePartitioner())); @@ -166,7 +166,7 @@ public Collection handle(StepExecutionSplitter stepSplitter, Step } @Test - public void testStoppedStepExecution() throws Exception { + void testStoppedStepExecution() throws Exception { step.setStepExecutionSplitter( new SimpleStepExecutionSplitter(jobRepository, true, step.getName(), new SimplePartitioner())); step.setPartitionHandler(new PartitionHandler() { @@ -192,7 +192,7 @@ public Collection handle(StepExecutionSplitter stepSplitter, Step } @Test - public void testStepAggregator() throws Exception { + void testStepAggregator() throws Exception { step.setStepExecutionAggregator(new DefaultStepExecutionAggregator() { @Override public void aggregate(StepExecution result, Collection executions) { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/RemoteStepExecutionAggregatorTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/RemoteStepExecutionAggregatorTests.java index 395b155cdb..ed7e888d3d 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/RemoteStepExecutionAggregatorTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/RemoteStepExecutionAggregatorTests.java @@ -15,8 +15,8 @@ */ package org.springframework.batch.core.partition.support; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; @@ -30,13 +30,15 @@ import java.util.Arrays; import java.util.Collections; +import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; -public class RemoteStepExecutionAggregatorTests { +class RemoteStepExecutionAggregatorTests { - private RemoteStepExecutionAggregator aggregator = new RemoteStepExecutionAggregator(); + private final RemoteStepExecutionAggregator aggregator = new RemoteStepExecutionAggregator(); private JobExecution jobExecution; @@ -46,8 +48,8 @@ public class RemoteStepExecutionAggregatorTests { private StepExecution stepExecution2; - @Before - public void init() throws Exception { + @BeforeEach + void init() throws Exception { EmbeddedDatabase embeddedDatabase = new EmbeddedDatabaseBuilder() .addScript("/org/springframework/batch/core/schema-drop-hsqldb.sql") .addScript("/org/springframework/batch/core/schema-hsqldb.sql").build(); @@ -69,17 +71,17 @@ public void init() throws Exception { } @Test - public void testAggregateEmpty() { + void testAggregateEmpty() { aggregator.aggregate(result, Collections.emptySet()); } @Test - public void testAggregateNull() { + void testAggregateNull() { aggregator.aggregate(result, null); } @Test - public void testAggregateStatusSunnyDay() { + void testAggregateStatusSunnyDay() { stepExecution1.setStatus(BatchStatus.COMPLETED); stepExecution2.setStatus(BatchStatus.COMPLETED); aggregator.aggregate(result, Arrays.asList(stepExecution1, stepExecution2)); @@ -87,14 +89,13 @@ public void testAggregateStatusSunnyDay() { assertEquals(BatchStatus.STARTING, result.getStatus()); } - @Test(expected = IllegalStateException.class) - public void testAggregateStatusMissingExecution() { + @Test + void testAggregateStatusMissingExecution() { stepExecution2 = jobExecution.createStepExecution("foo:3"); stepExecution1.setStatus(BatchStatus.COMPLETED); stepExecution2.setStatus(BatchStatus.COMPLETED); - aggregator.aggregate(result, Arrays.asList(stepExecution1, stepExecution2)); - assertNotNull(result); - assertEquals(BatchStatus.STARTING, result.getStatus()); + assertThrows(IllegalStateException.class, + () -> aggregator.aggregate(result, List.of(stepExecution1, stepExecution2))); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/SimplePartitionerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/SimplePartitionerTests.java index 74c4389a64..3617185e29 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/SimplePartitionerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/SimplePartitionerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2021 the original author or authors. + * Copyright 2021-2022 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. @@ -17,18 +17,20 @@ import java.util.Map; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.item.ExecutionContext; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + /** * @author Mahmoud Ben Hassine */ -public class SimplePartitionerTests { +class SimplePartitionerTests { @Test - public void testPartition() { + void testPartition() { // given SimplePartitioner partitioner = new SimplePartitioner(); @@ -36,11 +38,11 @@ public void testPartition() { Map partitions = partitioner.partition(3); // then - Assert.assertNotNull(partitions); - Assert.assertEquals(3, partitions.size()); - Assert.assertNotNull(partitions.get("partition0")); - Assert.assertNotNull(partitions.get("partition1")); - Assert.assertNotNull(partitions.get("partition2")); + assertNotNull(partitions); + assertEquals(3, partitions.size()); + assertNotNull(partitions.get("partition0")); + assertNotNull(partitions.get("partition1")); + assertNotNull(partitions.get("partition2")); } } \ No newline at end of file diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/SimpleStepExecutionSplitterTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/SimpleStepExecutionSplitterTests.java index bcfc10ccd5..0c67dc9141 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/SimpleStepExecutionSplitterTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/SimpleStepExecutionSplitterTests.java @@ -22,8 +22,8 @@ import java.util.Map; 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.springframework.batch.core.BatchStatus; import org.springframework.batch.core.JobExecution; @@ -40,11 +40,11 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class SimpleStepExecutionSplitterTests { +class SimpleStepExecutionSplitterTests { private Step step; @@ -52,8 +52,8 @@ public class SimpleStepExecutionSplitterTests { private StepExecution stepExecution; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { step = new TaskletStep("step"); EmbeddedDatabase embeddedDatabase = new EmbeddedDatabaseBuilder() .addScript("/org/springframework/batch/core/schema-drop-hsqldb.sql") @@ -68,14 +68,14 @@ public void setUp() throws Exception { } @Test - public void testSimpleStepExecutionProviderJobRepositoryStep() throws Exception { + void testSimpleStepExecutionProviderJobRepositoryStep() throws Exception { SimpleStepExecutionSplitter splitter = new SimpleStepExecutionSplitter(jobRepository, true, step.getName(), new SimplePartitioner()); Set execs = splitter.split(stepExecution, 2); assertEquals(2, execs.size()); for (StepExecution execution : execs) { - assertNotNull("step execution partition is saved", execution.getId()); + assertNotNull(execution.getId(), "step execution partition is saved"); } } @@ -84,7 +84,7 @@ public void testSimpleStepExecutionProviderJobRepositoryStep() throws Exception * @throws Exception */ @Test - public void testAddressabilityOfSetResults() throws Exception { + void testAddressabilityOfSetResults() throws Exception { SimpleStepExecutionSplitter splitter = new SimpleStepExecutionSplitter(jobRepository, true, step.getName(), new SimplePartitioner()); Set execs = splitter.split(stepExecution, 2); @@ -96,7 +96,7 @@ public void testAddressabilityOfSetResults() throws Exception { } @Test - public void testSimpleStepExecutionProviderJobRepositoryStepPartitioner() throws Exception { + void testSimpleStepExecutionProviderJobRepositoryStepPartitioner() throws Exception { final Map map = Collections.singletonMap("foo", new ExecutionContext()); SimpleStepExecutionSplitter splitter = new SimpleStepExecutionSplitter(jobRepository, true, step.getName(), new Partitioner() { @@ -109,7 +109,7 @@ public Map partition(int gridSize) { } @Test - public void testRememberGridSize() throws Exception { + void testRememberGridSize() throws Exception { SimpleStepExecutionSplitter provider = new SimpleStepExecutionSplitter(jobRepository, true, step.getName(), new SimplePartitioner()); Set split = provider.split(stepExecution, 2); @@ -119,7 +119,7 @@ public void testRememberGridSize() throws Exception { } @Test - public void testRememberPartitionNames() throws Exception { + void testRememberPartitionNames() throws Exception { class CustomPartitioner implements Partitioner, PartitionNameProvider { @Override @@ -144,14 +144,14 @@ public Collection getPartitionNames(int gridSize) { } @Test - public void testGetStepName() { + void testGetStepName() { SimpleStepExecutionSplitter provider = new SimpleStepExecutionSplitter(jobRepository, true, step.getName(), new SimplePartitioner()); assertEquals("step", provider.getStepName()); } @Test - public void testUnknownStatus() throws Exception { + void testUnknownStatus() throws Exception { SimpleStepExecutionSplitter provider = new SimpleStepExecutionSplitter(jobRepository, true, step.getName(), new SimplePartitioner()); Set split = provider.split(stepExecution, 2); @@ -162,12 +162,12 @@ public void testUnknownStatus() throws Exception { } catch (JobExecutionException e) { String message = e.getMessage(); - assertTrue("Wrong message: " + message, message.contains("UNKNOWN")); + assertTrue(message.contains("UNKNOWN"), "Wrong message: " + message); } } @Test - public void testCompleteStatusAfterFailure() throws Exception { + void testCompleteStatusAfterFailure() throws Exception { SimpleStepExecutionSplitter provider = new SimpleStepExecutionSplitter(jobRepository, false, step.getName(), new SimplePartitioner()); Set split = provider.split(stepExecution, 2); @@ -178,7 +178,7 @@ public void testCompleteStatusAfterFailure() throws Exception { } @Test - public void testCompleteStatusSameJobExecution() throws Exception { + void testCompleteStatusSameJobExecution() throws Exception { SimpleStepExecutionSplitter provider = new SimpleStepExecutionSplitter(jobRepository, false, step.getName(), new SimplePartitioner()); Set split = provider.split(stepExecution, 2); @@ -189,7 +189,7 @@ public void testCompleteStatusSameJobExecution() throws Exception { } @Test - public void testIncompleteStatus() throws Exception { + void testIncompleteStatus() throws Exception { SimpleStepExecutionSplitter provider = new SimpleStepExecutionSplitter(jobRepository, true, step.getName(), new SimplePartitioner()); Set split = provider.split(stepExecution, 2); @@ -201,12 +201,12 @@ public void testIncompleteStatus() throws Exception { } catch (JobExecutionException e) { String message = e.getMessage(); - assertTrue("Wrong message: " + message, message.contains("STARTED")); + assertTrue(message.contains("STARTED"), "Wrong message: " + message); } } @Test - public void testAbandonedStatus() throws Exception { + void testAbandonedStatus() throws Exception { SimpleStepExecutionSplitter provider = new SimpleStepExecutionSplitter(jobRepository, true, step.getName(), new SimplePartitioner()); Set split = provider.split(stepExecution, 2); @@ -218,7 +218,7 @@ public void testAbandonedStatus() throws Exception { } catch (JobExecutionException e) { String message = e.getMessage(); - assertTrue("Wrong message: " + message, message.contains("ABANDONED")); + assertTrue(message.contains("ABANDONED"), "Wrong message: " + message); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/TaskExecutorPartitionHandlerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/TaskExecutorPartitionHandlerTests.java index eb94fba2ef..8f2fb0ae26 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/TaskExecutorPartitionHandlerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/TaskExecutorPartitionHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2012 the original author or authors. + * Copyright 2008-2022 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. @@ -15,17 +15,17 @@ */ package org.springframework.batch.core.partition.support; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.TreeSet; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobExecutionException; @@ -37,17 +37,17 @@ import org.springframework.core.task.TaskExecutor; import org.springframework.core.task.TaskRejectedException; -public class TaskExecutorPartitionHandlerTests { +class TaskExecutorPartitionHandlerTests { private TaskExecutorPartitionHandler handler = new TaskExecutorPartitionHandler(); private int count = 0; - private Collection stepExecutions = new TreeSet<>(); + private final Collection stepExecutions = new TreeSet<>(); - private StepExecution stepExecution = new StepExecution("step", new JobExecution(1L)); + private final StepExecution stepExecution = new StepExecution("step", new JobExecution(1L)); - private StepExecutionSplitter stepExecutionSplitter = new StepExecutionSplitter() { + private final StepExecutionSplitter stepExecutionSplitter = new StepExecutionSplitter() { @Override public String getStepName() { @@ -64,8 +64,8 @@ public Set split(StepExecution stepExecution, int gridSize) throw } }; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { handler.setStep(new StepSupport() { @Override public void execute(StepExecution stepExecution) throws JobInterruptedException { @@ -77,35 +77,24 @@ public void execute(StepExecution stepExecution) throws JobInterruptedException } @Test - public void testConfiguration() throws Exception { + void testConfiguration() { handler = new TaskExecutorPartitionHandler(); - try { - handler.afterPropertiesSet(); - fail("Expected IllegalStateException when no step is set"); - } - catch (IllegalStateException e) { - // expected - String message = e.getMessage(); - assertEquals("Wrong message: " + message, "A Step must be provided.", message); - } + Exception exception = assertThrows(IllegalStateException.class, handler::afterPropertiesSet); + String message = exception.getMessage(); + assertEquals("A Step must be provided.", message, "Wrong message: " + message); } @Test - public void testNullStep() throws Exception { + void testNullStep() { handler = new TaskExecutorPartitionHandler(); - try { - handler.handle(stepExecutionSplitter, stepExecution); - fail("Expected IllegalArgumentException"); - } - catch (IllegalArgumentException e) { - // expected - String message = e.getMessage(); - assertTrue("Wrong message: " + message, message.contains("Step")); - } + Exception exception = assertThrows(IllegalArgumentException.class, + () -> handler.handle(stepExecutionSplitter, stepExecution)); + String message = exception.getMessage(); + assertTrue(message.contains("Step"), "Wrong message: " + message); } @Test - public void testSetGridSize() throws Exception { + void testSetGridSize() throws Exception { handler.setGridSize(2); handler.handle(stepExecutionSplitter, stepExecution); assertEquals(2, count); @@ -113,14 +102,14 @@ public void testSetGridSize() throws Exception { } @Test - public void testSetTaskExecutor() throws Exception { + void testSetTaskExecutor() throws Exception { handler.setTaskExecutor(new SimpleAsyncTaskExecutor()); handler.handle(stepExecutionSplitter, stepExecution); assertEquals(1, count); } @Test - public void testTaskExecutorFailure() throws Exception { + void testTaskExecutorFailure() throws Exception { handler.setGridSize(2); handler.setTaskExecutor(new TaskExecutor() { @Override diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractExecutionContextDaoTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractExecutionContextDaoTests.java index 3e71996ecd..0093728278 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractExecutionContextDaoTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractExecutionContextDaoTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2021 the original author or authors. + * Copyright 2008-2022 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. @@ -15,15 +15,16 @@ */ package org.springframework.batch.core.repository.dao; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayList; import java.util.Collections; import java.util.Date; 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.springframework.batch.core.BatchStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInstance; @@ -50,8 +51,8 @@ public abstract class AbstractExecutionContextDaoTests extends AbstractTransacti private StepExecution stepExecution; - @Before - public void setUp() { + @BeforeEach + void setUp() { jobInstanceDao = getJobInstanceDao(); jobExecutionDao = getJobExecutionDao(); stepExecutionDao = getStepExecutionDao(); @@ -87,7 +88,7 @@ public void setUp() { @Transactional @Test - public void testSaveAndFindJobContext() { + void testSaveAndFindJobContext() { ExecutionContext ctx = new ExecutionContext(Collections.singletonMap("key", "value")); jobExecution.setExecutionContext(ctx); @@ -99,7 +100,7 @@ public void testSaveAndFindJobContext() { @Transactional @Test - public void testSaveAndFindExecutionContexts() { + void testSaveAndFindExecutionContexts() { List stepExecutions = new ArrayList<>(); for (int i = 0; i < 3; i++) { @@ -129,20 +130,20 @@ public void testSaveAndFindExecutionContexts() { } @Transactional - @Test(expected = IllegalArgumentException.class) - public void testSaveNullExecutionContexts() { - contextDao.saveExecutionContexts(null); + @Test + void testSaveNullExecutionContexts() { + assertThrows(IllegalArgumentException.class, () -> contextDao.saveExecutionContexts(null)); } @Transactional @Test - public void testSaveEmptyExecutionContexts() { + void testSaveEmptyExecutionContexts() { contextDao.saveExecutionContexts(new ArrayList<>()); } @Transactional @Test - public void testSaveAndFindEmptyJobContext() { + void testSaveAndFindEmptyJobContext() { ExecutionContext ctx = new ExecutionContext(); jobExecution.setExecutionContext(ctx); @@ -154,7 +155,7 @@ public void testSaveAndFindEmptyJobContext() { @Transactional @Test - public void testUpdateContext() { + void testUpdateContext() { ExecutionContext ctx = new ExecutionContext(Collections.singletonMap("key", "value")); jobExecution.setExecutionContext(ctx); @@ -170,7 +171,7 @@ public void testUpdateContext() { @Transactional @Test - public void testSaveAndFindStepContext() { + void testSaveAndFindStepContext() { ExecutionContext ctx = new ExecutionContext(Collections.singletonMap("key", "value")); stepExecution.setExecutionContext(ctx); @@ -182,7 +183,7 @@ public void testSaveAndFindStepContext() { @Transactional @Test - public void testSaveAndFindEmptyStepContext() { + void testSaveAndFindEmptyStepContext() { ExecutionContext ctx = new ExecutionContext(); stepExecution.setExecutionContext(ctx); @@ -194,7 +195,7 @@ public void testSaveAndFindEmptyStepContext() { @Transactional @Test - public void testUpdateStepContext() { + void testUpdateStepContext() { ExecutionContext ctx = new ExecutionContext(Collections.singletonMap("key", "value")); stepExecution.setExecutionContext(ctx); @@ -210,7 +211,7 @@ public void testUpdateStepContext() { @Transactional @Test - public void testStoreInteger() { + void testStoreInteger() { ExecutionContext ec = new ExecutionContext(); ec.put("intValue", 343232); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractExecutionContextSerializerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractExecutionContextSerializerTests.java index 9fd16840ff..214046fd46 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractExecutionContextSerializerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractExecutionContextSerializerTests.java @@ -16,7 +16,7 @@ package org.springframework.batch.core.repository.dao; import com.fasterxml.jackson.annotation.JsonTypeInfo; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobParameter; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.repository.ExecutionContextSerializer; @@ -29,6 +29,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasEntry; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * Abstract test class for {@code ExecutionContextSerializer} implementations. Provides a @@ -43,7 +44,7 @@ public abstract class AbstractExecutionContextSerializerTests { @Test - public void testSerializeAMap() throws Exception { + void testSerializeAMap() throws Exception { Map m1 = new HashMap<>(); m1.put("object1", Long.valueOf(12345L)); m1.put("object2", "OBJECT TWO"); @@ -57,7 +58,7 @@ public void testSerializeAMap() throws Exception { } @Test - public void testSerializeStringJobParameter() throws Exception { + void testSerializeStringJobParameter() throws Exception { Map m1 = new HashMap<>(); m1.put("name", new JobParameter("foo")); @@ -67,7 +68,7 @@ public void testSerializeStringJobParameter() throws Exception { } @Test - public void testSerializeDateJobParameter() throws Exception { + void testSerializeDateJobParameter() throws Exception { Map m1 = new HashMap<>(); m1.put("birthDate", new JobParameter(new Date(123456790123L))); @@ -77,7 +78,7 @@ public void testSerializeDateJobParameter() throws Exception { } @Test - public void testSerializeDoubleJobParameter() throws Exception { + void testSerializeDoubleJobParameter() throws Exception { Map m1 = new HashMap<>(); m1.put("weight", new JobParameter(80.5D)); @@ -87,7 +88,7 @@ public void testSerializeDoubleJobParameter() throws Exception { } @Test - public void testSerializeLongJobParameter() throws Exception { + void testSerializeLongJobParameter() throws Exception { Map m1 = new HashMap<>(); m1.put("age", new JobParameter(20L)); @@ -97,7 +98,7 @@ public void testSerializeLongJobParameter() throws Exception { } @Test - public void testSerializeNonIdentifyingJobParameter() throws Exception { + void testSerializeNonIdentifyingJobParameter() throws Exception { Map m1 = new HashMap<>(); m1.put("name", new JobParameter("foo", false)); @@ -107,7 +108,7 @@ public void testSerializeNonIdentifyingJobParameter() throws Exception { } @Test - public void testSerializeJobParameters() throws Exception { + void testSerializeJobParameters() throws Exception { Map jobParametersMap = new HashMap<>(); jobParametersMap.put("paramName", new JobParameter("paramValue")); @@ -120,7 +121,7 @@ public void testSerializeJobParameters() throws Exception { } @Test - public void testSerializeEmptyJobParameters() throws IOException { + void testSerializeEmptyJobParameters() throws IOException { Map m1 = new HashMap<>(); m1.put("params", new JobParameters()); @@ -130,7 +131,7 @@ public void testSerializeEmptyJobParameters() throws IOException { } @Test - public void testComplexObject() throws Exception { + void testComplexObject() throws Exception { Map m1 = new HashMap<>(); ComplexObject o1 = new ComplexObject(); o1.setName("02345"); @@ -152,7 +153,7 @@ public void testComplexObject() throws Exception { } @Test - public void testSerializeRecords() throws IOException { + void testSerializeRecords() throws IOException { Map m1 = new HashMap<>(); m1.put("foo", new Person(1, "foo")); m1.put("bar", new Person(2, "bar")); @@ -162,9 +163,10 @@ public void testSerializeRecords() throws IOException { compareContexts(m1, m2); } - @Test(expected = IllegalArgumentException.class) - public void testNullSerialization() throws Exception { - getSerializer().serialize(null, null); + @Test + void testNullSerialization() { + ExecutionContextSerializer serializer = getSerializer(); + assertThrows(IllegalArgumentException.class, () -> serializer.serialize(null, null)); } protected void compareContexts(Map m1, Map m2) { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractJobDaoTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractJobDaoTests.java index a18b171f08..3f32268b87 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractJobDaoTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractJobDaoTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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,11 +16,10 @@ package org.springframework.batch.core.repository.dao; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.Date; import java.util.List; @@ -28,8 +27,8 @@ import javax.sql.DataSource; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; @@ -83,8 +82,8 @@ public void setJobExecutionDao(JobExecutionDao jobExecutionDao) { this.jobExecutionDao = jobExecutionDao; } - @Before - public void onSetUpInTransaction() throws Exception { + @BeforeEach + void onSetUpInTransaction() { // Create job. jobInstance = jobInstanceDao.createJobInstance(jobName, jobParameters); @@ -98,7 +97,7 @@ public void onSetUpInTransaction() throws Exception { @Transactional @Test - public void testVersionIsNotNullForJob() throws Exception { + void testVersionIsNotNullForJob() { int version = jdbcTemplate.queryForObject( "select version from BATCH_JOB_INSTANCE where JOB_INSTANCE_ID=" + jobInstance.getId(), Integer.class); assertEquals(0, version); @@ -106,7 +105,7 @@ public void testVersionIsNotNullForJob() throws Exception { @Transactional @Test - public void testVersionIsNotNullForJobExecution() throws Exception { + void testVersionIsNotNullForJobExecution() { int version = jdbcTemplate.queryForObject( "select version from BATCH_JOB_EXECUTION where JOB_EXECUTION_ID=" + jobExecution.getId(), Integer.class); @@ -115,7 +114,7 @@ public void testVersionIsNotNullForJobExecution() throws Exception { @Transactional @Test - public void testFindNonExistentJob() { + void testFindNonExistentJob() { // No job should be found since it hasn't been created. JobInstance jobInstance = jobInstanceDao.getJobInstance("nonexistentJob", jobParameters); assertNull(jobInstance); @@ -123,23 +122,16 @@ public void testFindNonExistentJob() { @Transactional @Test - public void testFindJob() { + void testFindJob() { JobInstance instance = jobInstanceDao.getJobInstance(jobName, jobParameters); assertNotNull(instance); - assertTrue(jobInstance.equals(instance)); + assertEquals(jobInstance, instance); } @Transactional @Test - public void testFindJobWithNullRuntime() { - - try { - jobInstanceDao.getJobInstance(null, null); - fail(); - } - catch (IllegalArgumentException ex) { - // expected - } + void testFindJobWithNullRuntime() { + assertThrows(IllegalArgumentException.class, () -> jobInstanceDao.getJobInstance(null, null)); } /** @@ -149,7 +141,7 @@ public void testFindJobWithNullRuntime() { */ @Transactional @Test - public void testCreateJobWithExistingName() { + void testCreateJobWithExistingName() { String scheduledJob = "ScheduledJob"; jobInstanceDao.createJobInstance(scheduledJob, jobParameters); @@ -169,7 +161,7 @@ public void testCreateJobWithExistingName() { @Transactional @Test - public void testUpdateJobExecution() { + void testUpdateJobExecution() { jobExecution.setStatus(BatchStatus.COMPLETED); jobExecution.setExitStatus(ExitStatus.COMPLETED); @@ -184,7 +176,7 @@ public void testUpdateJobExecution() { @Transactional @Test - public void testSaveJobExecution() { + void testSaveJobExecution() { List executions = jobExecutionDao.findJobExecutions(jobInstance); assertEquals(executions.size(), 1); @@ -193,37 +185,25 @@ public void testSaveJobExecution() { @Transactional @Test - public void testUpdateInvalidJobExecution() { + void testUpdateInvalidJobExecution() { // id is invalid JobExecution execution = new JobExecution(jobInstance, (long) 29432, jobParameters); execution.incrementVersion(); - try { - jobExecutionDao.updateJobExecution(execution); - fail("Expected NoSuchBatchDomainObjectException"); - } - catch (NoSuchObjectException ex) { - // expected - } + assertThrows(NoSuchObjectException.class, () -> jobExecutionDao.updateJobExecution(execution)); } @Transactional @Test - public void testUpdateNullIdJobExecution() { + void testUpdateNullIdJobExecution() { JobExecution execution = new JobExecution(jobInstance, jobParameters); - try { - jobExecutionDao.updateJobExecution(execution); - fail(); - } - catch (IllegalArgumentException ex) { - // expected - } + assertThrows(IllegalArgumentException.class, () -> jobExecutionDao.updateJobExecution(execution)); } @Transactional @Test - public void testJobWithSimpleJobIdentifier() throws Exception { + void testJobWithSimpleJobIdentifier() { String testJob = "test"; // Create job. @@ -238,7 +218,7 @@ public void testJobWithSimpleJobIdentifier() throws Exception { @Transactional @Test - public void testJobWithDefaultJobIdentifier() throws Exception { + void testJobWithDefaultJobIdentifier() { String testDefaultJob = "testDefault"; // Create job. @@ -251,7 +231,7 @@ public void testJobWithDefaultJobIdentifier() throws Exception { @Transactional @Test - public void testFindJobExecutions() { + void testFindJobExecutions() { List results = jobExecutionDao.findJobExecutions(jobInstance); assertEquals(results.size(), 1); @@ -270,7 +250,7 @@ private void validateJobExecution(JobExecution lhs, JobExecution rhs) { @Transactional @Test - public void testGetLastJobExecution() { + void testGetLastJobExecution() { JobExecution lastExecution = new JobExecution(jobInstance, jobParameters); lastExecution.setStatus(BatchStatus.STARTED); @@ -288,24 +268,18 @@ public void testGetLastJobExecution() { */ @Transactional @Test - public void testCreateDuplicateInstance() { + void testCreateDuplicateInstance() { jobParameters = new JobParameters(); jobInstanceDao.createJobInstance(jobName, jobParameters); - try { - jobInstanceDao.createJobInstance(jobName, jobParameters); - fail(); - } - catch (IllegalStateException e) { - // expected - } + assertThrows(IllegalStateException.class, () -> jobInstanceDao.createJobInstance(jobName, jobParameters)); } @Transactional @Test - public void testCreationAddsVersion() { + void testCreationAddsVersion() { jobInstance = jobInstanceDao.createJobInstance("testCreationAddsVersion", new JobParameters()); @@ -314,7 +288,7 @@ public void testCreationAddsVersion() { @Transactional @Test - public void testSaveAddsVersionAndId() { + void testSaveAddsVersionAndId() { JobExecution jobExecution = new JobExecution(jobInstance, jobParameters); @@ -329,7 +303,7 @@ public void testSaveAddsVersionAndId() { @Transactional @Test - public void testUpdateIncrementsVersion() { + void testUpdateIncrementsVersion() { int version = jobExecution.getVersion(); jobExecutionDao.updateJobExecution(jobExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractJobExecutionDaoTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractJobExecutionDaoTests.java index 25aaa346e3..2851fa8b53 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractJobExecutionDaoTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractJobExecutionDaoTests.java @@ -21,8 +21,8 @@ import java.util.List; 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.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; @@ -33,11 +33,11 @@ import org.springframework.dao.OptimisticLockingFailureException; import org.springframework.transaction.annotation.Transactional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Parent Test Class for {@link JdbcJobExecutionDao} and {@link MapJobExecutionDao}. @@ -66,8 +66,8 @@ protected StepExecutionDao getStepExecutionDao() { return null; } - @Before - public void onSetUp() throws Exception { + @BeforeEach + void onSetUp() { dao = getJobExecutionDao(); jobParameters = new JobParameters(); jobInstance = getJobInstanceDao().createJobInstance("execTestJob", jobParameters); @@ -79,7 +79,7 @@ public void onSetUp() throws Exception { */ @Transactional @Test - public void testSaveAndFind() { + void testSaveAndFind() { execution.setStartTime(new Date(System.currentTimeMillis())); execution.setLastUpdated(new Date(System.currentTimeMillis())); @@ -98,7 +98,7 @@ public void testSaveAndFind() { */ @Transactional @Test - public void testFindExecutionsOrdering() { + void testFindExecutionsOrdering() { List execs = new ArrayList<>(); @@ -123,7 +123,7 @@ public void testFindExecutionsOrdering() { */ @Transactional @Test - public void testFindNonExistentExecutions() { + void testFindNonExistentExecutions() { List executions = dao.findJobExecutions(jobInstance); assertEquals(0, executions.size()); } @@ -133,7 +133,7 @@ public void testFindNonExistentExecutions() { */ @Transactional @Test - public void testSaveAddsIdAndVersion() { + void testSaveAddsIdAndVersion() { assertNull(execution.getId()); assertNull(execution.getVersion()); @@ -147,7 +147,7 @@ public void testSaveAddsIdAndVersion() { */ @Transactional @Test - public void testUpdateExecution() { + void testUpdateExecution() { execution.setStatus(BatchStatus.STARTED); dao.saveJobExecution(execution); @@ -166,7 +166,7 @@ public void testUpdateExecution() { */ @Transactional @Test - public void testGetLastExecution() { + void testGetLastExecution() { JobExecution exec1 = new JobExecution(jobInstance, jobParameters); exec1.setCreateTime(new Date(0)); @@ -185,7 +185,7 @@ public void testGetLastExecution() { */ @Transactional @Test - public void testGetMissingLastExecution() { + void testGetMissingLastExecution() { JobExecution value = dao.getLastJobExecution(jobInstance); assertNull(value); } @@ -195,7 +195,7 @@ public void testGetMissingLastExecution() { */ @Transactional @Test - public void testFindRunningExecutions() { + void testFindRunningExecutions() { // Normally completed JobExecution as EndTime is populated JobExecution exec = new JobExecution(jobInstance, jobParameters); exec.setCreateTime(new Date(0)); @@ -240,7 +240,7 @@ public void testFindRunningExecutions() { */ @Transactional @Test - public void testNoRunningExecutions() { + void testNoRunningExecutions() { Set values = dao.findRunningJobExecutions("no-such-job"); assertEquals(0, values.size()); } @@ -250,7 +250,7 @@ public void testNoRunningExecutions() { */ @Transactional @Test - public void testGetExecution() { + void testGetExecution() { JobExecution exec = new JobExecution(jobInstance, jobParameters); exec.setCreateTime(new Date(0)); exec.createStepExecution("step"); @@ -273,7 +273,7 @@ public void testGetExecution() { */ @Transactional @Test - public void testGetMissingExecution() { + void testGetMissingExecution() { JobExecution value = dao.getJobExecution(54321L); assertNull(value); } @@ -284,7 +284,7 @@ public void testGetMissingExecution() { */ @Transactional @Test - public void testConcurrentModificationException() { + void testConcurrentModificationException() { JobExecution exec1 = new JobExecution(jobInstance, jobParameters); dao.saveJobExecution(exec1); @@ -299,14 +299,7 @@ public void testConcurrentModificationException() { dao.updateJobExecution(exec1); assertEquals((Integer) 1, exec1.getVersion()); - try { - dao.updateJobExecution(exec2); - fail(); - } - catch (OptimisticLockingFailureException e) { - // expected - } - + assertThrows(OptimisticLockingFailureException.class, () -> dao.updateJobExecution(exec2)); } /** @@ -314,7 +307,7 @@ public void testConcurrentModificationException() { */ @Transactional @Test - public void testSynchronizeStatusUpgrade() { + void testSynchronizeStatusUpgrade() { JobExecution exec1 = new JobExecution(jobInstance, jobParameters); exec1.setStatus(BatchStatus.STOPPING); @@ -341,7 +334,7 @@ public void testSynchronizeStatusUpgrade() { */ @Transactional @Test - public void testSynchronizeStatusDowngrade() { + void testSynchronizeStatusDowngrade() { JobExecution exec1 = new JobExecution(jobInstance, jobParameters); exec1.setStatus(BatchStatus.STARTED); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractJobInstanceDaoTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractJobInstanceDaoTests.java index 9cdbe06702..e54479b9de 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractJobInstanceDaoTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractJobInstanceDaoTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2021 the original author or authors. + * Copyright 2008-2022 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. @@ -15,18 +15,18 @@ */ package org.springframework.batch.core.repository.dao; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Date; 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.springframework.batch.core.JobInstance; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.JobParametersBuilder; @@ -38,16 +38,16 @@ public abstract class AbstractJobInstanceDaoTests { protected JobInstanceDao dao; - private String fooJob = "foo"; + private final String fooJob = "foo"; - private JobParameters fooParams = new JobParametersBuilder().addString("stringKey", "stringValue") + private final JobParameters fooParams = new JobParametersBuilder().addString("stringKey", "stringValue") .addLong("longKey", Long.MAX_VALUE).addDouble("doubleKey", Double.MAX_VALUE) .addDate("dateKey", new Date(DATE)).toJobParameters(); protected abstract JobInstanceDao getJobInstanceDao(); - @Before - public void onSetUp() throws Exception { + @BeforeEach + void onSetUp() { dao = getJobInstanceDao(); } @@ -56,7 +56,7 @@ public void onSetUp() throws Exception { */ @Transactional @Test - public void testCreateAndRetrieve() throws Exception { + void testCreateAndRetrieve() { JobInstance fooInstance = dao.createJobInstance(fooJob, fooParams); assertNotNull(fooInstance.getId()); @@ -72,7 +72,7 @@ public void testCreateAndRetrieve() throws Exception { */ @Transactional @Test - public void testCreateAndGetById() throws Exception { + void testCreateAndGetById() { JobInstance fooInstance = dao.createJobInstance(fooJob, fooParams); assertNotNull(fooInstance.getId()); @@ -88,7 +88,7 @@ public void testCreateAndGetById() throws Exception { */ @Transactional @Test - public void testGetMissingById() throws Exception { + void testGetMissingById() { JobInstance retrievedInstance = dao.getJobInstance(1111111L); assertNull(retrievedInstance); @@ -100,7 +100,7 @@ public void testGetMissingById() throws Exception { */ @Transactional @Test - public void testGetJobNames() throws Exception { + void testGetJobNames() { testCreateAndRetrieve(); List jobNames = dao.getJobNames(); @@ -114,7 +114,7 @@ public void testGetJobNames() throws Exception { */ @Transactional @Test - public void testGetLastInstances() throws Exception { + void testGetLastInstances() { testCreateAndRetrieve(); @@ -131,14 +131,14 @@ public void testGetLastInstances() throws Exception { assertEquals(Integer.valueOf(0), jobInstances.get(0).getVersion()); assertEquals(Integer.valueOf(0), jobInstances.get(1).getVersion()); - assertTrue("Last instance should be first on the list", - jobInstances.get(0).getId() > jobInstances.get(1).getId()); + assertTrue(jobInstances.get(0).getId() > jobInstances.get(1).getId(), + "Last instance should be first on the list"); } @Transactional @Test - public void testGetLastInstance() throws Exception { + void testGetLastInstance() { testCreateAndRetrieve(); // unrelated job instance that should be ignored by the query @@ -152,12 +152,12 @@ public void testGetLastInstance() throws Exception { JobInstance lastJobInstance = dao.getLastJobInstance(fooJob); assertNotNull(lastJobInstance); assertEquals(fooJob, lastJobInstance.getJobName()); - assertEquals("Last instance should be first on the list", jobInstances.get(0), lastJobInstance); + assertEquals(jobInstances.get(0), lastJobInstance, "Last instance should be first on the list"); } @Transactional @Test - public void testGetLastInstanceWhenNoInstance() { + void testGetLastInstanceWhenNoInstance() { JobInstance lastJobInstance = dao.getLastJobInstance("NonExistingJob"); assertNull(lastJobInstance); } @@ -167,7 +167,7 @@ public void testGetLastInstanceWhenNoInstance() { */ @Transactional @Test - public void testGetLastInstancesPaged() throws Exception { + void testGetLastInstancesPaged() { testCreateAndRetrieve(); @@ -206,7 +206,7 @@ public void testGetLastInstancesPaged() throws Exception { */ @Transactional @Test - public void testGetLastInstancesPastEnd() throws Exception { + void testGetLastInstancesPastEnd() { testCreateAndRetrieve(); @@ -226,22 +226,16 @@ public void testGetLastInstancesPastEnd() throws Exception { */ @Transactional @Test - public void testCreateDuplicateInstance() { + void testCreateDuplicateInstance() { dao.createJobInstance(fooJob, fooParams); - try { - dao.createJobInstance(fooJob, fooParams); - fail(); - } - catch (IllegalStateException e) { - // expected - } + assertThrows(IllegalStateException.class, () -> dao.createJobInstance(fooJob, fooParams)); } @Transactional @Test - public void testCreationAddsVersion() { + void testCreationAddsVersion() { JobInstance jobInstance = new JobInstance((long) 1, "testVersionAndId"); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractStepExecutionDaoTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractStepExecutionDaoTests.java index 24184b980c..ae3029e7fa 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractStepExecutionDaoTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractStepExecutionDaoTests.java @@ -16,10 +16,10 @@ package org.springframework.batch.core.repository.dao; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.time.Instant; import java.util.ArrayList; @@ -28,8 +28,8 @@ import java.util.Date; 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.springframework.batch.core.BatchStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInstance; @@ -71,8 +71,8 @@ public abstract class AbstractStepExecutionDaoTests extends AbstractTransactiona */ protected abstract JobRepository getJobRepository(); - @Before - public void onSetUp() throws Exception { + @BeforeEach + void onSetUp() throws Exception { repository = getJobRepository(); jobExecution = repository.createJobExecution("job", new JobParameters()); jobInstance = jobExecution.getJobInstance(); @@ -83,7 +83,7 @@ public void onSetUp() throws Exception { @Transactional @Test - public void testSaveExecutionAssignsIdAndVersion() throws Exception { + void testSaveExecutionAssignsIdAndVersion() { assertNull(stepExecution.getId()); assertNull(stepExecution.getVersion()); @@ -94,7 +94,7 @@ public void testSaveExecutionAssignsIdAndVersion() throws Exception { @Transactional @Test - public void testSaveAndGetExecution() { + void testSaveAndGetExecution() { stepExecution.setStatus(BatchStatus.STARTED); stepExecution.setReadSkipCount(7); @@ -121,7 +121,7 @@ public void testSaveAndGetExecution() { @Transactional @Test - public void testSaveAndGetExecutions() { + void testSaveAndGetExecutions() { List stepExecutions = new ArrayList<>(); for (int i = 0; i < 3; i++) { @@ -156,7 +156,7 @@ public void testSaveAndGetExecutions() { @Transactional @Test - public void testSaveAndGetLastExecution() { + void testSaveAndGetLastExecution() { Instant now = Instant.now(); StepExecution stepExecution1 = new StepExecution("step1", jobExecution); stepExecution1.setStartTime(Date.from(now)); @@ -172,7 +172,7 @@ public void testSaveAndGetLastExecution() { @Transactional @Test - public void testSaveAndGetLastExecutionWhenSameStartTime() { + void testSaveAndGetLastExecutionWhenSameStartTime() { Instant now = Instant.now(); StepExecution stepExecution1 = new StepExecution("step1", jobExecution); stepExecution1.setStartTime(Date.from(now)); @@ -188,26 +188,26 @@ public void testSaveAndGetLastExecutionWhenSameStartTime() { } @Transactional - @Test(expected = IllegalArgumentException.class) - public void testSaveNullCollectionThrowsException() { - dao.saveStepExecutions(null); + @Test + void testSaveNullCollectionThrowsException() { + assertThrows(IllegalArgumentException.class, () -> dao.saveStepExecutions(null)); } @Transactional @Test - public void testSaveEmptyCollection() { + void testSaveEmptyCollection() { dao.saveStepExecutions(new ArrayList<>()); } @Transactional @Test - public void testSaveAndGetNonExistentExecution() { + void testSaveAndGetNonExistentExecution() { assertNull(dao.getStepExecution(jobExecution, 45677L)); } @Transactional @Test - public void testSaveAndFindExecution() { + void testSaveAndFindExecution() { stepExecution.setStatus(BatchStatus.STARTED); stepExecution.setReadSkipCount(7); @@ -222,7 +222,7 @@ public void testSaveAndFindExecution() { @Transactional @Test - public void testGetForNotExistingJobExecution() { + void testGetForNotExistingJobExecution() { assertNull(dao.getStepExecution(new JobExecution(jobInstance, (long) 777, new JobParameters()), 11L)); } @@ -231,15 +231,9 @@ public void testGetForNotExistingJobExecution() { */ @Transactional @Test - public void testSaveExecutionWithIdAlreadySet() { + void testSaveExecutionWithIdAlreadySet() { stepExecution.setId((long) 7); - try { - dao.saveStepExecution(stepExecution); - fail(); - } - catch (IllegalArgumentException e) { - // expected - } + assertThrows(IllegalArgumentException.class, () -> dao.saveStepExecution(stepExecution)); } /** @@ -247,15 +241,9 @@ public void testSaveExecutionWithIdAlreadySet() { */ @Transactional @Test - public void testSaveExecutionWithVersionAlreadySet() { + void testSaveExecutionWithVersionAlreadySet() { stepExecution.incrementVersion(); - try { - dao.saveStepExecution(stepExecution); - fail(); - } - catch (IllegalArgumentException e) { - // expected - } + assertThrows(IllegalArgumentException.class, () -> dao.saveStepExecution(stepExecution)); } /** @@ -264,7 +252,7 @@ public void testSaveExecutionWithVersionAlreadySet() { */ @Transactional @Test - public void testUpdateExecution() { + void testUpdateExecution() { stepExecution.setStatus(BatchStatus.STARTED); dao.saveStepExecution(stepExecution); Integer versionAfterSave = stepExecution.getVersion(); @@ -286,7 +274,7 @@ public void testUpdateExecution() { */ @Transactional @Test - public void testConcurrentModificationException() { + void testConcurrentModificationException() { step = new StepSupport("foo"); StepExecution exec1 = new StepExecution(step.getName(), jobExecution); @@ -302,21 +290,14 @@ public void testConcurrentModificationException() { dao.updateStepExecution(exec1); assertEquals(Integer.valueOf(1), exec1.getVersion()); - try { - dao.updateStepExecution(exec2); - fail(); - } - catch (OptimisticLockingFailureException e) { - // expected - } - + assertThrows(OptimisticLockingFailureException.class, () -> dao.updateStepExecution(exec2)); } @Test - public void testGetStepExecutionsWhenNoneExist() throws Exception { + void testGetStepExecutionsWhenNoneExist() { int count = jobExecution.getStepExecutions().size(); dao.addStepExecutions(jobExecution); - assertEquals("Incorrect size of collection", count, jobExecution.getStepExecutions().size()); + assertEquals(count, jobExecution.getStepExecutions().size(), "Incorrect size of collection"); } private void assertStepExecutionsAreEqual(StepExecution expected, StepExecution actual) { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/DateFormatTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/DateFormatTests.java index d5d4cb870a..261e94d6b3 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/DateFormatTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/DateFormatTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,21 +15,20 @@ */ package org.springframework.batch.core.repository.dao; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.text.SimpleDateFormat; -import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; -import java.util.List; import java.util.Locale; import java.util.TimeZone; +import java.util.stream.Stream; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** * Test case showing some weirdnesses in date formatting. Looks like a bug in @@ -39,31 +38,19 @@ * @author Dave Syer * */ -@RunWith(Parameterized.class) -public class DateFormatTests { +class DateFormatTests { - private final SimpleDateFormat format; + private SimpleDateFormat format; - private final String input; - - private final int hour; - - private final String output; - - /** - * - */ - public DateFormatTests(String pattern, String input, String output, int hour) { - this.output = output; - this.format = new SimpleDateFormat(pattern, Locale.UK); + @BeforeEach + void setUp() { + format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S z", Locale.UK); format.setTimeZone(TimeZone.getTimeZone("GMT")); - this.input = input; - this.hour = hour; } - @Test - public void testDateFormat() throws Exception { - + @MethodSource + @ParameterizedTest + void testDateFormat(String input, String output, int hour) throws Exception { Date date = format.parse(input); GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT"), Locale.UK); calendar.setTime(date); @@ -78,29 +65,20 @@ public void testDateFormat() throws Exception { } - @Parameters - public static List data() { - - List params = new ArrayList<>(); - String format = "yyyy-MM-dd HH:mm:ss.S z"; - + static Stream testDateFormat() { /* * When the date format has an explicit time zone these are OK. But on 2008/10/26 * when the clocks went back to GMT these failed the hour assertion (with the hour * coming back as 12). On 2008/10/27, the day after, they are fine, but the * toString still didn't match. */ - params.add(new Object[] { format, "1970-01-01 11:20:34.0 GMT", "1970-01-01 11:20:34.0 GMT", 11 }); - params.add(new Object[] { format, "1971-02-01 11:20:34.0 GMT", "1971-02-01 11:20:34.0 GMT", 11 }); - - // After 1972 you always get the right answer - params.add(new Object[] { format, "1972-02-01 11:20:34.0 GMT", "1972-02-01 11:20:34.0 GMT", 11 }); - params.add(new Object[] { format, "1976-02-01 11:20:34.0 GMT", "1976-02-01 11:20:34.0 GMT", 11 }); - params.add(new Object[] { format, "1982-02-01 11:20:34.0 GMT", "1982-02-01 11:20:34.0 GMT", 11 }); - params.add(new Object[] { format, "2008-02-01 11:20:34.0 GMT", "2008-02-01 11:20:34.0 GMT", 11 }); - - return params; - + return Stream.of(Arguments.of("1970-01-01 11:20:34.0 GMT", "1970-01-01 11:20:34.0 GMT", 11), + Arguments.of("1971-02-01 11:20:34.0 GMT", "1971-02-01 11:20:34.0 GMT", 11), + // After 1972 you always get the right answer + Arguments.of("1972-02-01 11:20:34.0 GMT", "1972-02-01 11:20:34.0 GMT", 11), + Arguments.of("1976-02-01 11:20:34.0 GMT", "1976-02-01 11:20:34.0 GMT", 11), + Arguments.of("1982-02-01 11:20:34.0 GMT", "1982-02-01 11:20:34.0 GMT", 11), + Arguments.of("2008-02-01 11:20:34.0 GMT", "2008-02-01 11:20:34.0 GMT", 11)); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/DefaultExecutionContextSerializerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/DefaultExecutionContextSerializerTests.java index 94381b5859..c6cfe10f08 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/DefaultExecutionContextSerializerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/DefaultExecutionContextSerializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2022 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. @@ -15,36 +15,29 @@ */ package org.springframework.batch.core.repository.dao; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.repository.ExecutionContextSerializer; import java.io.ByteArrayOutputStream; import java.util.HashMap; import java.util.Map; +import static org.junit.jupiter.api.Assertions.assertThrows; + /** * @author Michael Minella * */ -public class DefaultExecutionContextSerializerTests extends AbstractExecutionContextSerializerTests { - - private DefaultExecutionContextSerializer serializer; +class DefaultExecutionContextSerializerTests extends AbstractExecutionContextSerializerTests { - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - serializer = new DefaultExecutionContextSerializer(); - } + private final DefaultExecutionContextSerializer serializer = new DefaultExecutionContextSerializer(); - @Test(expected = IllegalArgumentException.class) - public void testSerializeNonSerializable() throws Exception { + @Test + void testSerializeNonSerializable() { Map m1 = new HashMap<>(); m1.put("object1", new Object()); - serializer.serialize(m1, new ByteArrayOutputStream()); + assertThrows(IllegalArgumentException.class, () -> serializer.serialize(m1, new ByteArrayOutputStream())); } @Override diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/Jackson2ExecutionContextStringSerializerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/Jackson2ExecutionContextStringSerializerTests.java index 2dc4df9a3c..ae3e7b74b8 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/Jackson2ExecutionContextStringSerializerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/Jackson2ExecutionContextStringSerializerTests.java @@ -28,33 +28,28 @@ import java.util.Map; import com.fasterxml.jackson.annotation.JsonTypeInfo; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.repository.ExecutionContextSerializer; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Marten Deinum * @author Michael Minella * @author Mahmoud Ben Hassine */ -public class Jackson2ExecutionContextStringSerializerTests extends AbstractExecutionContextSerializerTests { +class Jackson2ExecutionContextStringSerializerTests extends AbstractExecutionContextSerializerTests { - ExecutionContextSerializer serializer; - - @Before - public void onSetUp() throws Exception { - Jackson2ExecutionContextStringSerializer serializerDeserializer = new Jackson2ExecutionContextStringSerializer( - AbstractExecutionContextSerializerTests.Person.class.getName()); - - serializer = serializerDeserializer; - } + private final ExecutionContextSerializer serializer = new Jackson2ExecutionContextStringSerializer( + AbstractExecutionContextSerializerTests.Person.class.getName()); @Test - public void mappedTypeTest() throws IOException { + void mappedTypeTest() throws IOException { Person person = new Person(); person.age = 28; @@ -73,16 +68,11 @@ public void mappedTypeTest() throws IOException { InputStream in = new ByteArrayInputStream(os.toByteArray()); - try { - j.deserialize(in); - } - catch (Exception e) { - fail(String.format("An exception was thrown but should not have been: %s", e.getMessage())); - } + assertDoesNotThrow(() -> j.deserialize(in)); } @Test - public void testAdditionalTrustedClass() throws IOException { + void testAdditionalTrustedClass() throws IOException { // given Jackson2ExecutionContextStringSerializer serializer = new Jackson2ExecutionContextStringSerializer( "java.util.Locale"); @@ -97,7 +87,7 @@ public void testAdditionalTrustedClass() throws IOException { // then Locale locale = (Locale) deserializedContext.get("locale"); - Assert.assertNotNull(locale); + assertNotNull(locale); } @Override @@ -134,7 +124,7 @@ public static class DomesticNumber extends PhoneNumber { } @Test - public void unmappedTypeTest() throws IOException { + void unmappedTypeTest() throws IOException { UnmappedPerson person = new UnmappedPerson(); person.age = 28; @@ -153,13 +143,7 @@ public void unmappedTypeTest() throws IOException { InputStream in = new ByteArrayInputStream(os.toByteArray()); - try { - j.deserialize(in); - fail("An exception should have been thrown but wasn't"); - } - catch (Exception e) { - return; - } + assertThrows(Exception.class, () -> j.deserialize(in)); } public static class UnmappedPerson { @@ -189,7 +173,7 @@ public static class UnmappedDomesticNumber extends UnmappedPhoneNumber { } @Test - public void arrayAsListSerializationTest() throws IOException { + void arrayAsListSerializationTest() throws IOException { // given List list = Arrays.asList("foo", "bar"); String key = "Arrays.asList"; @@ -205,12 +189,12 @@ public void arrayAsListSerializationTest() throws IOException { // then Object deserializedValue = deserializedContext.get(key); - Assert.assertTrue(List.class.isAssignableFrom(deserializedValue.getClass())); - Assert.assertTrue(((List) deserializedValue).containsAll(list)); + assertTrue(List.class.isAssignableFrom(deserializedValue.getClass())); + assertTrue(((List) deserializedValue).containsAll(list)); } @Test - public void testSqlTimestampSerialization() throws IOException { + void testSqlTimestampSerialization() throws IOException { // given Jackson2ExecutionContextStringSerializer serializer = new Jackson2ExecutionContextStringSerializer(); Map context = new HashMap<>(1); @@ -225,7 +209,7 @@ public void testSqlTimestampSerialization() throws IOException { // then Timestamp deserializedTimestamp = (Timestamp) deserializedContext.get("timestamp"); - Assert.assertEquals(timestamp, deserializedTimestamp); + assertEquals(timestamp, deserializedTimestamp); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/JdbcExecutionContextDaoTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/JdbcExecutionContextDaoTests.java index f6b7f180c9..52f1929bda 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/JdbcExecutionContextDaoTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/JdbcExecutionContextDaoTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2018 the original author or authors. + * Copyright 2008-2022 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. @@ -15,45 +15,33 @@ */ package org.springframework.batch.core.repository.dao; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.jdbc.core.JdbcOperations; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = { "sql-dao-test.xml" }) -public class JdbcExecutionContextDaoTests extends AbstractExecutionContextDaoTests { +@SpringJUnitConfig(locations = { "sql-dao-test.xml" }) +class JdbcExecutionContextDaoTests extends AbstractExecutionContextDaoTests { @Test - public void testNoSerializer() { - try { - JdbcExecutionContextDao jdbcExecutionContextDao = new JdbcExecutionContextDao(); - jdbcExecutionContextDao.setJdbcTemplate(mock(JdbcOperations.class)); - jdbcExecutionContextDao.afterPropertiesSet(); - } - catch (Exception e) { - Assert.assertTrue(e instanceof IllegalStateException); - Assert.assertEquals("ExecutionContextSerializer is required", e.getMessage()); - } + void testNoSerializer() { + JdbcExecutionContextDao jdbcExecutionContextDao = new JdbcExecutionContextDao(); + jdbcExecutionContextDao.setJdbcTemplate(mock(JdbcOperations.class)); + Exception exception = assertThrows(IllegalStateException.class, jdbcExecutionContextDao::afterPropertiesSet); + assertEquals("ExecutionContextSerializer is required", exception.getMessage()); } @Test - public void testNullSerializer() { - try { - JdbcExecutionContextDao jdbcExecutionContextDao = new JdbcExecutionContextDao(); - jdbcExecutionContextDao.setJdbcTemplate(mock(JdbcOperations.class)); - jdbcExecutionContextDao.setSerializer(null); - jdbcExecutionContextDao.afterPropertiesSet(); - } - catch (Exception e) { - Assert.assertTrue(e instanceof IllegalArgumentException); - Assert.assertEquals("Serializer must not be null", e.getMessage()); - } + void testNullSerializer() { + JdbcExecutionContextDao jdbcExecutionContextDao = new JdbcExecutionContextDao(); + jdbcExecutionContextDao.setJdbcTemplate(mock(JdbcOperations.class)); + Exception exception = assertThrows(IllegalArgumentException.class, + () -> jdbcExecutionContextDao.setSerializer(null)); + assertEquals("Serializer must not be null", exception.getMessage()); } @Override diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/JdbcJobDaoQueryTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/JdbcJobDaoQueryTests.java index efbdfa184b..38ae4477eb 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/JdbcJobDaoQueryTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/JdbcJobDaoQueryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -18,8 +18,8 @@ import java.util.ArrayList; import java.util.List; -import junit.framework.TestCase; - +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInstance; import org.springframework.batch.core.JobParameters; @@ -27,23 +27,21 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.support.incrementer.DataFieldMaxValueIncrementer; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.springframework.test.util.AssertionErrors.assertTrue; + /** * @author Dave Syer * */ -public class JdbcJobDaoQueryTests extends TestCase { +class JdbcJobDaoQueryTests { JdbcJobExecutionDao jobExecutionDao; List list = new ArrayList<>(); - /* - * (non-Javadoc) - * - * @see junit.framework.TestCase#setUp() - */ - @Override - protected void setUp() throws Exception { + @BeforeEach + void setUp() { jobExecutionDao = new JdbcJobExecutionDao(); jobExecutionDao.setJobExecutionIncrementer(new DataFieldMaxValueIncrementer() { @@ -66,7 +64,8 @@ public String nextStringValue() throws DataAccessException { }); } - public void testTablePrefix() throws Exception { + @Test + void testTablePrefix() { jobExecutionDao.setTablePrefix("FOO_"); jobExecutionDao.setJdbcTemplate(new JdbcTemplate() { @Override @@ -80,7 +79,7 @@ public int update(String sql, Object[] args, int[] argTypes) throws DataAccessEx jobExecutionDao.saveJobExecution(jobExecution); assertEquals(1, list.size()); String query = list.get(0); - assertTrue("Query did not contain FOO_:" + query, query.indexOf("FOO_") >= 0); + assertTrue("Query did not contain FOO_:" + query, query.contains("FOO_")); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/JdbcJobDaoTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/JdbcJobDaoTests.java index 810c781f6b..0cf0ed4df6 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/JdbcJobDaoTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/JdbcJobDaoTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2014 the original author or authors. + * Copyright 2008-2022 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. @@ -15,35 +15,32 @@ */ package org.springframework.batch.core.repository.dao; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import java.util.Map; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.ExitStatus; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.transaction.annotation.Transactional; -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = { "sql-dao-test.xml" }) +@SpringJUnitConfig(locations = { "sql-dao-test.xml" }) public class JdbcJobDaoTests extends AbstractJobDaoTests { public static final String LONG_STRING = "A very long String A very long String A very long String A very long String A very long String A very long String A very long String A very long String A very long String A very long String A very long String A very long String A very long String A very long String A very long String A very long String A very long String A very long String A very long String "; - @Before - public void onSetUpBeforeTransaction() throws Exception { + @BeforeEach + void onSetUpBeforeTransaction() { ((JdbcJobInstanceDao) jobInstanceDao).setTablePrefix(AbstractJdbcBatchMetadataDao.DEFAULT_TABLE_PREFIX); ((JdbcJobExecutionDao) jobExecutionDao).setTablePrefix(AbstractJdbcBatchMetadataDao.DEFAULT_TABLE_PREFIX); } @Transactional @Test - public void testUpdateJobExecutionWithLongExitCode() { + void testUpdateJobExecutionWithLongExitCode() { assertTrue(LONG_STRING.length() > 250); ((JdbcJobExecutionDao) jobExecutionDao).setExitMessageLength(250); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/JdbcJobExecutionDaoTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/JdbcJobExecutionDaoTests.java index 5807cf1016..b67e196631 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/JdbcJobExecutionDaoTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/JdbcJobExecutionDaoTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2021 the original author or authors. + * Copyright 2008-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,9 +22,8 @@ import javax.sql.DataSource; -import static org.junit.Assert.assertNull; -import org.junit.Test; -import org.junit.runner.RunWith; +import static org.junit.jupiter.api.Assertions.assertNull; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameter; @@ -34,16 +33,14 @@ import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.jdbc.JdbcTestUtils; import org.springframework.transaction.annotation.Transactional; /** * @author Parikshit Dutta */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = { "sql-dao-test.xml" }) +@SpringJUnitConfig(locations = { "sql-dao-test.xml" }) public class JdbcJobExecutionDaoTests extends AbstractJobExecutionDaoTests { @Autowired @@ -81,7 +78,7 @@ protected StepExecutionDao getStepExecutionDao() { @Transactional @Test - public void testSavedDateIsNullForNonDateTypeJobParams() { + void testSavedDateIsNullForNonDateTypeJobParams() { final String FIND_DATE_PARAM_FROM_ID = "SELECT DATE_VAL " + "from %PREFIX%JOB_EXECUTION_PARAMS where JOB_EXECUTION_ID = :JOB_EXECUTION_ID"; diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/JdbcJobInstanceDaoTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/JdbcJobInstanceDaoTests.java index d692788e36..5e2a442376 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/JdbcJobInstanceDaoTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/JdbcJobInstanceDaoTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2021 the original author or authors. + * Copyright 2008-2022 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. @@ -15,8 +15,8 @@ */ package org.springframework.batch.core.repository.dao; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.math.BigInteger; import java.security.MessageDigest; @@ -24,20 +24,17 @@ import javax.sql.DataSource; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInstance; import org.springframework.batch.core.JobParameters; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.jdbc.JdbcTestUtils; import org.springframework.transaction.annotation.Transactional; -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = "sql-dao-test.xml") +@SpringJUnitConfig(locations = "sql-dao-test.xml") public class JdbcJobInstanceDaoTests extends AbstractJobInstanceDaoTests { private JdbcTemplate jdbcTemplate; @@ -62,7 +59,7 @@ protected JobInstanceDao getJobInstanceDao() { @Transactional @Test - public void testFindJobInstanceByExecution() { + void testFindJobInstanceByExecution() { JobParameters jobParameters = new JobParameters(); JobInstance jobInstance = dao.createJobInstance("testInstance", jobParameters); @@ -74,21 +71,21 @@ public void testFindJobInstanceByExecution() { } @Test - public void testHexing() throws Exception { + void testHexing() throws Exception { MessageDigest digest = MessageDigest.getInstance("MD5"); byte[] bytes = digest.digest("f78spx".getBytes("UTF-8")); StringBuilder output = new StringBuilder(); for (byte bite : bytes) { output.append(String.format("%02x", bite)); } - assertEquals("Wrong hash: " + output, 32, output.length()); + assertEquals(32, output.length(), "Wrong hash: " + output); String value = String.format("%032x", new BigInteger(1, bytes)); - assertEquals("Wrong hash: " + value, 32, value.length()); + assertEquals(32, value.length(), "Wrong hash: " + value); assertEquals(value, output.toString()); } @Test - public void testJobInstanceWildcard() { + void testJobInstanceWildcard() { dao.createJobInstance("anotherJob", new JobParameters()); dao.createJobInstance("someJob", new JobParameters()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/JdbcStepExecutionDaoTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/JdbcStepExecutionDaoTests.java index e42374e904..989b4b7272 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/JdbcStepExecutionDaoTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/JdbcStepExecutionDaoTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2020 the original author or authors. + * Copyright 2008-2022 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. @@ -15,21 +15,18 @@ */ package org.springframework.batch.core.repository.dao; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.repository.JobRepository; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.transaction.annotation.Transactional; -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = "sql-dao-test.xml") -public class JdbcStepExecutionDaoTests extends AbstractStepExecutionDaoTests { +@SpringJUnitConfig(locations = "sql-dao-test.xml") +class JdbcStepExecutionDaoTests extends AbstractStepExecutionDaoTests { @Override protected StepExecutionDao getStepExecutionDao() { @@ -48,7 +45,7 @@ protected JobRepository getJobRepository() { */ @Transactional @Test - public void testTruncateExitDescription() { + void testTruncateExitDescription() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 100; i++) { @@ -65,20 +62,20 @@ public void testTruncateExitDescription() { StepExecution retrievedAfterSave = dao.getStepExecution(jobExecution, stepExecution.getId()); - assertTrue("Exit description should be truncated", retrievedAfterSave.getExitStatus().getExitDescription() - .length() < stepExecution.getExitStatus().getExitDescription().length()); + assertTrue(retrievedAfterSave.getExitStatus().getExitDescription().length() < stepExecution.getExitStatus() + .getExitDescription().length(), "Exit description should be truncated"); dao.updateStepExecution(stepExecution); StepExecution retrievedAfterUpdate = dao.getStepExecution(jobExecution, stepExecution.getId()); - assertTrue("Exit description should be truncated", retrievedAfterUpdate.getExitStatus().getExitDescription() - .length() < stepExecution.getExitStatus().getExitDescription().length()); + assertTrue(retrievedAfterUpdate.getExitStatus().getExitDescription().length() < stepExecution.getExitStatus() + .getExitDescription().length(), "Exit description should be truncated"); } @Transactional @Test - public void testCountStepExecutions() { + void testCountStepExecutions() { // Given dao.saveStepExecution(stepExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/NoSuchBatchDomainObjectExceptionTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/NoSuchBatchDomainObjectExceptionTests.java index 7527d4ee63..53d72a610d 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/NoSuchBatchDomainObjectExceptionTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/NoSuchBatchDomainObjectExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,18 +15,18 @@ */ package org.springframework.batch.core.repository.dao; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author Dave Syer * */ -public class NoSuchBatchDomainObjectExceptionTests { +class NoSuchBatchDomainObjectExceptionTests { @Test - public void testCreateException() throws Exception { + void testCreateException() { NoSuchObjectException e = new NoSuchObjectException("Foo"); assertEquals("Foo", e.getMessage()); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/OptimisticLockingFailureTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/OptimisticLockingFailureTests.java index 4434f23929..6cf4256f1b 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/OptimisticLockingFailureTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/OptimisticLockingFailureTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2020 the original author or authors. + * Copyright 2014-2022 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,13 +16,13 @@ package org.springframework.batch.core.repository.dao; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.EnumSet; import java.util.List; import java.util.Set; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; @@ -42,13 +42,13 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.lang.Nullable; -public class OptimisticLockingFailureTests { +class OptimisticLockingFailureTests { private static final Set END_STATUSES = EnumSet.of(BatchStatus.COMPLETED, BatchStatus.FAILED, BatchStatus.STOPPED); @Test - public void testAsyncStopOfStartingJob() throws Exception { + void testAsyncStopOfStartingJob() throws Exception { ApplicationContext applicationContext = new ClassPathXmlApplicationContext( "org/springframework/batch/core/repository/dao/OptimisticLockingFailureTests-context.xml"); Job job = applicationContext.getBean(Job.class); @@ -74,12 +74,12 @@ public void testAsyncStopOfStartingJob() throws Exception { BatchStatus stepExecutionStatus = stepExecution.getStatus(); BatchStatus jobExecutionStatus = jobExecution.getStatus(); - assertTrue("Should only be one StepExecution but got: " + numStepExecutions, numStepExecutions == 1); - assertTrue("Step name for execution should be step1 but got: " + stepName, "step1".equals(stepName)); - assertTrue("Step execution status should be STOPPED but got: " + stepExecutionStatus, - stepExecutionStatus.equals(BatchStatus.STOPPED)); - assertTrue("Job execution status should be STOPPED but got:" + jobExecutionStatus, - jobExecutionStatus.equals(BatchStatus.STOPPED)); + assertEquals(1, numStepExecutions, "Should only be one StepExecution but got: " + numStepExecutions); + assertEquals("step1", stepName, "Step name for execution should be step1 but got: " + stepName); + assertEquals(stepExecutionStatus, BatchStatus.STOPPED, + "Step execution status should be STOPPED but got: " + stepExecutionStatus); + assertEquals(jobExecutionStatus, BatchStatus.STOPPED, + "Job execution status should be STOPPED but got:" + jobExecutionStatus); JobExecution restartJobExecution = jobLauncher.run(job, jobParameters); @@ -91,19 +91,19 @@ public void testAsyncStopOfStartingJob() throws Exception { } int restartNumStepExecutions = restartJobExecution.getStepExecutions().size(); - assertTrue("Should be two StepExecution's on restart but got: " + restartNumStepExecutions, - restartNumStepExecutions == 2); + assertEquals(2, restartNumStepExecutions, + "Should be two StepExecution's on restart but got: " + restartNumStepExecutions); for (StepExecution restartStepExecution : restartJobExecution.getStepExecutions()) { BatchStatus restartStepExecutionStatus = restartStepExecution.getStatus(); - assertTrue("Step execution status should be COMPLETED but got: " + restartStepExecutionStatus, - restartStepExecutionStatus.equals(BatchStatus.COMPLETED)); + assertEquals(restartStepExecutionStatus, BatchStatus.COMPLETED, + "Step execution status should be COMPLETED but got: " + restartStepExecutionStatus); } BatchStatus restartJobExecutionStatus = restartJobExecution.getStatus(); - assertTrue("Job execution status should be COMPLETED but got:" + restartJobExecutionStatus, - restartJobExecutionStatus.equals(BatchStatus.COMPLETED)); + assertEquals(restartJobExecutionStatus, BatchStatus.COMPLETED, + "Job execution status should be COMPLETED but got:" + restartJobExecutionStatus); } public static class Writer implements ItemWriter { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/TablePrefixTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/TablePrefixTests.java index d69fce5996..cf532620c1 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/TablePrefixTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/TablePrefixTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2019 the original author or authors. + * Copyright 2006-2022 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. @@ -15,12 +15,11 @@ */ package org.springframework.batch.core.repository.dao; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import javax.sql.DataSource; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -33,13 +32,11 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.lang.Nullable; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.jdbc.JdbcTestUtils; -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class TablePrefixTests { +@SpringJUnitConfig +class TablePrefixTests { @Autowired private JobLauncher jobLauncher; @@ -55,13 +52,13 @@ public void setDataSource(DataSource dataSource) { } @Test - public void testJobLaunch() throws Exception { + void testJobLaunch() throws Exception { JobExecution jobExecution = jobLauncher.run(job, new JobParameters()); assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus()); assertEquals(1, JdbcTestUtils.countRowsInTable(jdbcTemplate, "PREFIX_JOB_INSTANCE")); } - public static class TestTasklet implements Tasklet { + static class TestTasklet implements Tasklet { @Nullable @Override diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/support/JobRepositoryFactoryBeanTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/support/JobRepositoryFactoryBeanTests.java index e019a1671f..8ac67f9d45 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/support/JobRepositoryFactoryBeanTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/support/JobRepositoryFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,9 +21,9 @@ import java.util.Map; import javax.sql.DataSource; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.repository.ExecutionContextSerializer; @@ -43,10 +43,10 @@ import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.support.DefaultTransactionDefinition; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -56,7 +56,7 @@ * @author Mahmoud Ben Hassine * */ -public class JobRepositoryFactoryBeanTests { +class JobRepositoryFactoryBeanTests { private JobRepositoryFactoryBean factory; @@ -66,10 +66,10 @@ public class JobRepositoryFactoryBeanTests { private PlatformTransactionManager transactionManager; - private String tablePrefix = "TEST_BATCH_PREFIX_"; + private final String tablePrefix = "TEST_BATCH_PREFIX_"; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { factory = new JobRepositoryFactoryBean(); dataSource = mock(DataSource.class); @@ -83,7 +83,7 @@ public void setUp() throws Exception { } @Test - public void testNoDatabaseType() throws Exception { + void testNoDatabaseType() throws Exception { DatabaseMetaData dmd = mock(DatabaseMetaData.class); Connection con = mock(Connection.class); @@ -105,7 +105,7 @@ public void testNoDatabaseType() throws Exception { } @Test - public void testOracleLobHandler() throws Exception { + void testOracleLobHandler() throws Exception { factory.setDatabaseType("ORACLE"); @@ -125,7 +125,7 @@ public void testOracleLobHandler() throws Exception { } @Test - public void testCustomLobHandler() throws Exception { + void testCustomLobHandler() throws Exception { factory.setDatabaseType("ORACLE"); @@ -148,7 +148,7 @@ public void testCustomLobHandler() throws Exception { @Test @SuppressWarnings("unchecked") - public void tesDefaultSerializer() throws Exception { + void tesDefaultSerializer() throws Exception { factory.setDatabaseType("ORACLE"); @@ -168,7 +168,7 @@ public void tesDefaultSerializer() throws Exception { } @Test - public void testCustomSerializer() throws Exception { + void testCustomSerializer() throws Exception { factory.setDatabaseType("ORACLE"); @@ -189,7 +189,7 @@ public void testCustomSerializer() throws Exception { } @Test - public void testDefaultJdbcOperations() throws Exception { + void testDefaultJdbcOperations() throws Exception { factory.setDatabaseType("ORACLE"); @@ -209,7 +209,7 @@ public void testDefaultJdbcOperations() throws Exception { } @Test - public void testCustomJdbcOperations() throws Exception { + void testCustomJdbcOperations() throws Exception { factory.setDatabaseType("ORACLE"); @@ -231,61 +231,44 @@ public void testCustomJdbcOperations() throws Exception { } @Test - public void testMissingDataSource() throws Exception { + void testMissingDataSource() { factory.setDataSource(null); - try { - factory.afterPropertiesSet(); - fail(); - } - catch (IllegalArgumentException ex) { - // expected - String message = ex.getMessage(); - assertTrue("Wrong message: " + message, message.contains("DataSource")); - } + Exception exception = assertThrows(IllegalArgumentException.class, factory::afterPropertiesSet); + String message = exception.getMessage(); + assertTrue(message.contains("DataSource"), "Wrong message: " + message); } @Test - public void testMissingTransactionManager() throws Exception { + void testMissingTransactionManager() { factory.setDatabaseType("mockDb"); factory.setTransactionManager(null); - try { - when(incrementerFactory.isSupportedIncrementerType("mockDb")).thenReturn(true); - when(incrementerFactory.getSupportedIncrementerTypes()).thenReturn(new String[0]); + when(incrementerFactory.isSupportedIncrementerType("mockDb")).thenReturn(true); + when(incrementerFactory.getSupportedIncrementerTypes()).thenReturn(new String[0]); - factory.afterPropertiesSet(); - fail(); - } - catch (IllegalArgumentException ex) { - // expected - String message = ex.getMessage(); - assertTrue("Wrong message: " + message, message.contains("TransactionManager")); - } + Exception exception = assertThrows(IllegalArgumentException.class, () -> factory.afterPropertiesSet()); + String message = exception.getMessage(); + assertTrue(message.contains("TransactionManager"), "Wrong message: " + message); } @Test - public void testInvalidDatabaseType() throws Exception { + void testInvalidDatabaseType() { factory.setDatabaseType("foo"); - try { - when(incrementerFactory.isSupportedIncrementerType("foo")).thenReturn(false); - when(incrementerFactory.getSupportedIncrementerTypes()).thenReturn(new String[0]); - factory.afterPropertiesSet(); - fail(); - } - catch (IllegalArgumentException ex) { - // expected - String message = ex.getMessage(); - assertTrue("Wrong message: " + message, message.contains("foo")); - } + when(incrementerFactory.isSupportedIncrementerType("foo")).thenReturn(false); + when(incrementerFactory.getSupportedIncrementerTypes()).thenReturn(new String[0]); + + Exception exception = assertThrows(IllegalArgumentException.class, () -> factory.afterPropertiesSet()); + String message = exception.getMessage(); + assertTrue(message.contains("foo"), "Wrong message: " + message); } @Test - public void testCreateRepository() throws Exception { + void testCreateRepository() throws Exception { String databaseType = "HSQL"; factory.setDatabaseType(databaseType); @@ -302,30 +285,21 @@ public void testCreateRepository() throws Exception { factory.getObject(); } - @Ignore + @Disabled @Test - public void testTransactionAttributesForCreateMethodNullHypothesis() throws Exception { + void testTransactionAttributesForCreateMethodNullHypothesis() throws Exception { testCreateRepository(); JobRepository repository = factory.getObject(); DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition( DefaultTransactionDefinition.PROPAGATION_REQUIRES_NEW); when(transactionManager.getTransaction(transactionDefinition)).thenReturn(null); - try { - repository.createJobExecution("foo", new JobParameters()); - // we expect an exception from the txControl because we provided the - // wrong meta data - fail("Expected IllegalArgumentException"); - } - catch (AssertionError e) { - // expected exception from txControl - wrong isolation level used in - // comparison - assertEquals("Unexpected method call", e.getMessage().substring(3, 25)); - } - + Error error = assertThrows(AssertionError.class, + () -> repository.createJobExecution("foo", new JobParameters())); + assertEquals("Unexpected method call", error.getMessage().substring(3, 25)); } @Test - public void testTransactionAttributesForCreateMethod() throws Exception { + void testTransactionAttributesForCreateMethod() throws Exception { testCreateRepository(); JobRepository repository = factory.getObject(); @@ -335,21 +309,14 @@ public void testTransactionAttributesForCreateMethod() throws Exception { when(transactionManager.getTransaction(transactionDefinition)).thenReturn(null); Connection conn = mock(Connection.class); when(dataSource.getConnection()).thenReturn(conn); - try { - repository.createJobExecution("foo", new JobParameters()); - // we expect an exception but not from the txControl because we - // provided the correct meta data - fail("Expected IllegalArgumentException"); - } - catch (IllegalArgumentException e) { - // expected exception from DataSourceUtils - assertEquals("No Statement specified", e.getMessage()); - } + Exception exception = assertThrows(IllegalArgumentException.class, + () -> repository.createJobExecution("foo", new JobParameters())); + assertEquals("No Statement specified", exception.getMessage()); } @Test - public void testSetTransactionAttributesForCreateMethod() throws Exception { + void testSetTransactionAttributesForCreateMethod() throws Exception { factory.setIsolationLevelForCreate(Isolation.READ_UNCOMMITTED); testCreateRepository(); @@ -360,26 +327,19 @@ public void testSetTransactionAttributesForCreateMethod() throws Exception { when(transactionManager.getTransaction(transactionDefinition)).thenReturn(null); Connection conn = mock(Connection.class); when(dataSource.getConnection()).thenReturn(conn); - try { - repository.createJobExecution("foo", new JobParameters()); - // we expect an exception but not from the txControl because we - // provided the correct meta data - fail("Expected IllegalArgumentException"); - } - catch (IllegalArgumentException e) { - // expected exception from DataSourceUtils - assertEquals("No Statement specified", e.getMessage()); - } + Exception exception = assertThrows(IllegalArgumentException.class, + () -> repository.createJobExecution("foo", new JobParameters())); + assertEquals("No Statement specified", exception.getMessage()); } - @Test(expected = IllegalArgumentException.class) - public void testInvalidCustomLobType() throws Exception { + @Test + void testInvalidCustomLobType() { factory.setClobType(Integer.MAX_VALUE); - testCreateRepository(); + assertThrows(IllegalArgumentException.class, this::testCreateRepository); } @Test - public void testCustomLobType() throws Exception { + void testCustomLobType() throws Exception { factory.setClobType(Types.ARRAY); testCreateRepository(); JobRepository repository = factory.getObject(); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/support/SimpleJobRepositoryIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/support/SimpleJobRepositoryIntegrationTests.java index 683259b0ff..55a161beb9 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/support/SimpleJobRepositoryIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/support/SimpleJobRepositoryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2021 the original author or authors. + * Copyright 2008-2022 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. @@ -15,8 +15,7 @@ */ package org.springframework.batch.core.repository.support; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; @@ -28,16 +27,15 @@ import org.springframework.batch.core.step.StepSupport; import org.springframework.batch.item.ExecutionContext; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.transaction.annotation.Transactional; import java.util.Arrays; import java.util.Date; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * Repository tests using JDBC DAOs (rather than mocks). @@ -46,16 +44,15 @@ * @author Dimitrios Liapis * @author Mahmoud Ben Hassine */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = "/org/springframework/batch/core/repository/dao/sql-dao-test.xml") -public class SimpleJobRepositoryIntegrationTests { +@SpringJUnitConfig(locations = "/org/springframework/batch/core/repository/dao/sql-dao-test.xml") +class SimpleJobRepositoryIntegrationTests { @Autowired private SimpleJobRepository jobRepository; - private JobSupport job = new JobSupport("SimpleJobRepositoryIntegrationTestsJob"); + private final JobSupport job = new JobSupport("SimpleJobRepositoryIntegrationTestsJob"); - private JobParameters jobParameters = new JobParameters(); + private final JobParameters jobParameters = new JobParameters(); /* * Create two job executions for same job+parameters tuple. Check both executions @@ -63,7 +60,7 @@ public class SimpleJobRepositoryIntegrationTests { */ @Transactional @Test - public void testCreateAndFind() throws Exception { + void testCreateAndFind() throws Exception { job.setRestartable(true); @@ -93,7 +90,7 @@ public void testCreateAndFind() throws Exception { */ @Transactional @Test - public void testCreateAndFindWithNoStartDate() throws Exception { + void testCreateAndFindWithNoStartDate() throws Exception { job.setRestartable(true); JobExecution firstExecution = jobRepository.createJobExecution(job.getName(), jobParameters); @@ -112,7 +109,7 @@ public void testCreateAndFindWithNoStartDate() throws Exception { */ @Transactional @Test - public void testGetStepExecutionCountAndLastStepExecution() throws Exception { + void testGetStepExecutionCountAndLastStepExecution() throws Exception { job.setRestartable(true); StepSupport step = new StepSupport("restartedStep"); @@ -149,8 +146,7 @@ public void testGetStepExecutionCountAndLastStepExecution() throws Exception { */ @Transactional @Test - public void testSaveExecutionContext() throws Exception { - @SuppressWarnings("serial") + void testSaveExecutionContext() throws Exception { ExecutionContext ctx = new ExecutionContext() { { putLong("crashedPosition", 7); @@ -181,7 +177,7 @@ public void testSaveExecutionContext() throws Exception { */ @Transactional @Test - public void testOnlyOneJobExecutionAllowedRunning() throws Exception { + void testOnlyOneJobExecutionAllowedRunning() throws Exception { job.setRestartable(true); JobExecution jobExecution = jobRepository.createJobExecution(job.getName(), jobParameters); @@ -189,18 +185,13 @@ public void testOnlyOneJobExecutionAllowedRunning() throws Exception { jobExecution.setStartTime(new Date()); jobRepository.update(jobExecution); - try { - jobRepository.createJobExecution(job.getName(), jobParameters); - fail(); - } - catch (JobExecutionAlreadyRunningException e) { - // expected - } + assertThrows(JobExecutionAlreadyRunningException.class, + () -> jobRepository.createJobExecution(job.getName(), jobParameters)); } @Transactional @Test - public void testGetLastJobExecution() throws Exception { + void testGetLastJobExecution() throws Exception { JobExecution jobExecution = jobRepository.createJobExecution(job.getName(), jobParameters); jobExecution.setStatus(BatchStatus.FAILED); jobExecution.setEndTime(new Date()); @@ -220,7 +211,7 @@ public void testGetLastJobExecution() throws Exception { */ @Transactional @Test - public void testReExecuteWithSameJobParameters() throws Exception { + void testReExecuteWithSameJobParameters() throws Exception { JobParameters jobParameters = new JobParametersBuilder().addString("name", "foo", false).toJobParameters(); JobExecution jobExecution1 = jobRepository.createJobExecution(job.getName(), jobParameters); jobExecution1.setStatus(BatchStatus.COMPLETED); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/support/SimpleJobRepositoryProxyTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/support/SimpleJobRepositoryProxyTests.java index 9f853770cd..2bf2f0271c 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/support/SimpleJobRepositoryProxyTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/support/SimpleJobRepositoryProxyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2013 the original author or authors. + * Copyright 2009-2022 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. @@ -15,14 +15,14 @@ */ package org.springframework.batch.core.repository.support; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.job.JobSupport; @@ -30,8 +30,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.transaction.annotation.Transactional; /** @@ -39,10 +38,9 @@ * * @author Robert Kasanicky */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration +@SpringJUnitConfig @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) -public class SimpleJobRepositoryProxyTests { +class SimpleJobRepositoryProxyTests { @Autowired private JobRepository jobRepository; @@ -50,19 +48,18 @@ public class SimpleJobRepositoryProxyTests { @Autowired private Advice advice; - private JobSupport job = new JobSupport("SimpleJobRepositoryProxyTestsJob"); + private final JobSupport job = new JobSupport("SimpleJobRepositoryProxyTestsJob"); @Transactional - @Test(expected = IllegalStateException.class) - public void testCreateAndFindWithExistingTransaction() throws Exception { + @Test + void testCreateAndFindWithExistingTransaction() { assertFalse(advice.invoked); - JobExecution jobExecution = jobRepository.createJobExecution(job.getName(), new JobParameters()); - assertNotNull(jobExecution); - assertTrue(advice.invoked); + assertThrows(IllegalStateException.class, + () -> jobRepository.createJobExecution(job.getName(), new JobParameters())); } @Test - public void testCreateAndFindNoTransaction() throws Exception { + void testCreateAndFindNoTransaction() throws Exception { assertFalse(advice.invoked); JobExecution jobExecution = jobRepository.createJobExecution(job.getName(), new JobParameters()); assertNotNull(jobExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/support/SimpleJobRepositoryTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/support/SimpleJobRepositoryTests.java index aa28437d34..fd35201fc5 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/support/SimpleJobRepositoryTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/support/SimpleJobRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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,11 +16,11 @@ package org.springframework.batch.core.repository.support; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.fail; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -31,8 +31,8 @@ import java.util.Date; 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.springframework.batch.core.BatchStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInstance; @@ -62,7 +62,7 @@ * @author Mahmoud Ben Hassine * */ -public class SimpleJobRepositoryTests { +class SimpleJobRepositoryTests { SimpleJobRepository jobRepository; @@ -92,8 +92,8 @@ public class SimpleJobRepositoryTests { JobExecution jobExecution; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { jobExecutionDao = mock(JobExecutionDao.class); jobInstanceDao = mock(JobInstanceDao.class); @@ -131,21 +131,15 @@ public void setUp() throws Exception { } @Test - public void testSaveOrUpdateInvalidJobExecution() { + void testSaveOrUpdateInvalidJobExecution() { // failure scenario - must have job ID JobExecution jobExecution = new JobExecution((JobInstance) null, (JobParameters) null); - try { - jobRepository.update(jobExecution); - fail(); - } - catch (Exception ex) { - // expected - } + assertThrows(Exception.class, () -> jobRepository.update(jobExecution)); } @Test - public void testUpdateValidJobExecution() throws Exception { + void testUpdateValidJobExecution() { JobExecution jobExecution = new JobExecution(new JobInstance(1L, job.getName()), 1L, jobParameters); // new execution - call update on job DAO @@ -155,22 +149,16 @@ public void testUpdateValidJobExecution() throws Exception { } @Test - public void testSaveOrUpdateStepExecutionException() { + void testSaveOrUpdateStepExecutionException() { StepExecution stepExecution = new StepExecution("stepName", null); // failure scenario -- no step id set. - try { - jobRepository.add(stepExecution); - fail(); - } - catch (Exception ex) { - // expected - } + assertThrows(Exception.class, () -> jobRepository.add(stepExecution)); } @Test - public void testSaveStepExecutionSetsLastUpdated() { + void testSaveStepExecutionSetsLastUpdated() { StepExecution stepExecution = new StepExecution("stepName", jobExecution); @@ -185,7 +173,7 @@ public void testSaveStepExecutionSetsLastUpdated() { } @Test - public void testSaveStepExecutions() { + void testSaveStepExecutions() { List stepExecutions = new ArrayList<>(); for (int i = 0; i < 3; i++) { StepExecution stepExecution = new StepExecution("stepName" + i, jobExecution); @@ -197,13 +185,13 @@ public void testSaveStepExecutions() { verify(ecDao).saveExecutionContexts(stepExecutions); } - @Test(expected = IllegalArgumentException.class) - public void testSaveNullStepExecutions() { - jobRepository.addAll(null); + @Test + void testSaveNullStepExecutions() { + assertThrows(IllegalArgumentException.class, () -> jobRepository.addAll(null)); } @Test - public void testUpdateStepExecutionSetsLastUpdated() { + void testUpdateStepExecutionSetsLastUpdated() { StepExecution stepExecution = new StepExecution("stepName", jobExecution); stepExecution.setId(2343L); @@ -219,7 +207,7 @@ public void testUpdateStepExecutionSetsLastUpdated() { } @Test - public void testInterrupted() { + void testInterrupted() { jobExecution.setStatus(BatchStatus.STOPPING); StepExecution stepExecution = new StepExecution("stepName", jobExecution); @@ -230,20 +218,20 @@ public void testInterrupted() { } @Test - public void testIsJobInstanceFalse() throws Exception { + void testIsJobInstanceFalse() { jobInstanceDao.getJobInstance("foo", new JobParameters()); assertFalse(jobRepository.isJobInstanceExists("foo", new JobParameters())); } @Test - public void testIsJobInstanceTrue() throws Exception { + void testIsJobInstanceTrue() { when(jobInstanceDao.getJobInstance("foo", new JobParameters())).thenReturn(jobInstance); jobInstanceDao.getJobInstance("foo", new JobParameters()); assertTrue(jobRepository.isJobInstanceExists("foo", new JobParameters())); } - @Test(expected = JobExecutionAlreadyRunningException.class) - public void testCreateJobExecutionAlreadyRunning() throws Exception { + @Test + void testCreateJobExecutionAlreadyRunning() { jobExecution.setStatus(BatchStatus.STARTED); jobExecution.setStartTime(new Date()); jobExecution.setEndTime(null); @@ -251,41 +239,43 @@ public void testCreateJobExecutionAlreadyRunning() throws Exception { when(jobInstanceDao.getJobInstance("foo", new JobParameters())).thenReturn(jobInstance); when(jobExecutionDao.findJobExecutions(jobInstance)).thenReturn(Arrays.asList(jobExecution)); - jobRepository.createJobExecution("foo", new JobParameters()); + assertThrows(JobExecutionAlreadyRunningException.class, + () -> jobRepository.createJobExecution("foo", new JobParameters())); } - @Test(expected = JobRestartException.class) - public void testCreateJobExecutionStatusUnknown() throws Exception { + @Test + void testCreateJobExecutionStatusUnknown() { jobExecution.setStatus(BatchStatus.UNKNOWN); jobExecution.setEndTime(new Date()); when(jobInstanceDao.getJobInstance("foo", new JobParameters())).thenReturn(jobInstance); when(jobExecutionDao.findJobExecutions(jobInstance)).thenReturn(Arrays.asList(jobExecution)); - jobRepository.createJobExecution("foo", new JobParameters()); + assertThrows(JobRestartException.class, () -> jobRepository.createJobExecution("foo", new JobParameters())); } - @Test(expected = JobInstanceAlreadyCompleteException.class) - public void testCreateJobExecutionAlreadyComplete() throws Exception { + @Test + void testCreateJobExecutionAlreadyComplete() { jobExecution.setStatus(BatchStatus.COMPLETED); jobExecution.setEndTime(new Date()); when(jobInstanceDao.getJobInstance("foo", new JobParameters())).thenReturn(jobInstance); when(jobExecutionDao.findJobExecutions(jobInstance)).thenReturn(Arrays.asList(jobExecution)); - jobRepository.createJobExecution("foo", new JobParameters()); + assertThrows(JobInstanceAlreadyCompleteException.class, + () -> jobRepository.createJobExecution("foo", new JobParameters())); } - @Test(expected = IllegalStateException.class) - public void testCreateJobExecutionInstanceWithoutExecutions() throws Exception { + @Test + void testCreateJobExecutionInstanceWithoutExecutions() { when(jobInstanceDao.getJobInstance("foo", new JobParameters())).thenReturn(jobInstance); when(jobExecutionDao.findJobExecutions(jobInstance)).thenReturn(Collections.emptyList()); - jobRepository.createJobExecution("foo", new JobParameters()); + assertThrows(IllegalStateException.class, () -> jobRepository.createJobExecution("foo", new JobParameters())); } @Test - public void testGetStepExecutionCount() { + void testGetStepExecutionCount() { // Given int expectedResult = 1; when(stepExecutionDao.countStepExecutions(jobInstance, "stepName")).thenReturn(expectedResult); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/resource/JdbcCursorItemReaderPreparedStatementIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/resource/JdbcCursorItemReaderPreparedStatementIntegrationTests.java index 21d5d23564..c3a1cbe11c 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/resource/JdbcCursorItemReaderPreparedStatementIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/resource/JdbcCursorItemReaderPreparedStatementIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2019 the original author or authors. + * Copyright 2008-2022 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. @@ -19,23 +19,20 @@ import java.util.List; import javax.sql.DataSource; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.database.JdbcCursorItemReader; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.ArgumentPreparedStatementSetter; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.transaction.annotation.Transactional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = "/org/springframework/batch/core/repository/dao/data-source-context.xml") +@SpringJUnitConfig(locations = "/org/springframework/batch/core/repository/dao/data-source-context.xml") public class JdbcCursorItemReaderPreparedStatementIntegrationTests { JdbcCursorItemReader itemReader; @@ -47,8 +44,8 @@ public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } - @Before - public void onSetUpInTransaction() throws Exception { + @BeforeEach + void onSetUpInTransaction() { itemReader = new JdbcCursorItemReader<>(); itemReader.setDataSource(dataSource); @@ -71,7 +68,7 @@ public void onSetUpInTransaction() throws Exception { @Transactional @Test - public void testRead() throws Exception { + void testRead() throws Exception { itemReader.open(new ExecutionContext()); Foo foo = itemReader.read(); assertEquals(2, foo.getId()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/resource/StepExecutionSimpleCompletionPolicyTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/resource/StepExecutionSimpleCompletionPolicyTests.java index 0ec4585030..fc33b3a5a6 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/resource/StepExecutionSimpleCompletionPolicyTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/resource/StepExecutionSimpleCompletionPolicyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2020 the original author or authors. + * Copyright 2006-2022 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,10 +16,8 @@ package org.springframework.batch.core.resource; -import java.io.IOException; - -import junit.framework.TestCase; - +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInstance; import org.springframework.batch.core.JobParameters; @@ -29,44 +27,42 @@ import org.springframework.batch.core.step.StepSupport; import org.springframework.batch.repeat.RepeatContext; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.springframework.test.util.AssertionErrors.assertTrue; + /** * Unit tests for {@link StepExecutionSimpleCompletionPolicy} * * @author Dave Syer */ -public class StepExecutionSimpleCompletionPolicyTests extends TestCase { +class StepExecutionSimpleCompletionPolicyTests { /** * Object under test */ - private StepExecutionSimpleCompletionPolicy policy = new StepExecutionSimpleCompletionPolicy(); - - private JobInstance jobInstance; - - private StepExecution stepExecution; + private final StepExecutionSimpleCompletionPolicy policy = new StepExecutionSimpleCompletionPolicy(); /** * mock step context */ - - @Override - protected void setUp() throws Exception { - + @BeforeEach + void setUp() { JobParameters jobParameters = new JobParametersBuilder().addLong("commit.interval", 2L).toJobParameters(); - jobInstance = new JobInstance(0L, "testJob"); + JobInstance jobInstance = new JobInstance(0L, "testJob"); JobExecution jobExecution = new JobExecution(jobInstance, jobParameters); Step step = new StepSupport("bar"); - stepExecution = jobExecution.createStepExecution(step.getName()); + StepExecution stepExecution = jobExecution.createStepExecution(step.getName()); policy.beforeStep(stepExecution); - } - public void testToString() throws Exception { + @Test + void testToString() { String msg = policy.toString(); - assertTrue("String does not contain chunk size", msg.indexOf("chunkSize=2") >= 0); + assertTrue("String does not contain chunk size", msg.contains("chunkSize=2")); } - public void testKeyName() throws Exception, IOException { + @Test + void testKeyName() { RepeatContext context = policy.start(null); assertFalse(policy.isComplete(context)); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/AsyncJobScopeIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/AsyncJobScopeIntegrationTests.java index 78b4848998..86e418508d 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/AsyncJobScopeIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/AsyncJobScopeIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2022 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. @@ -15,7 +15,7 @@ */ package org.springframework.batch.core.scope; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.List; @@ -24,10 +24,9 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.scope.context.JobContext; import org.springframework.batch.core.scope.context.JobSynchronizationManager; @@ -40,20 +39,18 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.core.task.TaskExecutor; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) +@SpringJUnitConfig public class AsyncJobScopeIntegrationTests implements BeanFactoryAware { - private Log logger = LogFactory.getLog(getClass()); + private final Log logger = LogFactory.getLog(getClass()); @Autowired @Qualifier("simple") private Collaborator simple; - private TaskExecutor taskExecutor = new SimpleAsyncTaskExecutor(); + private final TaskExecutor taskExecutor = new SimpleAsyncTaskExecutor(); private ListableBeanFactory beanFactory; @@ -64,21 +61,21 @@ public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = (ListableBeanFactory) beanFactory; } - @Before - public void countBeans() { + @BeforeEach + void countBeans() { JobSynchronizationManager.release(); beanCount = beanFactory.getBeanDefinitionCount(); } - @After - public void cleanUp() { + @AfterEach + void cleanUp() { JobSynchronizationManager.close(); // Check that all temporary bean definitions are cleaned up assertEquals(beanCount, beanFactory.getBeanDefinitionCount()); } @Test - public void testSimpleProperty() throws Exception { + void testSimpleProperty() { JobExecution jobExecution = new JobExecution(11L); ExecutionContext executionContext = jobExecution.getExecutionContext(); executionContext.put("foo", "bar"); @@ -87,7 +84,7 @@ public void testSimpleProperty() throws Exception { } @Test - public void testGetMultipleInMultipleThreads() throws Exception { + void testGetMultipleInMultipleThreads() throws Exception { List> tasks = new ArrayList<>(); @@ -123,7 +120,7 @@ public String call() throws Exception { } @Test - public void testGetSameInMultipleThreads() throws Exception { + void testGetSameInMultipleThreads() throws Exception { List> tasks = new ArrayList<>(); final JobExecution jobExecution = new JobExecution(11L); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/AsyncStepScopeIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/AsyncStepScopeIntegrationTests.java index 053386e15b..23f1b22eda 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/AsyncStepScopeIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/AsyncStepScopeIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2012 the original author or authors. + * Copyright 2008-2022 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. @@ -15,7 +15,7 @@ */ package org.springframework.batch.core.scope; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.List; @@ -24,10 +24,9 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.scope.context.StepContext; @@ -41,20 +40,18 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.core.task.TaskExecutor; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) +@SpringJUnitConfig public class AsyncStepScopeIntegrationTests implements BeanFactoryAware { - private Log logger = LogFactory.getLog(getClass()); + private final Log logger = LogFactory.getLog(getClass()); @Autowired @Qualifier("simple") private Collaborator simple; - private TaskExecutor taskExecutor = new SimpleAsyncTaskExecutor(); + private final TaskExecutor taskExecutor = new SimpleAsyncTaskExecutor(); private ListableBeanFactory beanFactory; @@ -65,21 +62,21 @@ public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = (ListableBeanFactory) beanFactory; } - @Before - public void countBeans() { + @BeforeEach + void countBeans() { StepSynchronizationManager.release(); beanCount = beanFactory.getBeanDefinitionCount(); } - @After - public void cleanUp() { + @AfterEach + void cleanUp() { StepSynchronizationManager.close(); // Check that all temporary bean definitions are cleaned up assertEquals(beanCount, beanFactory.getBeanDefinitionCount()); } @Test - public void testSimpleProperty() throws Exception { + void testSimpleProperty() { StepExecution stepExecution = new StepExecution("step", new JobExecution(0L), 123L); ExecutionContext executionContext = stepExecution.getExecutionContext(); executionContext.put("foo", "bar"); @@ -88,7 +85,7 @@ public void testSimpleProperty() throws Exception { } @Test - public void testGetMultipleInMultipleThreads() throws Exception { + void testGetMultipleInMultipleThreads() throws Exception { List> tasks = new ArrayList<>(); @@ -124,7 +121,7 @@ public String call() throws Exception { } @Test - public void testGetSameInMultipleThreads() throws Exception { + void testGetSameInMultipleThreads() throws Exception { List> tasks = new ArrayList<>(); final StepExecution stepExecution = new StepExecution("foo", new JobExecution(0L), 123L); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopeDestructionCallbackIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopeDestructionCallbackIntegrationTests.java index cf598aca76..348b77bc29 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopeDestructionCallbackIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopeDestructionCallbackIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013 the original author or authors. + * Copyright 2013-2022 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. @@ -15,24 +15,21 @@ */ package org.springframework.batch.core.scope; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.util.StringUtils; -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class JobScopeDestructionCallbackIntegrationTests { +@SpringJUnitConfig +class JobScopeDestructionCallbackIntegrationTests { @Autowired @Qualifier("proxied") @@ -50,29 +47,29 @@ public class JobScopeDestructionCallbackIntegrationTests { @Qualifier("foo") private Collaborator foo; - @Before - @After - public void resetMessage() throws Exception { + @BeforeEach + @AfterEach + void resetMessage() { TestDisposableCollaborator.message = "none"; TestAdvice.names.clear(); } @Test - public void testDisposableScopedProxy() throws Exception { + void testDisposableScopedProxy() { assertNotNull(proxied); proxied.execute(new JobExecution(1L)); assertEquals(1, StringUtils.countOccurrencesOf(TestDisposableCollaborator.message, "destroyed")); } @Test - public void testDisposableInnerScopedProxy() throws Exception { + void testDisposableInnerScopedProxy() { assertNotNull(nested); nested.execute(new JobExecution(1L)); assertEquals(1, StringUtils.countOccurrencesOf(TestDisposableCollaborator.message, "destroyed")); } @Test - public void testProxiedScopedProxy() throws Exception { + void testProxiedScopedProxy() { assertNotNull(nested); nested.execute(new JobExecution(1L)); assertEquals(4, TestAdvice.names.size()); @@ -81,7 +78,7 @@ public void testProxiedScopedProxy() throws Exception { } @Test - public void testRefScopedProxy() throws Exception { + void testRefScopedProxy() { assertNotNull(ref); ref.execute(new JobExecution(1L)); assertEquals(4, TestAdvice.names.size()); @@ -92,7 +89,7 @@ public void testRefScopedProxy() throws Exception { } @Test - public void testProxiedNormalBean() throws Exception { + void testProxiedNormalBean() { assertNotNull(nested); String name = foo.getName(); assertEquals(1, TestAdvice.names.size()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopeIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopeIntegrationTests.java index 2d5075b9d4..84e5ab9b9e 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopeIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopeIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013 the original author or authors. + * Copyright 2013-2022 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. @@ -15,27 +15,24 @@ */ package org.springframework.batch.core.scope; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.scope.context.JobSynchronizationManager; import org.springframework.batch.item.ExecutionContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class JobScopeIntegrationTests { +@SpringJUnitConfig +class JobScopeIntegrationTests { private static final String PROXY_TO_STRING_REGEX = "class .*\\$Proxy\\d+"; @@ -59,33 +56,33 @@ public class JobScopeIntegrationTests { @Qualifier("double") private Job doubleEnhanced; - @Before - @After - public void start() { + @BeforeEach + @AfterEach + void start() { JobSynchronizationManager.close(); TestJob.reset(); } @Test - public void testScopeCreation() throws Exception { + void testScopeCreation() { vanilla.execute(new JobExecution(11L)); assertNotNull(TestJob.getContext()); assertNull(JobSynchronizationManager.getContext()); } @Test - public void testScopedProxy() throws Exception { + void testScopedProxy() { proxied.execute(new JobExecution(11L)); assertTrue(TestJob.getContext().attributeNames().length > 0); String collaborator = (String) TestJob.getContext().getAttribute("collaborator"); assertNotNull(collaborator); assertEquals("bar", collaborator); - assertTrue("Scoped proxy not created", - ((String) TestJob.getContext().getAttribute("collaborator.class")).matches(PROXY_TO_STRING_REGEX)); + assertTrue(((String) TestJob.getContext().getAttribute("collaborator.class")).matches(PROXY_TO_STRING_REGEX), + "Scoped proxy not created"); } @Test - public void testNestedScopedProxy() throws Exception { + void testNestedScopedProxy() { nested.execute(new JobExecution(11L)); assertTrue(TestJob.getContext().attributeNames().length > 0); String collaborator = (String) TestJob.getContext().getAttribute("collaborator"); @@ -94,12 +91,12 @@ public void testNestedScopedProxy() throws Exception { String parent = (String) TestJob.getContext().getAttribute("parent"); assertNotNull(parent); assertEquals("bar", parent); - assertTrue("Scoped proxy not created", - ((String) TestJob.getContext().getAttribute("parent.class")).matches(PROXY_TO_STRING_REGEX)); + assertTrue(((String) TestJob.getContext().getAttribute("parent.class")).matches(PROXY_TO_STRING_REGEX), + "Scoped proxy not created"); } @Test - public void testExecutionContext() throws Exception { + void testExecutionContext() { JobExecution stepExecution = new JobExecution(11L); ExecutionContext executionContext = new ExecutionContext(); executionContext.put("name", "spam"); @@ -112,7 +109,7 @@ public void testExecutionContext() throws Exception { } @Test - public void testScopedProxyForReference() throws Exception { + void testScopedProxyForReference() { enhanced.execute(new JobExecution(11L)); assertTrue(TestJob.getContext().attributeNames().length > 0); String collaborator = (String) TestJob.getContext().getAttribute("collaborator"); @@ -121,7 +118,7 @@ public void testScopedProxyForReference() throws Exception { } @Test - public void testScopedProxyForSecondReference() throws Exception { + void testScopedProxyForSecondReference() { doubleEnhanced.execute(new JobExecution(11L)); assertTrue(TestJob.getContext().attributeNames().length > 0); String collaborator = (String) TestJob.getContext().getAttribute("collaborator"); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopeNestedIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopeNestedIntegrationTests.java index f60571b51d..c9073a2161 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopeNestedIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopeNestedIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013 the original author or authors. + * Copyright 2013-2022 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. @@ -15,20 +15,17 @@ */ package org.springframework.batch.core.scope; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.Job; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class JobScopeNestedIntegrationTests { +@SpringJUnitConfig +class JobScopeNestedIntegrationTests { @Autowired @Qualifier("proxied") @@ -39,7 +36,7 @@ public class JobScopeNestedIntegrationTests { private Collaborator parent; @Test - public void testNestedScopedProxy() throws Exception { + void testNestedScopedProxy() { assertNotNull(proxied); assertEquals("foo", parent.getName()); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopePlaceholderIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopePlaceholderIntegrationTests.java index a58e4c338c..7a18220450 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopePlaceholderIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopePlaceholderIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2022 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. @@ -15,12 +15,11 @@ */ package org.springframework.batch.core.scope; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.scope.context.JobSynchronizationManager; import org.springframework.batch.item.ExecutionContext; @@ -30,12 +29,10 @@ import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class JobScopePlaceholderIntegrationTests implements BeanFactoryAware { +@SpringJUnitConfig +class JobScopePlaceholderIntegrationTests implements BeanFactoryAware { @Autowired @Qualifier("simple") @@ -80,8 +77,8 @@ public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = (ListableBeanFactory) beanFactory; } - @Before - public void start() { + @BeforeEach + void start() { start("bar"); } @@ -101,15 +98,15 @@ private void start(String foo) { } - @After - public void stop() { + @AfterEach + void stop() { JobSynchronizationManager.close(); // Check that all temporary bean definitions are cleaned up assertEquals(beanCount, beanFactory.getBeanDefinitionCount()); } @Test - public void testSimpleProperty() throws Exception { + void testSimpleProperty() { assertEquals("bar", simple.getName()); // Once the job context is set up it should be baked into the proxies // so changing it now should have no effect @@ -118,12 +115,12 @@ public void testSimpleProperty() throws Exception { } @Test - public void testCompoundProperty() throws Exception { + void testCompoundProperty() { assertEquals("bar-bar", compound.getName()); } @Test - public void testCompoundPropertyTwice() throws Exception { + void testCompoundPropertyTwice() { assertEquals("bar-bar", compound.getName()); @@ -141,27 +138,27 @@ public void testCompoundPropertyTwice() throws Exception { } @Test - public void testParentByRef() throws Exception { + void testParentByRef() { assertEquals("bar", ref.getParent().getName()); } @Test - public void testParentByValue() throws Exception { + void testParentByValue() { assertEquals("bar", value.getParent().getName()); } @Test - public void testList() throws Exception { + void testList() { assertEquals("[bar]", list.getList().toString()); } @Test - public void testNested() throws Exception { + void testNested() { assertEquals("bar", nested.getParent().getName()); } @Test - public void testScopedRef() throws Exception { + void testScopedRef() { assertEquals("bar", scopedRef.getParent().getName()); stop(); start("spam"); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopeProxyTargetClassIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopeProxyTargetClassIntegrationTests.java index 082b2f4ca7..11e91fefb0 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopeProxyTargetClassIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopeProxyTargetClassIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2022 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. @@ -15,12 +15,11 @@ */ package org.springframework.batch.core.scope; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.scope.context.JobSynchronizationManager; import org.springframework.batch.item.ExecutionContext; @@ -30,11 +29,9 @@ import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) +@SpringJUnitConfig public class JobScopeProxyTargetClassIntegrationTests implements BeanFactoryAware { @Autowired @@ -52,8 +49,8 @@ public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = (ListableBeanFactory) beanFactory; } - @Before - public void start() { + @BeforeEach + void start() { JobSynchronizationManager.close(); jobExecution = new JobExecution(123L); @@ -68,15 +65,15 @@ public void start() { } - @After - public void cleanUp() { + @AfterEach + void cleanUp() { JobSynchronizationManager.close(); // Check that all temporary bean definitions are cleaned up assertEquals(beanCount, beanFactory.getBeanDefinitionCount()); } @Test - public void testSimpleProperty() throws Exception { + void testSimpleProperty() { assertEquals("bar", simple.getName()); // Once the job context is set up it should be baked into the proxies // so changing it now should have no effect diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopeStartupIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopeStartupIntegrationTests.java index 7ba25f7ec1..06ebb2cf80 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopeStartupIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopeStartupIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013 the original author or authors. + * Copyright 2013-2022 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. @@ -15,17 +15,14 @@ */ package org.springframework.batch.core.scope; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.junit.jupiter.api.Test; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class JobScopeStartupIntegrationTests { +@SpringJUnitConfig +class JobScopeStartupIntegrationTests { @Test - public void testScopedProxyDuringStartup() throws Exception { + void testScopedProxyDuringStartup() { } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopeTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopeTests.java index b45c0d4b96..fc67ba549c 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopeTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopeTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,18 +15,18 @@ */ package org.springframework.batch.core.scope; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.List; -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.batch.core.JobExecution; import org.springframework.batch.core.scope.context.JobContext; import org.springframework.batch.core.scope.context.JobSynchronizationManager; @@ -38,45 +38,38 @@ * @author Dave Syer * @author Jimmy Praet */ -public class JobScopeTests { +class JobScopeTests { - private JobScope scope = new JobScope(); + private final JobScope scope = new JobScope(); - private JobExecution jobExecution = new JobExecution(0L); + private final JobExecution jobExecution = new JobExecution(0L); private JobContext context; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { context = JobSynchronizationManager.register(jobExecution); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() { JobSynchronizationManager.release(); } @Test - public void testGetWithNoContext() throws Exception { + void testGetWithNoContext() { final String foo = "bar"; JobSynchronizationManager.release(); - try { - scope.get("foo", new ObjectFactory() { - @Override - public String getObject() throws BeansException { - return foo; - } - }); - fail("Expected IllegalStateException"); - } - catch (IllegalStateException e) { - // expected - } - + assertThrows(IllegalStateException.class, () -> scope.get("foo", new ObjectFactory() { + @Override + public String getObject() throws BeansException { + return foo; + } + })); } @Test - public void testGetWithNothingAlreadyThere() { + void testGetWithNothingAlreadyThere() { final String foo = "bar"; Object value = scope.get("foo", new ObjectFactory() { @Override @@ -89,7 +82,7 @@ public String getObject() throws BeansException { } @Test - public void testGetWithSomethingAlreadyThere() { + void testGetWithSomethingAlreadyThere() { context.setAttribute("foo", "bar"); Object value = scope.get("foo", new ObjectFactory() { @Override @@ -102,13 +95,13 @@ public String getObject() throws BeansException { } @Test - public void testGetConversationId() { + void testGetConversationId() { String id = scope.getConversationId(); assertNotNull(id); } @Test - public void testRegisterDestructionCallback() { + void testRegisterDestructionCallback() { final List list = new ArrayList<>(); context.setAttribute("foo", "bar"); scope.registerDestructionCallback("foo", new Runnable() { @@ -125,7 +118,7 @@ public void run() { } @Test - public void testRegisterAnotherDestructionCallback() { + void testRegisterAnotherDestructionCallback() { final List list = new ArrayList<>(); context.setAttribute("foo", "bar"); scope.registerDestructionCallback("foo", new Runnable() { @@ -148,22 +141,21 @@ public void run() { } @Test - public void testRemove() { + void testRemove() { context.setAttribute("foo", "bar"); scope.remove("foo"); assertFalse(context.hasAttribute("foo")); } @Test - public void testOrder() throws Exception { + void testOrder() { assertEquals(Integer.MAX_VALUE, scope.getOrder()); scope.setOrder(11); assertEquals(11, scope.getOrder()); } @Test - @SuppressWarnings("resource") - public void testName() throws Exception { + void testName() { scope.setName("foo"); StaticApplicationContext beanFactory = new StaticApplicationContext(); scope.postProcessBeanFactory(beanFactory.getDefaultListableBeanFactory()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeClassIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeClassIntegrationTests.java index ce053d333a..d9e0f7723e 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeClassIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeClassIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2012 the original author or authors. + * Copyright 2010-2022 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. @@ -15,13 +15,12 @@ */ package org.springframework.batch.core.scope; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; +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.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.scope.context.StepSynchronizationManager; @@ -32,12 +31,10 @@ import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -@Ignore // Maybe one day support class replacement? +@SpringJUnitConfig +@Disabled // Maybe one day support class replacement? public class StepScopeClassIntegrationTests implements BeanFactoryAware { @Autowired @@ -48,8 +45,6 @@ public class StepScopeClassIntegrationTests implements BeanFactoryAware { @Qualifier("nested") private Collaborator nested; - private StepExecution stepExecution; - private ListableBeanFactory beanFactory; private int beanCount; @@ -59,15 +54,15 @@ public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = (ListableBeanFactory) beanFactory; } - @Before - public void start() { + @BeforeEach + void start() { start("bar"); } private void start(String foo) { StepSynchronizationManager.close(); - stepExecution = new StepExecution("foo", new JobExecution(11L), 123L); + StepExecution stepExecution = new StepExecution("foo", new JobExecution(11L), 123L); ExecutionContext executionContext = new ExecutionContext(); executionContext.put("foo", foo); @@ -80,20 +75,20 @@ private void start(String foo) { } - @After - public void stop() { + @AfterEach + void stop() { StepSynchronizationManager.close(); // Check that all temporary bean definitions are cleaned up assertEquals(beanCount, beanFactory.getBeanDefinitionCount()); } @Test - public void testSimpleValue() throws Exception { + void testSimpleValue() { assertEquals("foo", value.getName()); } @Test - public void testNested() throws Exception { + void testNested() { assertEquals("bar", nested.getParent().getName()); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeDestructionCallbackIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeDestructionCallbackIntegrationTests.java index 58e261027e..a1d262de18 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeDestructionCallbackIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeDestructionCallbackIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2010 the original author or authors. + * Copyright 2008-2022 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. @@ -15,25 +15,22 @@ */ package org.springframework.batch.core.scope; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.Step; import org.springframework.batch.core.StepExecution; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.util.StringUtils; -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class StepScopeDestructionCallbackIntegrationTests { +@SpringJUnitConfig +class StepScopeDestructionCallbackIntegrationTests { @Autowired @Qualifier("proxied") @@ -51,29 +48,29 @@ public class StepScopeDestructionCallbackIntegrationTests { @Qualifier("foo") private Collaborator foo; - @Before - @After - public void resetMessage() throws Exception { + @BeforeEach + @AfterEach + void resetMessage() { TestDisposableCollaborator.message = "none"; TestAdvice.names.clear(); } @Test - public void testDisposableScopedProxy() throws Exception { + void testDisposableScopedProxy() throws Exception { assertNotNull(proxied); proxied.execute(new StepExecution("step", new JobExecution(0L), 1L)); assertEquals(1, StringUtils.countOccurrencesOf(TestDisposableCollaborator.message, "destroyed")); } @Test - public void testDisposableInnerScopedProxy() throws Exception { + void testDisposableInnerScopedProxy() throws Exception { assertNotNull(nested); nested.execute(new StepExecution("step", new JobExecution(0L), 1L)); assertEquals(1, StringUtils.countOccurrencesOf(TestDisposableCollaborator.message, "destroyed")); } @Test - public void testProxiedScopedProxy() throws Exception { + void testProxiedScopedProxy() throws Exception { assertNotNull(nested); nested.execute(new StepExecution("step", new JobExecution(0L), 1L)); assertEquals(4, TestAdvice.names.size()); @@ -82,7 +79,7 @@ public void testProxiedScopedProxy() throws Exception { } @Test - public void testRefScopedProxy() throws Exception { + void testRefScopedProxy() throws Exception { assertNotNull(ref); ref.execute(new StepExecution("step", new JobExecution(0L), 1L)); assertEquals(4, TestAdvice.names.size()); @@ -93,7 +90,7 @@ public void testRefScopedProxy() throws Exception { } @Test - public void testProxiedNormalBean() throws Exception { + void testProxiedNormalBean() { assertNotNull(nested); String name = foo.getName(); assertEquals(1, TestAdvice.names.size()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeIntegrationTests.java index a0ea85f02b..6e7e759519 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2013 the original author or authors. + * Copyright 2008-2022 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. @@ -15,15 +15,14 @@ */ package org.springframework.batch.core.scope; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.Step; import org.springframework.batch.core.StepExecution; @@ -31,12 +30,10 @@ import org.springframework.batch.item.ExecutionContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class StepScopeIntegrationTests { +@SpringJUnitConfig +class StepScopeIntegrationTests { private static final String PROXY_TO_STRING_REGEX = "class .*\\$Proxy\\d+"; @@ -60,33 +57,33 @@ public class StepScopeIntegrationTests { @Qualifier("double") private Step doubleEnhanced; - @Before - @After - public void start() { + @BeforeEach + @AfterEach + void start() { StepSynchronizationManager.close(); TestStep.reset(); } @Test - public void testScopeCreation() throws Exception { + void testScopeCreation() throws Exception { vanilla.execute(new StepExecution("foo", new JobExecution(11L), 12L)); assertNotNull(TestStep.getContext()); assertNull(StepSynchronizationManager.getContext()); } @Test - public void testScopedProxy() throws Exception { + void testScopedProxy() throws Exception { proxied.execute(new StepExecution("foo", new JobExecution(11L), 31L)); assertTrue(TestStep.getContext().attributeNames().length > 0); String collaborator = (String) TestStep.getContext().getAttribute("collaborator"); assertNotNull(collaborator); assertEquals("bar", collaborator); - assertTrue("Scoped proxy not created", - ((String) TestStep.getContext().getAttribute("collaborator.class")).matches(PROXY_TO_STRING_REGEX)); + assertTrue(((String) TestStep.getContext().getAttribute("collaborator.class")).matches(PROXY_TO_STRING_REGEX), + "Scoped proxy not created"); } @Test - public void testNestedScopedProxy() throws Exception { + void testNestedScopedProxy() throws Exception { nested.execute(new StepExecution("foo", new JobExecution(11L), 31L)); assertTrue(TestStep.getContext().attributeNames().length > 0); String collaborator = (String) TestStep.getContext().getAttribute("collaborator"); @@ -95,12 +92,12 @@ public void testNestedScopedProxy() throws Exception { String parent = (String) TestStep.getContext().getAttribute("parent"); assertNotNull(parent); assertEquals("bar", parent); - assertTrue("Scoped proxy not created", - ((String) TestStep.getContext().getAttribute("parent.class")).matches(PROXY_TO_STRING_REGEX)); + assertTrue(((String) TestStep.getContext().getAttribute("parent.class")).matches(PROXY_TO_STRING_REGEX), + "Scoped proxy not created"); } @Test - public void testExecutionContext() throws Exception { + void testExecutionContext() throws Exception { StepExecution stepExecution = new StepExecution("foo", new JobExecution(11L), 1L); ExecutionContext executionContext = new ExecutionContext(); executionContext.put("name", "spam"); @@ -113,7 +110,7 @@ public void testExecutionContext() throws Exception { } @Test - public void testScopedProxyForReference() throws Exception { + void testScopedProxyForReference() throws Exception { enhanced.execute(new StepExecution("foo", new JobExecution(11L), 123L)); assertTrue(TestStep.getContext().attributeNames().length > 0); String collaborator = (String) TestStep.getContext().getAttribute("collaborator"); @@ -122,7 +119,7 @@ public void testScopedProxyForReference() throws Exception { } @Test - public void testScopedProxyForSecondReference() throws Exception { + void testScopedProxyForSecondReference() throws Exception { doubleEnhanced.execute(new StepExecution("foo", new JobExecution(11L), 321L)); assertTrue(TestStep.getContext().attributeNames().length > 0); String collaborator = (String) TestStep.getContext().getAttribute("collaborator"); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeNestedIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeNestedIntegrationTests.java index 333c8188db..176e071e47 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeNestedIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeNestedIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008 the original author or authors. + * Copyright 2008-2022 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. @@ -15,20 +15,17 @@ */ package org.springframework.batch.core.scope; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.Step; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class StepScopeNestedIntegrationTests { +@SpringJUnitConfig +class StepScopeNestedIntegrationTests { @Autowired @Qualifier("proxied") @@ -39,7 +36,7 @@ public class StepScopeNestedIntegrationTests { private Collaborator parent; @Test - public void testNestedScopedProxy() throws Exception { + void testNestedScopedProxy() { assertNotNull(proxied); assertEquals("foo", parent.getName()); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopePerformanceTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopePerformanceTests.java index 18b3a8283a..2212eefa16 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopePerformanceTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopePerformanceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2014 the original author or authors. + * Copyright 2009-2022 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. @@ -17,10 +17,9 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.scope.context.StepSynchronizationManager; @@ -29,15 +28,13 @@ import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.util.StopWatch; -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) +@SpringJUnitConfig public class StepScopePerformanceTests implements ApplicationContextAware { - private Log logger = LogFactory.getLog(getClass()); + private final Log logger = LogFactory.getLog(getClass()); private ApplicationContext applicationContext; @@ -47,27 +44,27 @@ public void setApplicationContext(ApplicationContext applicationContext) throws } - @Before - public void start() throws Exception { + @BeforeEach + void start() throws Exception { int count = doTest("vanilla", "warmup"); logger.info("Item count: " + count); StepSynchronizationManager.close(); StepSynchronizationManager.register(new StepExecution("step", new JobExecution(0L), 1L)); } - @After - public void cleanup() { + @AfterEach + void cleanup() { StepSynchronizationManager.close(); } @Test - public void testVanilla() throws Exception { + void testVanilla() throws Exception { int count = doTest("vanilla", "vanilla"); logger.info("Item count: " + count); } @Test - public void testProxied() throws Exception { + void testProxied() throws Exception { int count = doTest("proxied", "proxied"); logger.info("Item count: " + count); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopePlaceholderIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopePlaceholderIntegrationTests.java index ffc9458d14..95ee5e44ee 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopePlaceholderIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopePlaceholderIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2012 the original author or authors. + * Copyright 2008-2022 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. @@ -15,12 +15,11 @@ */ package org.springframework.batch.core.scope; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.scope.context.StepSynchronizationManager; @@ -31,11 +30,9 @@ import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) +@SpringJUnitConfig public class StepScopePlaceholderIntegrationTests implements BeanFactoryAware { @Autowired @@ -81,8 +78,8 @@ public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = (ListableBeanFactory) beanFactory; } - @Before - public void start() { + @BeforeEach + void start() { start("bar"); } @@ -102,15 +99,15 @@ private void start(String foo) { } - @After - public void stop() { + @AfterEach + void stop() { StepSynchronizationManager.close(); // Check that all temporary bean definitions are cleaned up assertEquals(beanCount, beanFactory.getBeanDefinitionCount()); } @Test - public void testSimpleProperty() throws Exception { + void testSimpleProperty() { assertEquals("bar", simple.getName()); // Once the step context is set up it should be baked into the proxies // so changing it now should have no effect @@ -119,12 +116,12 @@ public void testSimpleProperty() throws Exception { } @Test - public void testCompoundProperty() throws Exception { + void testCompoundProperty() { assertEquals("bar-bar", compound.getName()); } @Test - public void testCompoundPropertyTwice() throws Exception { + void testCompoundPropertyTwice() { assertEquals("bar-bar", compound.getName()); @@ -142,27 +139,27 @@ public void testCompoundPropertyTwice() throws Exception { } @Test - public void testParentByRef() throws Exception { + void testParentByRef() { assertEquals("bar", ref.getParent().getName()); } @Test - public void testParentByValue() throws Exception { + void testParentByValue() { assertEquals("bar", value.getParent().getName()); } @Test - public void testList() throws Exception { + void testList() { assertEquals("[bar]", list.getList().toString()); } @Test - public void testNested() throws Exception { + void testNested() { assertEquals("bar", nested.getParent().getName()); } @Test - public void testScopedRef() throws Exception { + void testScopedRef() { assertEquals("bar", scopedRef.getParent().getName()); stop(); start("spam"); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeProxyTargetClassIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeProxyTargetClassIntegrationTests.java index defa915845..f63a84ae26 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeProxyTargetClassIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeProxyTargetClassIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2012 the original author or authors. + * Copyright 2009-2022 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. @@ -15,12 +15,11 @@ */ package org.springframework.batch.core.scope; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.scope.context.StepSynchronizationManager; @@ -31,11 +30,9 @@ import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) +@SpringJUnitConfig public class StepScopeProxyTargetClassIntegrationTests implements BeanFactoryAware { @Autowired @@ -53,8 +50,8 @@ public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = (ListableBeanFactory) beanFactory; } - @Before - public void start() { + @BeforeEach + void start() { StepSynchronizationManager.close(); stepExecution = new StepExecution("foo", new JobExecution(11L), 123L); @@ -69,15 +66,15 @@ public void start() { } - @After - public void cleanUp() { + @AfterEach + void cleanUp() { StepSynchronizationManager.close(); // Check that all temporary bean definitions are cleaned up assertEquals(beanCount, beanFactory.getBeanDefinitionCount()); } @Test - public void testSimpleProperty() throws Exception { + void testSimpleProperty() { assertEquals("bar", simple.getName()); // Once the step context is set up it should be baked into the proxies // so changing it now should have no effect diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeProxyTargetClassOverrideIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeProxyTargetClassOverrideIntegrationTests.java index bd588f9c0a..e624f67cca 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeProxyTargetClassOverrideIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeProxyTargetClassOverrideIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2022 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. @@ -15,14 +15,13 @@ */ package org.springframework.batch.core.scope; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.aop.support.AopUtils; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.Step; @@ -35,11 +34,9 @@ import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) +@SpringJUnitConfig public class StepScopeProxyTargetClassOverrideIntegrationTests implements BeanFactoryAware { private static final String JDK_PROXY_TO_STRING_REGEX = "class .*\\$Proxy\\d+"; @@ -70,8 +67,6 @@ public class StepScopeProxyTargetClassOverrideIntegrationTests implements BeanFa @Qualifier("nestedProxyTargetClassFalse") private Step nestedProxyTargetClassFalse; - private StepExecution stepExecution; - private ListableBeanFactory beanFactory; private int beanCount; @@ -81,12 +76,12 @@ public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = (ListableBeanFactory) beanFactory; } - @Before - public void start() { + @BeforeEach + void start() { StepSynchronizationManager.close(); TestStep.reset(); - stepExecution = new StepExecution("foo", new JobExecution(11L), 123L); + StepExecution stepExecution = new StepExecution("foo", new JobExecution(11L), 123L); ExecutionContext executionContext = new ExecutionContext(); executionContext.put("foo", "bar"); @@ -98,33 +93,33 @@ public void start() { } - @After - public void cleanUp() { + @AfterEach + void cleanUp() { StepSynchronizationManager.close(); // Check that all temporary bean definitions are cleaned up assertEquals(beanCount, beanFactory.getBeanDefinitionCount()); } @Test - public void testSimple() throws Exception { + void testSimple() { assertTrue(AopUtils.isCglibProxy(simple)); assertEquals("bar", simple.getName()); } @Test - public void testSimpleProxyTargetClassTrue() throws Exception { + void testSimpleProxyTargetClassTrue() { assertTrue(AopUtils.isCglibProxy(simpleProxyTargetClassTrue)); assertEquals("bar", simpleProxyTargetClassTrue.getName()); } @Test - public void testSimpleProxyTargetClassFalse() throws Exception { + void testSimpleProxyTargetClassFalse() { assertTrue(AopUtils.isJdkDynamicProxy(simpleProxyTargetClassFalse)); assertEquals("bar", simpleProxyTargetClassFalse.getName()); } @Test - public void testNested() throws Exception { + void testNested() throws Exception { nested.execute(new StepExecution("foo", new JobExecution(11L), 31L)); assertTrue(TestStep.getContext().attributeNames().length > 0); String collaborator = (String) TestStep.getContext().getAttribute("collaborator"); @@ -133,26 +128,26 @@ public void testNested() throws Exception { String parent = (String) TestStep.getContext().getAttribute("parent"); assertNotNull(parent); assertEquals("bar", parent); - assertTrue("Scoped proxy not created", - ((String) TestStep.getContext().getAttribute("parent.class")).matches(CGLIB_PROXY_TO_STRING_REGEX)); + assertTrue(((String) TestStep.getContext().getAttribute("parent.class")).matches(CGLIB_PROXY_TO_STRING_REGEX), + "Scoped proxy not created"); } @Test - public void testNestedProxyTargetClassTrue() throws Exception { + void testNestedProxyTargetClassTrue() throws Exception { nestedProxyTargetClassTrue.execute(new StepExecution("foo", new JobExecution(11L), 31L)); String parent = (String) TestStep.getContext().getAttribute("parent"); assertEquals("bar", parent); - assertTrue("Scoped proxy not created", - ((String) TestStep.getContext().getAttribute("parent.class")).matches(CGLIB_PROXY_TO_STRING_REGEX)); + assertTrue(((String) TestStep.getContext().getAttribute("parent.class")).matches(CGLIB_PROXY_TO_STRING_REGEX), + "Scoped proxy not created"); } @Test - public void testNestedProxyTargetClassFalse() throws Exception { + void testNestedProxyTargetClassFalse() throws Exception { nestedProxyTargetClassFalse.execute(new StepExecution("foo", new JobExecution(11L), 31L)); String parent = (String) TestStep.getContext().getAttribute("parent"); assertEquals("bar", parent); - assertTrue("Scoped proxy not created", - ((String) TestStep.getContext().getAttribute("parent.class")).matches(JDK_PROXY_TO_STRING_REGEX)); + assertTrue(((String) TestStep.getContext().getAttribute("parent.class")).matches(JDK_PROXY_TO_STRING_REGEX), + "Scoped proxy not created"); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeStartupIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeStartupIntegrationTests.java index a03e334c9b..74afdb321d 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeStartupIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeStartupIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008 the original author or authors. + * Copyright 2008-2022 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. @@ -15,17 +15,14 @@ */ package org.springframework.batch.core.scope; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.junit.jupiter.api.Test; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class StepScopeStartupIntegrationTests { +@SpringJUnitConfig +class StepScopeStartupIntegrationTests { @Test - public void testScopedProxyDuringStartup() throws Exception { + void testScopedProxyDuringStartup() { } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeTests.java index b4cbfecf7b..4e9ec22c79 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2013 the original author or authors. + * Copyright 2006-2022 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. @@ -15,19 +15,19 @@ */ package org.springframework.batch.core.scope; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.List; -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.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.scope.context.StepContext; @@ -40,46 +40,39 @@ * @author Dave Syer * */ -public class StepScopeTests { +class StepScopeTests { - private StepScope scope = new StepScope(); + private final StepScope scope = new StepScope(); - private StepExecution stepExecution = new StepExecution("foo", new JobExecution(0L), 123L); + private final StepExecution stepExecution = new StepExecution("foo", new JobExecution(0L), 123L); private StepContext context; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { StepSynchronizationManager.release(); context = StepSynchronizationManager.register(stepExecution); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() { StepSynchronizationManager.close(); } @Test - public void testGetWithNoContext() throws Exception { + void testGetWithNoContext() { final String foo = "bar"; StepSynchronizationManager.close(); - try { - scope.get("foo", new ObjectFactory() { - @Override - public Object getObject() throws BeansException { - return foo; - } - }); - fail("Expected IllegalStateException"); - } - catch (IllegalStateException e) { - // expected - } - + assertThrows(IllegalStateException.class, () -> scope.get("foo", new ObjectFactory() { + @Override + public Object getObject() throws BeansException { + return foo; + } + })); } @Test - public void testGetWithNothingAlreadyThere() { + void testGetWithNothingAlreadyThere() { final String foo = "bar"; Object value = scope.get("foo", new ObjectFactory() { @Override @@ -92,7 +85,7 @@ public Object getObject() throws BeansException { } @Test - public void testGetWithSomethingAlreadyThere() { + void testGetWithSomethingAlreadyThere() { context.setAttribute("foo", "bar"); Object value = scope.get("foo", new ObjectFactory() { @Override @@ -105,7 +98,7 @@ public Object getObject() throws BeansException { } @Test - public void testGetWithSomethingAlreadyInParentContext() { + void testGetWithSomethingAlreadyInParentContext() { context.setAttribute("foo", "bar"); StepContext context = StepSynchronizationManager.register(new StepExecution("bar", new JobExecution(0L))); Object value = scope.get("foo", new ObjectFactory() { @@ -121,20 +114,20 @@ public Object getObject() throws BeansException { } @Test - public void testParentContextWithSameStepExecution() { + void testParentContextWithSameStepExecution() { context.setAttribute("foo", "bar"); StepContext other = StepSynchronizationManager.register(stepExecution); assertSame(other, context); } @Test - public void testGetConversationId() { + void testGetConversationId() { String id = scope.getConversationId(); assertNotNull(id); } @Test - public void testRegisterDestructionCallback() { + void testRegisterDestructionCallback() { final List list = new ArrayList<>(); context.setAttribute("foo", "bar"); scope.registerDestructionCallback("foo", new Runnable() { @@ -151,7 +144,7 @@ public void run() { } @Test - public void testRegisterAnotherDestructionCallback() { + void testRegisterAnotherDestructionCallback() { final List list = new ArrayList<>(); context.setAttribute("foo", "bar"); scope.registerDestructionCallback("foo", new Runnable() { @@ -174,22 +167,21 @@ public void run() { } @Test - public void testRemove() { + void testRemove() { context.setAttribute("foo", "bar"); scope.remove("foo"); assertFalse(context.hasAttribute("foo")); } @Test - public void testOrder() throws Exception { + void testOrder() { assertEquals(Integer.MAX_VALUE, scope.getOrder()); scope.setOrder(11); assertEquals(11, scope.getOrder()); } - @SuppressWarnings("resource") @Test - public void testName() throws Exception { + void testName() { scope.setName("foo"); StaticApplicationContext beanFactory = new StaticApplicationContext(); scope.postProcessBeanFactory(beanFactory.getDefaultListableBeanFactory()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/ChunkContextTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/ChunkContextTests.java index c1edcc22de..eda53366c1 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/ChunkContextTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/ChunkContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,14 +15,14 @@ */ package org.springframework.batch.core.scope.context; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Collections; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInstance; import org.springframework.batch.core.JobParameter; @@ -33,31 +33,32 @@ * @author Mahmoud Ben Hassine * */ -public class ChunkContextTests { +class ChunkContextTests { - private ChunkContext context = new ChunkContext(new StepContext(new JobExecution(new JobInstance(0L, "job"), 1L, - new JobParameters(Collections.singletonMap("foo", new JobParameter("bar")))).createStepExecution("foo"))); + private final ChunkContext context = new ChunkContext(new StepContext(new JobExecution(new JobInstance(0L, "job"), + 1L, new JobParameters(Collections.singletonMap("foo", new JobParameter("bar")))) + .createStepExecution("foo"))); @Test - public void testGetStepContext() { + void testGetStepContext() { StepContext stepContext = context.getStepContext(); assertNotNull(stepContext); assertEquals("bar", context.getStepContext().getJobParameters().get("foo")); } @Test - public void testIsComplete() { + void testIsComplete() { assertFalse(context.isComplete()); context.setComplete(); assertTrue(context.isComplete()); } @Test - public void testToString() { + void testToString() { String value = context.toString(); - assertTrue("Wrong toString: " + value, value.contains("stepContext=")); - assertTrue("Wrong toString: " + value, value.contains("complete=false")); - assertTrue("Wrong toString: " + value, value.contains("attributes=[]")); + assertTrue(value.contains("stepContext="), "Wrong toString: " + value); + assertTrue(value.contains("complete=false"), "Wrong toString: " + value); + assertTrue(value.contains("attributes=[]"), "Wrong toString: " + value); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/InternalBeanStepScopeIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/InternalBeanStepScopeIntegrationTests.java index 82761453a6..97134be952 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/InternalBeanStepScopeIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/InternalBeanStepScopeIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2022 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. @@ -15,7 +15,7 @@ */ package org.springframework.batch.core.scope.context; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -24,15 +24,15 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author mminella */ -public class InternalBeanStepScopeIntegrationTests { +class InternalBeanStepScopeIntegrationTests { @Test - public void testCommitIntervalJobParameter() throws Exception { + void testCommitIntervalJobParameter() throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext( "/org/springframework/batch/core/scope/context/CommitIntervalJobParameter-context.xml"); Job job = context.getBean(Job.class); @@ -47,7 +47,7 @@ public void testCommitIntervalJobParameter() throws Exception { } @Test - public void testInvalidCommitIntervalJobParameter() throws Exception { + void testInvalidCommitIntervalJobParameter() throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext( "/org/springframework/batch/core/scope/context/CommitIntervalJobParameter-context.xml"); Job job = context.getBean(Job.class); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/JobContextTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/JobContextTests.java index 51bc756991..430377f20a 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/JobContextTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/JobContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,17 +15,17 @@ */ package org.springframework.batch.core.scope.context; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; 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.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInstance; import org.springframework.batch.core.JobParameters; @@ -36,7 +36,7 @@ * @author Dave Syer * @author Jimmy Praet */ -public class JobContextTests { +class JobContextTests { private List list; @@ -44,8 +44,8 @@ public class JobContextTests { private JobContext context; - @Before - public void setUp() { + @BeforeEach + void setUp() { jobExecution = new JobExecution(1L); JobInstance jobInstance = new JobInstance(2L, "job"); jobExecution.setJobInstance(jobInstance); @@ -54,39 +54,33 @@ public void setUp() { } @Test - public void testGetJobExecution() { + void testGetJobExecution() { context = new JobContext(jobExecution); assertNotNull(context.getJobExecution()); } @Test - public void testNullJobExecution() { - try { - context = new JobContext(null); - fail("Expected IllegalArgumentException"); - } - catch (IllegalArgumentException e) { - // expected - } + void testNullJobExecution() { + assertThrows(IllegalArgumentException.class, () -> new JobContext(null)); } @Test - public void testEqualsSelf() { + void testEqualsSelf() { assertEquals(context, context); } @Test - public void testNotEqualsNull() { + void testNotEqualsNull() { assertFalse(context.equals(null)); } @Test - public void testEqualsContextWithSameJobExecution() { + void testEqualsContextWithSameJobExecution() { assertEquals(new JobContext(jobExecution), context); } @Test - public void testDestructionCallbackSunnyDay() throws Exception { + void testDestructionCallbackSunnyDay() { context.setAttribute("foo", "FOO"); context.registerDestructionCallback("foo", new Runnable() { @Override @@ -100,7 +94,7 @@ public void run() { } @Test - public void testDestructionCallbackMissingAttribute() throws Exception { + void testDestructionCallbackMissingAttribute() { context.registerDestructionCallback("foo", new Runnable() { @Override public void run() { @@ -114,7 +108,7 @@ public void run() { } @Test - public void testDestructionCallbackWithException() throws Exception { + void testDestructionCallbackWithException() { context.setAttribute("foo", "FOO"); context.setAttribute("bar", "BAR"); context.registerDestructionCallback("bar", new Runnable() { @@ -131,14 +125,9 @@ public void run() { throw new RuntimeException("fail!"); } }); - try { - context.close(); - fail("Expected RuntimeException"); - } - catch (RuntimeException e) { - // We don't care which one was thrown... - assertEquals("fail!", e.getMessage()); - } + Exception exception = assertThrows(RuntimeException.class, () -> context.close()); + // We don't care which one was thrown... + assertEquals("fail!", exception.getMessage()); // ...but we do care that both were executed: assertEquals(2, list.size()); assertTrue(list.contains("bar")); @@ -146,25 +135,25 @@ public void run() { } @Test - public void testJobName() throws Exception { + void testJobName() { assertEquals("job", context.getJobName()); } @Test - public void testJobExecutionContext() throws Exception { + void testJobExecutionContext() { ExecutionContext executionContext = jobExecution.getExecutionContext(); executionContext.put("foo", "bar"); assertEquals("bar", context.getJobExecutionContext().get("foo")); } @Test - public void testSystemProperties() throws Exception { + void testSystemProperties() { System.setProperty("foo", "bar"); assertEquals("bar", context.getSystemProperties().getProperty("foo")); } @Test - public void testJobParameters() throws Exception { + void testJobParameters() { JobParameters jobParameters = new JobParametersBuilder().addString("foo", "bar").toJobParameters(); JobInstance jobInstance = new JobInstance(0L, "foo"); jobExecution = new JobExecution(5L, jobParameters); @@ -174,14 +163,14 @@ public void testJobParameters() throws Exception { } @Test - public void testContextId() throws Exception { + void testContextId() { assertEquals("jobExecution#1", context.getId()); } - @Test(expected = IllegalStateException.class) - public void testIllegalContextId() throws Exception { + @Test + void testIllegalContextId() { context = new JobContext(new JobExecution((Long) null)); - context.getId(); + assertThrows(IllegalStateException.class, context::getId); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/JobSynchronizationManagerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/JobSynchronizationManagerTests.java index 90c0a2a562..6284828350 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/JobSynchronizationManagerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/JobSynchronizationManagerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013 the original author or authors. + * Copyright 2013-2022 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. @@ -15,9 +15,9 @@ */ package org.springframework.batch.core.scope.context; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import java.util.ArrayList; import java.util.List; @@ -27,9 +27,9 @@ import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; -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.batch.core.JobExecution; /** @@ -37,27 +37,27 @@ * * @author Jimmy Praet */ -public class JobSynchronizationManagerTests { +class JobSynchronizationManagerTests { - private JobExecution jobExecution = new JobExecution(0L); + private final JobExecution jobExecution = new JobExecution(0L); - @Before - @After - public void start() { + @BeforeEach + @AfterEach + void start() { while (JobSynchronizationManager.getContext() != null) { JobSynchronizationManager.close(); } } @Test - public void testGetContext() { + void testGetContext() { assertNull(JobSynchronizationManager.getContext()); JobSynchronizationManager.register(jobExecution); assertNotNull(JobSynchronizationManager.getContext()); } @Test - public void testClose() throws Exception { + void testClose() { final List list = new ArrayList<>(); JobContext context = JobSynchronizationManager.register(jobExecution); context.registerDestructionCallback("foo", new Runnable() { @@ -72,7 +72,7 @@ public void run() { } @Test - public void testMultithreaded() throws Exception { + void testMultithreaded() throws Exception { JobContext context = JobSynchronizationManager.register(jobExecution); ExecutorService executorService = Executors.newFixedThreadPool(2); FutureTask task = new FutureTask<>(new Callable() { @@ -97,7 +97,7 @@ public JobContext call() throws Exception { } @Test - public void testRelease() { + void testRelease() { JobContext context = JobSynchronizationManager.register(jobExecution); final List list = new ArrayList<>(); context.registerDestructionCallback("foo", new Runnable() { @@ -113,14 +113,14 @@ public void run() { } @Test - public void testRegisterNull() { + void testRegisterNull() { assertNull(JobSynchronizationManager.getContext()); JobSynchronizationManager.register(null); assertNull(JobSynchronizationManager.getContext()); } @Test - public void testRegisterTwice() { + void testRegisterTwice() { JobSynchronizationManager.register(jobExecution); JobSynchronizationManager.register(jobExecution); JobSynchronizationManager.close(); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/StepContextRepeatCallbackTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/StepContextRepeatCallbackTests.java index 1cf3a01ee4..6cb8576a0c 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/StepContextRepeatCallbackTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/StepContextRepeatCallbackTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,12 +15,12 @@ */ package org.springframework.batch.core.scope.context; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; @@ -31,21 +31,21 @@ * @author Dave Syer * */ -public class StepContextRepeatCallbackTests { +class StepContextRepeatCallbackTests { - private StepExecution stepExecution = new StepExecution("foo", new JobExecution(0L), 123L); + private final StepExecution stepExecution = new StepExecution("foo", new JobExecution(0L), 123L); private boolean addedAttribute = false; private boolean removedAttribute = false; - @After - public void cleanUpStepContext() { + @AfterEach + void cleanUpStepContext() { StepSynchronizationManager.close(); } @Test - public void testDoInIteration() throws Exception { + void testDoInIteration() throws Exception { StepContextRepeatCallback callback = new StepContextRepeatCallback(stepExecution) { @Override public RepeatStatus doInChunkContext(RepeatContext context, ChunkContext chunkContext) throws Exception { @@ -58,7 +58,7 @@ public RepeatStatus doInChunkContext(RepeatContext context, ChunkContext chunkCo } @Test - public void testAddingAttributes() throws Exception { + void testAddingAttributes() throws Exception { StepSynchronizationManager.register(stepExecution); StepContextRepeatCallback callback = new StepContextRepeatCallback(stepExecution) { @Override diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/StepContextTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/StepContextTests.java index 02a2587b78..a451112c8e 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/StepContextTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/StepContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,18 +15,16 @@ */ package org.springframework.batch.core.scope.context; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.List; -import java.util.Map; -import java.util.Properties; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInstance; import org.springframework.batch.core.JobParameters; @@ -40,9 +38,9 @@ * @author Mahmoud Ben Hassine * */ -public class StepContextTests { +class StepContextTests { - private List list = new ArrayList<>(); + private final List list = new ArrayList<>(); private StepExecution stepExecution = new StepExecution("step", new JobExecution(new JobInstance(2L, "job"), 0L, null), 1L); @@ -50,39 +48,33 @@ public class StepContextTests { private StepContext context = new StepContext(stepExecution); @Test - public void testGetStepExecution() { + void testGetStepExecution() { context = new StepContext(stepExecution); assertNotNull(context.getStepExecution()); } @Test - public void testNullStepExecution() { - try { - context = new StepContext(null); - fail("Expected IllegalArgumentException"); - } - catch (IllegalArgumentException e) { - // expected - } + void testNullStepExecution() { + assertThrows(IllegalArgumentException.class, () -> new StepContext(null)); } @Test - public void testEqualsSelf() { + void testEqualsSelf() { assertEquals(context, context); } @Test - public void testNotEqualsNull() { + void testNotEqualsNull() { assertFalse(context.equals(null)); } @Test - public void testEqualsContextWithSameStepExecution() { + void testEqualsContextWithSameStepExecution() { assertEquals(new StepContext(stepExecution), context); } @Test - public void testDestructionCallbackSunnyDay() throws Exception { + void testDestructionCallbackSunnyDay() { context.setAttribute("foo", "FOO"); context.registerDestructionCallback("foo", new Runnable() { @Override @@ -96,7 +88,7 @@ public void run() { } @Test - public void testDestructionCallbackMissingAttribute() throws Exception { + void testDestructionCallbackMissingAttribute() { context.registerDestructionCallback("foo", new Runnable() { @Override public void run() { @@ -110,7 +102,7 @@ public void run() { } @Test - public void testDestructionCallbackWithException() throws Exception { + void testDestructionCallbackWithException() { context.setAttribute("foo", "FOO"); context.setAttribute("bar", "BAR"); context.registerDestructionCallback("bar", new Runnable() { @@ -127,14 +119,9 @@ public void run() { throw new RuntimeException("fail!"); } }); - try { - context.close(); - fail("Expected RuntimeException"); - } - catch (RuntimeException e) { - // We don't care which one was thrown... - assertEquals("fail!", e.getMessage()); - } + Exception exception = assertThrows(RuntimeException.class, () -> context.close()); + // We don't care which one was thrown... + assertEquals("fail!", exception.getMessage()); // ...but we do care that both were executed: assertEquals(2, list.size()); assertTrue(list.contains("bar")); @@ -142,42 +129,42 @@ public void run() { } @Test - public void testStepName() throws Exception { + void testStepName() { assertEquals("step", context.getStepName()); } @Test - public void testJobName() throws Exception { + void testJobName() { assertEquals("job", context.getJobName()); } @Test - public void testJobInstanceId() throws Exception { + void testJobInstanceId() { assertEquals(2L, (long) context.getJobInstanceId()); } @Test - public void testStepExecutionContext() throws Exception { + void testStepExecutionContext() { ExecutionContext executionContext = stepExecution.getExecutionContext(); executionContext.put("foo", "bar"); assertEquals("bar", context.getStepExecutionContext().get("foo")); } @Test - public void testSystemProperties() throws Exception { + void testSystemProperties() { System.setProperty("foo", "bar"); assertEquals("bar", context.getSystemProperties().getProperty("foo")); } @Test - public void testJobExecutionContext() throws Exception { + void testJobExecutionContext() { ExecutionContext executionContext = stepExecution.getJobExecution().getExecutionContext(); executionContext.put("foo", "bar"); assertEquals("bar", context.getJobExecutionContext().get("foo")); } @Test - public void testJobParameters() throws Exception { + void testJobParameters() { JobParameters jobParameters = new JobParametersBuilder().addString("foo", "bar").toJobParameters(); JobInstance instance = stepExecution.getJobExecution().getJobInstance(); stepExecution = new StepExecution("step", new JobExecution(instance, jobParameters)); @@ -186,14 +173,14 @@ public void testJobParameters() throws Exception { } @Test - public void testContextId() throws Exception { + void testContextId() { assertEquals("execution#1", context.getId()); } - @Test(expected = IllegalStateException.class) - public void testIllegalContextId() throws Exception { + @Test + void testIllegalContextId() { context = new StepContext(new StepExecution("foo", new JobExecution(0L))); - context.getId(); + assertThrows(IllegalStateException.class, context::getId); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/StepSynchronizationManagerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/StepSynchronizationManagerTests.java index 39d5291792..98657de748 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/StepSynchronizationManagerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/StepSynchronizationManagerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2021 the original author or authors. + * Copyright 2013-2022 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. @@ -15,9 +15,9 @@ */ package org.springframework.batch.core.scope.context; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import java.util.ArrayList; import java.util.List; @@ -27,33 +27,33 @@ import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; -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.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; -public class StepSynchronizationManagerTests { +class StepSynchronizationManagerTests { - private StepExecution stepExecution = new StepExecution("step", new JobExecution(0L)); + private final StepExecution stepExecution = new StepExecution("step", new JobExecution(0L)); - @Before - @After - public void start() { + @BeforeEach + @AfterEach + void start() { while (StepSynchronizationManager.getContext() != null) { StepSynchronizationManager.close(); } } @Test - public void testGetContext() { + void testGetContext() { assertNull(StepSynchronizationManager.getContext()); StepSynchronizationManager.register(stepExecution); assertNotNull(StepSynchronizationManager.getContext()); } @Test - public void testClose() throws Exception { + void testClose() { final List list = new ArrayList<>(); StepContext context = StepSynchronizationManager.register(stepExecution); context.registerDestructionCallback("foo", new Runnable() { @@ -68,7 +68,7 @@ public void run() { } @Test - public void testMultithreaded() throws Exception { + void testMultithreaded() throws Exception { StepContext context = StepSynchronizationManager.register(stepExecution); ExecutorService executorService = Executors.newFixedThreadPool(2); FutureTask task = new FutureTask<>(new Callable() { @@ -93,7 +93,7 @@ public StepContext call() throws Exception { } @Test - public void testRelease() { + void testRelease() { StepContext context = StepSynchronizationManager.register(stepExecution); final List list = new ArrayList<>(); context.registerDestructionCallback("foo", new Runnable() { @@ -109,14 +109,14 @@ public void run() { } @Test - public void testRegisterNull() { + void testRegisterNull() { assertNull(StepSynchronizationManager.getContext()); StepSynchronizationManager.register(null); assertNull(StepSynchronizationManager.getContext()); } @Test - public void testRegisterTwice() { + void testRegisterTwice() { StepSynchronizationManager.register(stepExecution); StepSynchronizationManager.register(stepExecution); StepSynchronizationManager.close(); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/NoSuchStepExceptionTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/NoSuchStepExceptionTests.java index 41fe26fb72..7763e606a7 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/NoSuchStepExceptionTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/NoSuchStepExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,14 +15,14 @@ */ package org.springframework.batch.core.step; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class NoSuchStepExceptionTests { +class NoSuchStepExceptionTests { @Test - public void testNoSuchStepExecutionExceptionString() { + void testNoSuchStepExecutionExceptionString() { NoSuchStepException exception = new NoSuchStepException("foo"); assertEquals("foo", exception.getMessage()); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/NoWorkFoundStepExecutionListenerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/NoWorkFoundStepExecutionListenerTests.java index e0e342a2b2..ca6216cda2 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/NoWorkFoundStepExecutionListenerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/NoWorkFoundStepExecutionListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2022 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. @@ -15,10 +15,10 @@ */ package org.springframework.batch.core.step; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInstance; @@ -28,12 +28,12 @@ /** * Tests for {@link NoWorkFoundStepExecutionListener}. */ -public class NoWorkFoundStepExecutionListenerTests { +class NoWorkFoundStepExecutionListenerTests { - private NoWorkFoundStepExecutionListener tested = new NoWorkFoundStepExecutionListener(); + private final NoWorkFoundStepExecutionListener tested = new NoWorkFoundStepExecutionListener(); @Test - public void noWork() { + void noWork() { StepExecution stepExecution = new StepExecution("NoProcessingStep", new JobExecution(new JobInstance(1L, "NoProcessingJob"), new JobParameters())); @@ -45,7 +45,7 @@ public void noWork() { } @Test - public void workDone() { + void workDone() { StepExecution stepExecution = new StepExecution("NoProcessingStep", new JobExecution(new JobInstance(1L, "NoProcessingJob"), new JobParameters())); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/NonAbstractStepTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/NonAbstractStepTests.java index bdf1b145b2..2fb627df56 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/NonAbstractStepTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/NonAbstractStepTests.java @@ -22,9 +22,9 @@ import io.micrometer.core.instrument.Tag; import io.micrometer.core.instrument.Tags; import io.micrometer.core.tck.MeterRegistryAssert; -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.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; @@ -38,15 +38,16 @@ import org.springframework.lang.Nullable; import org.springframework.util.Assert; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests for {@link AbstractStep}. */ -public class NonAbstractStepTests { +class NonAbstractStepTests { AbstractStep tested = new EventTrackingStep(); @@ -151,14 +152,14 @@ public void add(StepExecution stepExecution) { } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { tested.setJobRepository(repository); repository.add(execution); } @Test - public void testBeanName() throws Exception { + void testBeanName() { AbstractStep step = new AbstractStep() { @Override protected void doExecute(StepExecution stepExecution) throws Exception { @@ -170,7 +171,7 @@ protected void doExecute(StepExecution stepExecution) throws Exception { } @Test - public void testName() throws Exception { + void testName() { AbstractStep step = new AbstractStep() { @Override protected void doExecute(StepExecution stepExecution) throws Exception { @@ -187,7 +188,7 @@ protected void doExecute(StepExecution stepExecution) throws Exception { * Typical step execution scenario. */ @Test - public void testExecute() throws Exception { + void testExecute() throws Exception { tested.setStepExecutionListeners(new StepExecutionListener[] { listener1, listener2 }); tested.execute(execution); @@ -203,10 +204,10 @@ public void testExecute() throws Exception { assertEquals(ExitStatus.COMPLETED, execution.getExitStatus()); - assertTrue("Execution context modifications made by listener should be persisted", - repository.saved.containsKey("beforeStep")); - assertTrue("Execution context modifications made by listener should be persisted", - repository.saved.containsKey("afterStep")); + assertTrue(repository.saved.containsKey("beforeStep"), + "Execution context modifications made by listener should be persisted"); + assertTrue(repository.saved.containsKey("afterStep"), + "Execution context modifications made by listener should be persisted"); // Observability MeterRegistryAssert.assertThat(Metrics.globalRegistry).hasTimerWithNameAndTags( @@ -216,13 +217,13 @@ public void testExecute() throws Exception { Tag.of("spring.batch.step.status", "COMPLETED"))); } - @After - public void cleanup() { + @AfterEach + void cleanup() { Metrics.globalRegistry.clear(); } @Test - public void testFailure() throws Exception { + void testFailure() throws Exception { tested = new EventTrackingStep() { @Override protected void doExecute(StepExecution context) throws Exception { @@ -250,17 +251,17 @@ protected void doExecute(StepExecution context) throws Exception { assertEquals(ExitStatus.FAILED.getExitCode(), execution.getExitStatus().getExitCode()); String exitDescription = execution.getExitStatus().getExitDescription(); - assertTrue("Wrong message: " + exitDescription, exitDescription.contains("crash")); + assertTrue(exitDescription.contains("crash"), "Wrong message: " + exitDescription); - assertTrue("Execution context modifications made by listener should be persisted", - repository.saved.containsKey("afterStep")); + assertTrue(repository.saved.containsKey("afterStep"), + "Execution context modifications made by listener should be persisted"); } /** * Exception during business processing. */ @Test - public void testStoppedStep() throws Exception { + void testStoppedStep() throws Exception { tested = new EventTrackingStep() { @Override protected void doExecute(StepExecution context) throws Exception { @@ -288,12 +289,12 @@ protected void doExecute(StepExecution context) throws Exception { assertEquals("STOPPED", execution.getExitStatus().getExitCode()); - assertTrue("Execution context modifications made by listener should be persisted", - repository.saved.containsKey("afterStep")); + assertTrue(repository.saved.containsKey("afterStep"), + "Execution context modifications made by listener should be persisted"); } @Test - public void testStoppedStepWithCustomStatus() throws Exception { + void testStoppedStepWithCustomStatus() throws Exception { tested = new EventTrackingStep() { @Override protected void doExecute(StepExecution context) throws Exception { @@ -312,15 +313,15 @@ protected void doExecute(StepExecution context) throws Exception { assertEquals("FUNNY", execution.getExitStatus().getExitCode()); - assertTrue("Execution context modifications made by listener should be persisted", - repository.saved.containsKey("afterStep")); + assertTrue(repository.saved.containsKey("afterStep"), + "Execution context modifications made by listener should be persisted"); } /** * Exception during business processing. */ @Test - public void testFailureInSavingExecutionContext() throws Exception { + void testFailureInSavingExecutionContext() throws Exception { tested = new EventTrackingStep() { @Override protected void doExecute(StepExecution context) throws Exception { @@ -352,10 +353,10 @@ public void updateExecutionContext(StepExecution stepExecution) { /** * JobRepository is a required property. */ - @Test(expected = IllegalStateException.class) - public void testAfterPropertiesSet() throws Exception { + @Test + void testAfterPropertiesSet() { tested.setJobRepository(null); - tested.afterPropertiesSet(); + assertThrows(IllegalStateException.class, tested::afterPropertiesSet); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/RestartInPriorStepTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/RestartInPriorStepTests.java index dc03023f6f..4345d3177a 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/RestartInPriorStepTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/RestartInPriorStepTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2021 the original author or authors. + * Copyright 2013-2022 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. @@ -15,8 +15,7 @@ */ package org.springframework.batch.core.step; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.Job; @@ -33,23 +32,21 @@ import org.springframework.batch.repeat.RepeatStatus; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.lang.Nullable; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import java.util.Map; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Michael Minella * @author Mahmoud Ben Hassine * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) +@SpringJUnitConfig // FIXME this test fails when upgrading the batch xsd from 2.2 to 3.0: // https://github.com/spring-projects/spring-batch/issues/1287 -public class RestartInPriorStepTests { +class RestartInPriorStepTests { @Autowired private JobRepository jobRepository; @@ -61,7 +58,7 @@ public class RestartInPriorStepTests { private Job job; @Test - public void test() throws Exception { + void test() throws Exception { JobExecution run1 = jobLauncher.run(job, new JobParameters()); assertEquals(BatchStatus.STOPPED, run1.getStatus()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/RestartLoopTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/RestartLoopTests.java index d1af78d0e9..ee88bbefd5 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/RestartLoopTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/RestartLoopTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2022 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. @@ -15,8 +15,7 @@ */ package org.springframework.batch.core.step; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -28,17 +27,15 @@ import org.springframework.batch.repeat.RepeatStatus; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.lang.Nullable; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Michael Minella */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class RestartLoopTests { +@SpringJUnitConfig +class RestartLoopTests { @Autowired private Job job; @@ -47,7 +44,7 @@ public class RestartLoopTests { private JobLauncher jobLauncher; @Test - public void test() throws Exception { + void test() throws Exception { // Run 1 JobExecution jobExecution1 = jobLauncher.run(job, new JobParameters()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/StepLocatorStepFactoryBeanTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/StepLocatorStepFactoryBeanTests.java index b43e2caaa8..7af0831ce5 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/StepLocatorStepFactoryBeanTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/StepLocatorStepFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 the original author or authors. + * Copyright 2012-2022 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. @@ -15,10 +15,10 @@ */ package org.springframework.batch.core.step; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobInterruptedException; import org.springframework.batch.core.Step; import org.springframework.batch.core.StepExecution; @@ -29,10 +29,10 @@ * * @author tvaughan */ -public class StepLocatorStepFactoryBeanTests { +class StepLocatorStepFactoryBeanTests { @Test - public void testFoo() throws Exception { + void testFoo() throws Exception { Step testStep1 = buildTestStep("foo"); Step testStep2 = buildTestStep("bar"); Step testStep3 = buildTestStep("baz"); @@ -73,7 +73,7 @@ public void execute(StepExecution stepExecution) throws JobInterruptedException } @Test - public void testGetObjectType() { + void testGetObjectType() { assertTrue((new StepLocatorStepFactoryBean()).getObjectType().isAssignableFrom(Step.class)); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/ThreadStepInterruptionPolicyTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/ThreadStepInterruptionPolicyTests.java index f2dd035f47..205d393574 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/ThreadStepInterruptionPolicyTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/ThreadStepInterruptionPolicyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,46 +15,34 @@ */ package org.springframework.batch.core.step; -import junit.framework.TestCase; - +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobInterruptedException; import org.springframework.batch.core.StepExecution; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * @author Dave Syer * */ -public class ThreadStepInterruptionPolicyTests extends TestCase { +class ThreadStepInterruptionPolicyTests { - ThreadStepInterruptionPolicy policy = new ThreadStepInterruptionPolicy(); + private final ThreadStepInterruptionPolicy policy = new ThreadStepInterruptionPolicy(); - private StepExecution context = new StepExecution("stepSupport", null); + private final StepExecution context = new StepExecution("stepSupport", null); - /** - * Test method for - * {@link org.springframework.batch.core.step.ThreadStepInterruptionPolicy#checkInterrupted(StepExecution)}. - * @throws Exception - */ - public void testCheckInterruptedNotComplete() throws Exception { - policy.checkInterrupted(context); - // no exception + @Test + void testCheckInterruptedNotComplete() { + assertDoesNotThrow(() -> policy.checkInterrupted(context)); } - /** - * Test method for - * {@link org.springframework.batch.core.step.ThreadStepInterruptionPolicy#checkInterrupted(StepExecution)}. - * @throws Exception - */ - public void testCheckInterruptedComplete() throws Exception { + @Test + void testCheckInterruptedComplete() { context.setTerminateOnly(); - try { - policy.checkInterrupted(context); - fail("Expected StepInterruptedException"); - } - catch (JobInterruptedException e) { - // expected - assertTrue(e.getMessage().indexOf("interrupt") >= 0); - } + Exception exception = assertThrows(JobInterruptedException.class, () -> policy.checkInterrupted(context)); + assertTrue(exception.getMessage().contains("interrupt")); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/builder/FaultTolerantStepBuilderTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/builder/FaultTolerantStepBuilderTests.java index c464231f0a..833eb1cf93 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/builder/FaultTolerantStepBuilderTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/builder/FaultTolerantStepBuilderTests.java @@ -15,8 +15,7 @@ */ package org.springframework.batch.core.step.builder; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.xml.DummyItemReader; @@ -24,18 +23,19 @@ import org.springframework.batch.core.configuration.xml.DummyJobRepository; import org.springframework.batch.support.transaction.ResourcelessTransactionManager; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -public class FaultTolerantStepBuilderTests { +class FaultTolerantStepBuilderTests { @Test - public void faultTolerantReturnsSameInstance() { + void faultTolerantReturnsSameInstance() { FaultTolerantStepBuilder builder = new FaultTolerantStepBuilder<>(new StepBuilder("test")); assertEquals(builder, builder.faultTolerant()); } @Test - public void testAnnotationBasedStepExecutionListenerRegistration() { + void testAnnotationBasedStepExecutionListenerRegistration() { // given FaultTolerantStepBuilder faultTolerantStepBuilder = new StepBuilder("myStep") .repository(new DummyJobRepository()).transactionManager(new ResourcelessTransactionManager()) @@ -46,7 +46,7 @@ public void testAnnotationBasedStepExecutionListenerRegistration() { Step step = faultTolerantStepBuilder.build(); // then - Assert.assertNotNull(step); + assertNotNull(step); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/builder/RegisterMultiListenerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/builder/RegisterMultiListenerTests.java index 12c51eb11f..5add119942 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/builder/RegisterMultiListenerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/builder/RegisterMultiListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2021 the original author or authors. + * Copyright 2013-2022 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. @@ -18,8 +18,8 @@ import java.util.List; import javax.sql.DataSource; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ChunkListener; @@ -53,7 +53,7 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.lang.Nullable; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test for registering a listener class that implements different listeners interfaces @@ -62,7 +62,7 @@ * @author Tobias Flohre * @author Michael Minella */ -public class RegisterMultiListenerTests { +class RegisterMultiListenerTests { @Autowired private JobLauncher jobLauncher; @@ -75,8 +75,8 @@ public class RegisterMultiListenerTests { private GenericApplicationContext context; - @After - public void tearDown() { + @AfterEach + void tearDown() { jobLauncher = null; job = null; callChecker = null; @@ -94,7 +94,7 @@ public void tearDown() { * @throws Exception */ @Test - public void testMultiListenerFaultTolerantStep() throws Exception { + void testMultiListenerFaultTolerantStep() throws Exception { bootstrap(MultiListenerFaultTolerantTestConfiguration.class); JobExecution execution = jobLauncher.run(job, new JobParameters()); @@ -106,7 +106,7 @@ public void testMultiListenerFaultTolerantStep() throws Exception { } @Test - public void testMultiListenerSimpleStep() throws Exception { + void testMultiListenerSimpleStep() throws Exception { bootstrap(MultiListenerTestConfiguration.class); JobExecution execution = jobLauncher.run(job, new JobParameters()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/builder/StepBuilderTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/builder/StepBuilderTests.java index aee0a1803e..3df90204bc 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/builder/StepBuilderTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/builder/StepBuilderTests.java @@ -17,11 +17,10 @@ import java.util.Arrays; import java.util.List; -import java.util.function.Function; import java.util.function.UnaryOperator; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; @@ -60,7 +59,7 @@ import org.springframework.lang.Nullable; import org.springframework.transaction.PlatformTransactionManager; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Dave Syer @@ -69,7 +68,7 @@ * @author Parikshit Dutta * */ -public class StepBuilderTests { +class StepBuilderTests { private JobRepository jobRepository; @@ -77,8 +76,8 @@ public class StepBuilderTests { private PlatformTransactionManager transactionManager; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { EmbeddedDatabase embeddedDatabase = new EmbeddedDatabaseBuilder() .addScript("/org/springframework/batch/core/schema-drop-hsqldb.sql") .addScript("/org/springframework/batch/core/schema-hsqldb.sql").build(); @@ -94,7 +93,7 @@ public void setUp() throws Exception { } @Test - public void test() throws Exception { + void test() throws Exception { TaskletStepBuilder builder = new StepBuilder("step").repository(jobRepository) .transactionManager(transactionManager).tasklet((contribution, chunkContext) -> null); builder.build().execute(execution); @@ -102,7 +101,7 @@ public void test() throws Exception { } @Test - public void testListeners() throws Exception { + void testListeners() throws Exception { TaskletStepBuilder builder = new StepBuilder("step").repository(jobRepository) .transactionManager(transactionManager).listener(new InterfaceBasedStepExecutionListener()) .listener(new AnnotationBasedStepExecutionListener()).tasklet((contribution, chunkContext) -> null); @@ -117,7 +116,7 @@ public void testListeners() throws Exception { } @Test - public void testAnnotationBasedChunkListenerForTaskletStep() throws Exception { + void testAnnotationBasedChunkListenerForTaskletStep() throws Exception { TaskletStepBuilder builder = new StepBuilder("step").repository(jobRepository) .transactionManager(transactionManager).tasklet((contribution, chunkContext) -> null) .listener(new AnnotationBasedChunkListener()); @@ -128,7 +127,7 @@ public void testAnnotationBasedChunkListenerForTaskletStep() throws Exception { } @Test - public void testAnnotationBasedChunkListenerForSimpleTaskletStep() throws Exception { + void testAnnotationBasedChunkListenerForSimpleTaskletStep() throws Exception { SimpleStepBuilder builder = new StepBuilder("step").repository(jobRepository) .transactionManager(transactionManager).chunk(5).reader(new DummyItemReader()) .writer(new DummyItemWriter()).listener(new AnnotationBasedChunkListener()); @@ -139,7 +138,7 @@ public void testAnnotationBasedChunkListenerForSimpleTaskletStep() throws Except } @Test - public void testAnnotationBasedChunkListenerForFaultTolerantTaskletStep() throws Exception { + void testAnnotationBasedChunkListenerForFaultTolerantTaskletStep() throws Exception { SimpleStepBuilder builder = new StepBuilder("step").repository(jobRepository) .transactionManager(transactionManager).chunk(5).reader(new DummyItemReader()) .writer(new DummyItemWriter()).faultTolerant().listener(new AnnotationBasedChunkListener()); // TODO// @@ -154,7 +153,7 @@ public void testAnnotationBasedChunkListenerForFaultTolerantTaskletStep() throws } @Test - public void testAnnotationBasedChunkListenerForJobStepBuilder() throws Exception { + void testAnnotationBasedChunkListenerForJobStepBuilder() throws Exception { SimpleJob job = new SimpleJob("job"); job.setJobRepository(jobRepository); JobStepBuilder builder = new StepBuilder("step").repository(jobRepository) @@ -169,7 +168,7 @@ public void testAnnotationBasedChunkListenerForJobStepBuilder() throws Exception } @Test - public void testItemListeners() throws Exception { + void testItemListeners() throws Exception { List items = Arrays.asList("1", "2", "3"); ItemReader reader = new ListItemReader<>(items); @@ -194,12 +193,12 @@ public void testItemListeners() throws Exception { } @Test - public void testFunctions() throws Exception { + void testFunctions() throws Exception { assertStepFunctions(false); } @Test - public void testFunctionsWithFaultTolerantStep() throws Exception { + void testFunctionsWithFaultTolerantStep() throws Exception { assertStepFunctions(true); } @@ -227,46 +226,46 @@ private void assertStepFunctions(boolean faultTolerantStep) throws Exception { } @Test - public void testReturnedTypeOfChunkListenerIsAssignableToSimpleStepBuilder() throws Exception { + void testReturnedTypeOfChunkListenerIsAssignableToSimpleStepBuilder() throws Exception { testReturnedTypeOfSetterIsAssignableToSimpleStepBuilder(builder -> builder.listener(new ChunkListenerSupport() { })); } @Test - public void testReturnedTypeOfStreamIsAssignableToSimpleStepBuilder() throws Exception { + void testReturnedTypeOfStreamIsAssignableToSimpleStepBuilder() throws Exception { testReturnedTypeOfSetterIsAssignableToSimpleStepBuilder(builder -> builder.stream(new ItemStreamSupport() { })); } @Test - public void testReturnedTypeOfTaskExecutorIsAssignableToSimpleStepBuilder() throws Exception { + void testReturnedTypeOfTaskExecutorIsAssignableToSimpleStepBuilder() throws Exception { testReturnedTypeOfSetterIsAssignableToSimpleStepBuilder(builder -> builder.taskExecutor(null)); } @Test - public void testReturnedTypeOfThrottleLimitIsAssignableToSimpleStepBuilder() throws Exception { + void testReturnedTypeOfThrottleLimitIsAssignableToSimpleStepBuilder() throws Exception { testReturnedTypeOfSetterIsAssignableToSimpleStepBuilder(builder -> builder.throttleLimit(4)); } @Test - public void testReturnedTypeOfExceptionHandlerIsAssignableToSimpleStepBuilder() throws Exception { + void testReturnedTypeOfExceptionHandlerIsAssignableToSimpleStepBuilder() throws Exception { testReturnedTypeOfSetterIsAssignableToSimpleStepBuilder( builder -> builder.exceptionHandler(new DefaultExceptionHandler())); } @Test - public void testReturnedTypeOfStepOperationsIsAssignableToSimpleStepBuilder() throws Exception { + void testReturnedTypeOfStepOperationsIsAssignableToSimpleStepBuilder() throws Exception { testReturnedTypeOfSetterIsAssignableToSimpleStepBuilder( builder -> builder.stepOperations(new RepeatTemplate())); } @Test - public void testReturnedTypeOfTransactionAttributeIsAssignableToSimpleStepBuilder() throws Exception { + void testReturnedTypeOfTransactionAttributeIsAssignableToSimpleStepBuilder() throws Exception { testReturnedTypeOfSetterIsAssignableToSimpleStepBuilder(builder -> builder.transactionAttribute(null)); } @Test - public void testReturnedTypeOfListenerIsAssignableToSimpleStepBuilder() throws Exception { + void testReturnedTypeOfListenerIsAssignableToSimpleStepBuilder() throws Exception { testReturnedTypeOfSetterIsAssignableToSimpleStepBuilder( builder -> builder.listener(new AnnotationBasedStepExecutionListener())); assertEquals(1, AnnotationBasedStepExecutionListener.beforeStepCount); @@ -274,7 +273,7 @@ public void testReturnedTypeOfListenerIsAssignableToSimpleStepBuilder() throws E } @Test - public void testReturnedTypeOfExecutionListenerIsAssignableToSimpleStepBuilder() throws Exception { + void testReturnedTypeOfExecutionListenerIsAssignableToSimpleStepBuilder() throws Exception { testReturnedTypeOfSetterIsAssignableToSimpleStepBuilder( builder -> builder.listener(new InterfaceBasedStepExecutionListener())); assertEquals(1, InterfaceBasedStepExecutionListener.beforeStepCount); @@ -282,7 +281,7 @@ public void testReturnedTypeOfExecutionListenerIsAssignableToSimpleStepBuilder() } @Test - public void testReturnedTypeOfAllowStartIfCompleteIsAssignableToSimpleStepBuilder() throws Exception { + void testReturnedTypeOfAllowStartIfCompleteIsAssignableToSimpleStepBuilder() throws Exception { testReturnedTypeOfSetterIsAssignableToSimpleStepBuilder(builder -> builder.allowStartIfComplete(false)); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/AlmostStatefulRetryChunkTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/AlmostStatefulRetryChunkTests.java index 947ec4cce2..f9cd6c3f28 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/AlmostStatefulRetryChunkTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/AlmostStatefulRetryChunkTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -18,30 +18,25 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.stream.Stream; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Dave Syer * */ -@RunWith(Parameterized.class) -public class AlmostStatefulRetryChunkTests { +class AlmostStatefulRetryChunkTests { - private Log logger = LogFactory.getLog(getClass()); - - private final Chunk chunk; - - private final int retryLimit; + private final Log logger = LogFactory.getLog(getClass()); private int retryAttempts = 0; @@ -49,16 +44,13 @@ public class AlmostStatefulRetryChunkTests { private int count = 0; - public AlmostStatefulRetryChunkTests(String[] args, int limit) { - chunk = new Chunk<>(); + @MethodSource + @ParameterizedTest + void testRetry(List args, int limit) { + Chunk chunk = new Chunk<>(); for (String string : args) { chunk.add(string); } - this.retryLimit = limit; - } - - @Test - public void testRetry() throws Exception { logger.debug("Starting simple scenario"); List items = new ArrayList<>(chunk.getItems()); int before = items.size(); @@ -66,7 +58,7 @@ public void testRetry() throws Exception { boolean error = true; while (error && count++ < BACKSTOP_LIMIT) { try { - statefulRetry(chunk); + statefulRetry(chunk, limit); error = false; } catch (Exception e) { @@ -74,7 +66,7 @@ public void testRetry() throws Exception { } } logger.debug("Chunk: " + chunk); - assertTrue("Backstop reached. Probably an infinite loop...", count < BACKSTOP_LIMIT); + assertTrue(count < BACKSTOP_LIMIT, "Backstop reached. Probably an infinite loop..."); assertFalse(chunk.getItems().contains("fail")); assertEquals(items, chunk.getItems()); assertEquals(before - chunk.getItems().size(), chunk.getSkips().size()); @@ -83,7 +75,7 @@ public void testRetry() throws Exception { /** * @param chunk Chunk to retry */ - private void statefulRetry(Chunk chunk) throws Exception { + private void statefulRetry(Chunk chunk, int retryLimit) throws Exception { if (retryAttempts <= retryLimit) { try { // N.B. a classic stateful retry goes straight to recovery here @@ -107,8 +99,6 @@ private void statefulRetry(Chunk chunk) throws Exception { } } // recovery - return; - } /** @@ -136,26 +126,18 @@ private void doWrite(List items) throws Exception { } } - @Parameters - public static List data() { - List params = new ArrayList<>(); - params.add(new Object[] { new String[] { "foo" }, 0 }); - params.add(new Object[] { new String[] { "foo", "bar" }, 0 }); - params.add(new Object[] { new String[] { "foo", "bar", "spam" }, 0 }); - params.add(new Object[] { new String[] { "foo", "bar", "spam", "maps", "rab", "oof" }, 0 }); - params.add(new Object[] { new String[] { "fail" }, 0 }); - params.add(new Object[] { new String[] { "foo", "fail" }, 0 }); - params.add(new Object[] { new String[] { "fail", "bar" }, 0 }); - params.add(new Object[] { new String[] { "foo", "fail", "spam" }, 0 }); - params.add(new Object[] { new String[] { "fail", "bar", "spam" }, 0 }); - params.add(new Object[] { new String[] { "foo", "fail", "spam", "maps", "rab", "oof" }, 0 }); - params.add(new Object[] { new String[] { "foo", "fail", "spam", "fail", "rab", "oof" }, 0 }); - params.add(new Object[] { new String[] { "fail", "bar", "spam", "fail", "rab", "oof" }, 0 }); - params.add(new Object[] { new String[] { "foo", "fail", "fail", "fail", "rab", "oof" }, 0 }); - params.add(new Object[] { new String[] { "fail" }, 1 }); - params.add(new Object[] { new String[] { "foo", "fail", "fail", "fail", "rab", "oof" }, 1 }); - params.add(new Object[] { new String[] { "foo", "fail", "fail", "fail", "rab", "oof" }, 4 }); - return params; + static Stream testRetry() { + return Stream.of(Arguments.of(List.of("foo"), 0), Arguments.of(List.of("foo", "bar"), 0), + Arguments.of(List.of("foo", "bar", "spam"), 0), + Arguments.of(List.of("foo", "bar", "spam", "maps", "rab", "oof"), 0), Arguments.of(List.of("fail"), 0), + Arguments.of(List.of("foo", "fail"), 0), Arguments.of(List.of("fail", "bar"), 0), + Arguments.of(List.of("foo", "fail", "spam"), 0), Arguments.of(List.of("fail", "bar", "spam"), 0), + Arguments.of(List.of("foo", "fail", "spam", "maps", "rab", "oof"), 0), + Arguments.of(List.of("foo", "fail", "spam", "fail", "rab", "oof"), 0), + Arguments.of(List.of("fail", "bar", "spam", "fail", "rab", "oof"), 0), + Arguments.of(List.of("foo", "fail", "fail", "fail", "rab", "oof"), 0), Arguments.of(List.of("fail"), 1), + Arguments.of(List.of("foo", "fail", "fail", "fail", "rab", "oof"), 1), + Arguments.of(List.of("foo", "fail", "fail", "fail", "rab", "oof"), 4)); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/BatchRetryTemplateTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/BatchRetryTemplateTests.java index 10eb6e1676..2cecc24da8 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/BatchRetryTemplateTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/BatchRetryTemplateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2012 the original author or authors. + * Copyright 2008-2022 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. @@ -15,7 +15,7 @@ */ package org.springframework.batch.core.step.item; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.retry.ExhaustedRetryException; import org.springframework.retry.RecoveryCallback; import org.springframework.retry.RetryCallback; @@ -29,13 +29,12 @@ import java.util.Collections; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class BatchRetryTemplateTests { +class BatchRetryTemplateTests { - @SuppressWarnings("serial") private static class RecoverableException extends Exception { public RecoverableException(String message) { @@ -49,15 +48,15 @@ public RecoverableException(String message) { private List outputs = new ArrayList<>(); @Test - public void testSuccessfulAttempt() throws Exception { + void testSuccessfulAttempt() throws Exception { BatchRetryTemplate template = new BatchRetryTemplate(); String result = template.execute(new RetryCallback() { @Override public String doWithRetry(RetryContext context) throws Exception { - assertTrue("Wrong context type: " + context.getClass().getSimpleName(), - context.getClass().getSimpleName().contains("Batch")); + assertTrue(context.getClass().getSimpleName().contains("Batch"), + "Wrong context type: " + context.getClass().getSimpleName()); return "2"; } }, Arrays.asList(new DefaultRetryState("1"))); @@ -67,7 +66,7 @@ public String doWithRetry(RetryContext context) throws Exception { } @Test - public void testUnSuccessfulAttemptAndRetry() throws Exception { + void testUnSuccessfulAttemptAndRetry() throws Exception { BatchRetryTemplate template = new BatchRetryTemplate(); @@ -83,21 +82,16 @@ public String[] doWithRetry(RetryContext context) throws Exception { }; List states = Arrays.asList(new DefaultRetryState("1"), new DefaultRetryState("2")); - try { - template.execute(retryCallback, states); - fail("Expected RecoverableException"); - } - catch (RecoverableException e) { - assertEquals("Recoverable", e.getMessage()); - } + Exception exception = assertThrows(RecoverableException.class, () -> template.execute(retryCallback, states)); + assertEquals("Recoverable", exception.getMessage()); String[] result = template.execute(retryCallback, states); assertEquals("[a, b]", Arrays.toString(result)); } - @Test(expected = ExhaustedRetryException.class) - public void testExhaustedRetry() throws Exception { + @Test + void testExhaustedRetry() { BatchRetryTemplate template = new BatchRetryTemplate(); template.setRetryPolicy(new SimpleRetryPolicy(1, @@ -113,21 +107,17 @@ public String[] doWithRetry(RetryContext context) throws Exception { } }; - outputs = Arrays.asList("a", "b"); - try { - template.execute(retryCallback, BatchRetryTemplate.createState(outputs)); - fail("Expected RecoverableException"); - } - catch (RecoverableException e) { - assertEquals("Recoverable", e.getMessage()); - } - outputs = Arrays.asList("a", "c"); - template.execute(retryCallback, BatchRetryTemplate.createState(outputs)); - + outputs = List.of("a", "b"); + Exception exception = assertThrows(RecoverableException.class, + () -> template.execute(retryCallback, BatchRetryTemplate.createState(outputs))); + assertEquals("Recoverable", exception.getMessage()); + outputs = List.of("a", "c"); + assertThrows(ExhaustedRetryException.class, + () -> template.execute(retryCallback, BatchRetryTemplate.createState(outputs))); } @Test - public void testExhaustedRetryAfterShuffle() throws Exception { + void testExhaustedRetryAfterShuffle() throws Exception { BatchRetryTemplate template = new BatchRetryTemplate(); template.setRetryPolicy(new SimpleRetryPolicy(1, @@ -144,21 +134,13 @@ public String[] doWithRetry(RetryContext context) throws Exception { }; outputs = Arrays.asList("a", "b"); - try { - template.execute(retryCallback, BatchRetryTemplate.createState(outputs)); - fail("Expected RecoverableException"); - } - catch (RecoverableException e) { - assertEquals("Recoverable", e.getMessage()); - } + Exception exception = assertThrows(RecoverableException.class, + () -> template.execute(retryCallback, BatchRetryTemplate.createState(outputs))); + assertEquals("Recoverable", exception.getMessage()); outputs = Arrays.asList("b", "c"); - try { - template.execute(retryCallback, BatchRetryTemplate.createState(outputs)); - fail("Expected ExhaustedRetryException"); - } - catch (ExhaustedRetryException e) { - } + assertThrows(ExhaustedRetryException.class, + () -> template.execute(retryCallback, BatchRetryTemplate.createState(outputs))); // "c" is not tarred with same brush as "b" because it was never // processed on account of the exhausted retry @@ -168,12 +150,8 @@ public String[] doWithRetry(RetryContext context) throws Exception { // "a" is still marked as a failure from the first chunk outputs = Arrays.asList("a", "e"); - try { - template.execute(retryCallback, BatchRetryTemplate.createState(outputs)); - fail("Expected ExhaustedRetryException"); - } - catch (ExhaustedRetryException e) { - } + assertThrows(ExhaustedRetryException.class, + () -> template.execute(retryCallback, BatchRetryTemplate.createState(outputs))); outputs = Arrays.asList("e", "f"); result = template.execute(retryCallback, BatchRetryTemplate.createState(outputs)); @@ -182,7 +160,7 @@ public String[] doWithRetry(RetryContext context) throws Exception { } @Test - public void testExhaustedRetryWithRecovery() throws Exception { + void testExhaustedRetryWithRecovery() throws Exception { BatchRetryTemplate template = new BatchRetryTemplate(); template.setRetryPolicy(new SimpleRetryPolicy(1, @@ -210,13 +188,9 @@ public String[] recover(RetryContext context) throws Exception { }; outputs = Arrays.asList("a", "b"); - try { - template.execute(retryCallback, recoveryCallback, BatchRetryTemplate.createState(outputs)); - fail("Expected RecoverableException"); - } - catch (RecoverableException e) { - assertEquals("Recoverable", e.getMessage()); - } + Exception exception = assertThrows(RecoverableException.class, + () -> template.execute(retryCallback, recoveryCallback, BatchRetryTemplate.createState(outputs))); + assertEquals("Recoverable", exception.getMessage()); outputs = Arrays.asList("b", "c"); String[] result = template.execute(retryCallback, recoveryCallback, BatchRetryTemplate.createState(outputs)); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/ChunkMonitorTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/ChunkMonitorTests.java index 992c8e0b7c..f8c283d959 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/ChunkMonitorTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/ChunkMonitorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2019 the original author or authors. + * Copyright 2006-2022 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. @@ -15,11 +15,12 @@ */ package org.springframework.batch.core.step.item; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.ItemStreamException; @@ -32,7 +33,7 @@ * @author Dave Syer * */ -public class ChunkMonitorTests { +class ChunkMonitorTests { private static final int CHUNK_SIZE = 5; @@ -42,8 +43,8 @@ public class ChunkMonitorTests { private boolean closed = false; - @Before - public void setUp() { + @BeforeEach + void setUp() { monitor.setItemReader(new ItemReader() { @Nullable @Override @@ -62,21 +63,21 @@ public void close() { } @Test - public void testIncrementOffset() { + void testIncrementOffset() { assertEquals(0, monitor.getOffset()); monitor.incrementOffset(); assertEquals(1, monitor.getOffset()); } @Test - public void testResetOffsetManually() { + void testResetOffsetManually() { monitor.incrementOffset(); monitor.resetOffset(); assertEquals(0, monitor.getOffset()); } @Test - public void testResetOffsetAutomatically() { + void testResetOffsetAutomatically() { for (int i = 0; i < CHUNK_SIZE; i++) { monitor.incrementOffset(); } @@ -84,7 +85,7 @@ public void testResetOffsetAutomatically() { } @Test - public void testClose() { + void testClose() { monitor.incrementOffset(); monitor.close(); assertTrue(closed); @@ -92,7 +93,7 @@ public void testClose() { } @Test - public void testOpen() { + void testOpen() { ExecutionContext executionContext = new ExecutionContext(); executionContext.putInt(ChunkMonitor.class.getName() + ".OFFSET", 2); monitor.open(executionContext); @@ -101,15 +102,15 @@ public void testOpen() { } @Test - public void testOpenWithNullReader() { + void testOpenWithNullReader() { monitor.setItemReader(null); ExecutionContext executionContext = new ExecutionContext(); monitor.open(executionContext); assertEquals(0, monitor.getOffset()); } - @Test(expected = ItemStreamException.class) - public void testOpenWithErrorInReader() { + @Test + void testOpenWithErrorInReader() { monitor.setItemReader(new ItemReader() { @Nullable @Override @@ -119,11 +120,11 @@ public String read() throws Exception, UnexpectedInputException, ParseException }); ExecutionContext executionContext = new ExecutionContext(); executionContext.putInt(ChunkMonitor.class.getName() + ".OFFSET", 2); - monitor.open(executionContext); + assertThrows(ItemStreamException.class, () -> monitor.open(executionContext)); } @Test - public void testUpdateOnBoundary() { + void testUpdateOnBoundary() { monitor.resetOffset(); ExecutionContext executionContext = new ExecutionContext(); monitor.update(executionContext); @@ -135,7 +136,7 @@ public void testUpdateOnBoundary() { } @Test - public void testUpdateVanilla() { + void testUpdateVanilla() { monitor.incrementOffset(); ExecutionContext executionContext = new ExecutionContext(); monitor.update(executionContext); @@ -143,7 +144,7 @@ public void testUpdateVanilla() { } @Test - public void testUpdateWithNoStream() throws Exception { + void testUpdateWithNoStream() { monitor = new ChunkMonitor(); monitor.setItemReader(new ItemReader() { @Nullable diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/ChunkOrientedTaskletTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/ChunkOrientedTaskletTests.java index 56c1f7ef97..c883e59a24 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/ChunkOrientedTaskletTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/ChunkOrientedTaskletTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2013 the original author or authors. + * Copyright 2006-2022 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. @@ -15,10 +15,11 @@ */ package org.springframework.batch.core.step.item; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInstance; @@ -31,12 +32,12 @@ * @author Dave Syer * */ -public class ChunkOrientedTaskletTests { +class ChunkOrientedTaskletTests { - private ChunkContext context = new ChunkContext(null); + private final ChunkContext context = new ChunkContext(null); @Test - public void testHandle() throws Exception { + void testHandle() throws Exception { ChunkOrientedTasklet handler = new ChunkOrientedTasklet<>(new ChunkProvider() { @Override public Chunk provide(StepContribution contribution) throws Exception { @@ -64,7 +65,7 @@ public void process(StepContribution contribution, Chunk chunk) { } @Test - public void testFail() throws Exception { + void testFail() { ChunkOrientedTasklet handler = new ChunkOrientedTasklet<>(new ChunkProvider() { @Override public Chunk provide(StepContribution contribution) throws Exception { @@ -82,18 +83,13 @@ public void process(StepContribution contribution, Chunk chunk) { }); StepContribution contribution = new StepContribution( new StepExecution("foo", new JobExecution(new JobInstance(123L, "job"), new JobParameters()))); - try { - handler.execute(contribution, context); - fail("Expected RuntimeException"); - } - catch (RuntimeException e) { - assertEquals("Foo!", e.getMessage()); - } + Exception exception = assertThrows(RuntimeException.class, () -> handler.execute(contribution, context)); + assertEquals("Foo!", exception.getMessage()); assertEquals(0, contribution.getReadCount()); } @Test - public void testExitCode() throws Exception { + void testExitCode() throws Exception { ChunkOrientedTasklet handler = new ChunkOrientedTasklet<>(new ChunkProvider() { @Override public Chunk provide(StepContribution contribution) throws Exception { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantChunkProcessorTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantChunkProcessorTests.java index 8517b08af9..24d2099213 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantChunkProcessorTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantChunkProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2019 the original author or authors. + * Copyright 2008-2022 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. @@ -15,17 +15,19 @@ */ package org.springframework.batch.core.step.item; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; +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.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInstance; import org.springframework.batch.core.JobParameters; @@ -44,23 +46,23 @@ import org.springframework.retry.policy.NeverRetryPolicy; import org.springframework.retry.policy.SimpleRetryPolicy; -public class FaultTolerantChunkProcessorTests { +class FaultTolerantChunkProcessorTests { private BatchRetryTemplate batchRetryTemplate; - private List list = new ArrayList<>(); + private final List list = new ArrayList<>(); - private List after = new ArrayList<>(); + private final List after = new ArrayList<>(); - private List writeError = new ArrayList<>(); + private final List writeError = new ArrayList<>(); private FaultTolerantChunkProcessor processor; - private StepContribution contribution = new StepExecution("foo", + private final StepContribution contribution = new StepExecution("foo", new JobExecution(new JobInstance(0L, "job"), new JobParameters())).createStepContribution(); - @Before - public void setUp() { + @BeforeEach + void setUp() { batchRetryTemplate = new BatchRetryTemplate(); processor = new FaultTolerantChunkProcessor<>(new PassThroughItemProcessor<>(), new ItemWriter() { @Override @@ -75,14 +77,14 @@ public void write(List items) throws Exception { } @Test - public void testWrite() throws Exception { + void testWrite() throws Exception { Chunk inputs = new Chunk<>(Arrays.asList("1", "2")); processor.process(contribution, inputs); assertEquals(2, list.size()); } @Test - public void testTransform() throws Exception { + void testTransform() throws Exception { processor.setItemProcessor(new ItemProcessor() { @Nullable @Override @@ -97,7 +99,7 @@ public String process(String item) throws Exception { } @Test - public void testFilterCountOnSkip() throws Exception { + void testFilterCountOnSkip() throws Exception { processor.setProcessSkipPolicy(new AlwaysSkipItemSkipPolicy()); processor.setItemProcessor(new ItemProcessor() { @Nullable @@ -113,13 +115,8 @@ public String process(String item) throws Exception { } }); Chunk inputs = new Chunk<>(Arrays.asList("3", "1", "2")); - try { - processor.process(contribution, inputs); - fail("Expected Exception"); - } - catch (Exception e) { - assertEquals("Skippable", e.getMessage()); - } + Exception exception = assertThrows(Exception.class, () -> processor.process(contribution, inputs)); + assertEquals("Skippable", exception.getMessage()); processor.process(contribution, inputs); assertEquals(1, list.size()); assertEquals(1, contribution.getSkipCount()); @@ -128,7 +125,7 @@ public String process(String item) throws Exception { @Test // BATCH-2663 - public void testFilterCountOnSkipInWriteWithoutRetry() throws Exception { + void testFilterCountOnSkipInWriteWithoutRetry() throws Exception { processor.setWriteSkipPolicy(new AlwaysSkipItemSkipPolicy()); processor.setItemProcessor(new ItemProcessor() { @Nullable @@ -156,7 +153,7 @@ public String process(String item) throws Exception { @Test // BATCH-2663 - public void testFilterCountOnSkipInWriteWithRetry() throws Exception { + void testFilterCountOnSkipInWriteWithRetry() throws Exception { SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(); retryPolicy.setMaxAttempts(3); batchRetryTemplate.setRetryPolicy(retryPolicy); @@ -192,29 +189,24 @@ public String process(String item) throws Exception { * @throws Exception */ @Test - public void testWriteSkipOnError() throws Exception { + void testWriteSkipOnError() throws Exception { processor.setWriteSkipPolicy(new AlwaysSkipItemSkipPolicy()); processor.setItemWriter(new ItemWriter() { @Override public void write(List items) throws Exception { if (items.contains("fail")) { - assertFalse("Expected Error!", true); + fail("Expected Error!"); } } }); Chunk inputs = new Chunk<>(Arrays.asList("3", "fail", "2")); - try { - processor.process(contribution, inputs); - fail("Expected Error"); - } - catch (Error e) { - assertEquals("Expected Error!", e.getMessage()); - } + Error error = assertThrows(Error.class, () -> processor.process(contribution, inputs)); + assertEquals("Expected Error!", error.getMessage()); processor.process(contribution, inputs); } @Test - public void testWriteSkipOnException() throws Exception { + void testWriteSkipOnException() throws Exception { processor.setWriteSkipPolicy(new AlwaysSkipItemSkipPolicy()); processor.setItemWriter(new ItemWriter() { @Override @@ -225,28 +217,18 @@ public void write(List items) throws Exception { } }); Chunk inputs = new Chunk<>(Arrays.asList("3", "fail", "2")); - try { - processor.process(contribution, inputs); - fail("Expected RuntimeException"); - } - catch (RuntimeException e) { - assertEquals("Expected Exception!", e.getMessage()); - } + Exception exception = assertThrows(RuntimeException.class, () -> processor.process(contribution, inputs)); + assertEquals("Expected Exception!", exception.getMessage()); processor.process(contribution, inputs); - try { - processor.process(contribution, inputs); - fail("Expected RuntimeException"); - } - catch (RuntimeException e) { - assertEquals("Expected Exception!", e.getMessage()); - } + exception = assertThrows(RuntimeException.class, () -> processor.process(contribution, inputs)); + assertEquals("Expected Exception!", exception.getMessage()); assertEquals(1, contribution.getSkipCount()); assertEquals(1, contribution.getWriteCount()); assertEquals(0, contribution.getFilterCount()); } @Test - public void testWriteSkipOnExceptionWithTrivialChunk() throws Exception { + void testWriteSkipOnExceptionWithTrivialChunk() throws Exception { processor.setWriteSkipPolicy(new AlwaysSkipItemSkipPolicy()); processor.setItemWriter(new ItemWriter() { @Override @@ -257,22 +239,12 @@ public void write(List items) throws Exception { } }); Chunk inputs = new Chunk<>(Arrays.asList("fail")); - try { - processor.process(contribution, inputs); - fail("Expected RuntimeException"); - } - catch (RuntimeException e) { - assertEquals("Expected Exception!", e.getMessage()); - } + Exception exception = assertThrows(RuntimeException.class, () -> processor.process(contribution, inputs)); + assertEquals("Expected Exception!", exception.getMessage()); // BATCH-1518: ideally we would not want this to be necessary, but it // still is... - try { - processor.process(contribution, inputs); - fail("Expected RuntimeException"); - } - catch (RuntimeException e) { - assertEquals("Expected Exception!", e.getMessage()); - } + exception = assertThrows(RuntimeException.class, () -> processor.process(contribution, inputs)); + assertEquals("Expected Exception!", exception.getMessage()); processor.process(contribution, inputs); assertEquals(1, contribution.getSkipCount()); assertEquals(0, contribution.getWriteCount()); @@ -280,7 +252,7 @@ public void write(List items) throws Exception { } @Test - public void testTransformWithExceptionAndNoRollback() throws Exception { + void testTransformWithExceptionAndNoRollback() throws Exception { processor.setItemProcessor(new ItemProcessor() { @Nullable @Override @@ -292,15 +264,15 @@ public String process(String item) throws Exception { } }); processor.setProcessSkipPolicy(new AlwaysSkipItemSkipPolicy()); - processor.setRollbackClassifier(new BinaryExceptionClassifier( - Collections.>singleton(DataIntegrityViolationException.class), false)); + processor.setRollbackClassifier( + new BinaryExceptionClassifier(Set.of(DataIntegrityViolationException.class), false)); Chunk inputs = new Chunk<>(Arrays.asList("1", "2")); processor.process(contribution, inputs); assertEquals(1, list.size()); } @Test - public void testAfterWrite() throws Exception { + void testAfterWrite() throws Exception { Chunk chunk = new Chunk<>(Arrays.asList("foo", "fail", "bar")); processor.setListeners(Arrays.asList(new ItemListenerSupport() { @Override @@ -325,7 +297,7 @@ public void afterWrite(List item) { } @Test - public void testAfterWriteAllPassedInRecovery() throws Exception { + void testAfterWriteAllPassedInRecovery() throws Exception { Chunk chunk = new Chunk<>(Arrays.asList("foo", "bar")); processor = new FaultTolerantChunkProcessor<>(new PassThroughItemProcessor<>(), new ItemWriter() { @Override @@ -354,7 +326,7 @@ public void afterWrite(List item) { } @Test - public void testOnErrorInWrite() throws Exception { + void testOnErrorInWrite() throws Exception { Chunk chunk = new Chunk<>(Arrays.asList("foo", "fail")); processor.setListeners(Arrays.asList(new ItemListenerSupport() { @Override @@ -372,7 +344,7 @@ public void onWriteError(Exception e, List item) { } @Test - public void testOnErrorInWriteAllItemsFail() throws Exception { + void testOnErrorInWriteAllItemsFail() throws Exception { Chunk chunk = new Chunk<>(Arrays.asList("foo", "bar")); processor = new FaultTolerantChunkProcessor<>(new PassThroughItemProcessor<>(), new ItemWriter() { @Override @@ -397,7 +369,7 @@ public void onWriteError(Exception e, List item) { } @Test - public void testWriteRetryOnException() throws Exception { + void testWriteRetryOnException() throws Exception { SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(); retryPolicy.setMaxAttempts(2); batchRetryTemplate.setRetryPolicy(retryPolicy); @@ -411,31 +383,16 @@ public void write(List items) throws Exception { } }); Chunk inputs = new Chunk<>(Arrays.asList("3", "fail", "2")); - try { - processor.process(contribution, inputs); - fail("Expected RuntimeException"); - } - catch (RuntimeException e) { - assertEquals("Expected Exception!", e.getMessage()); - } - try { - // first retry - processor.process(contribution, inputs); - fail("Expected RuntimeException"); - } - catch (RuntimeException e) { - assertEquals("Expected Exception!", e.getMessage()); - } + Exception exception = assertThrows(RuntimeException.class, () -> processor.process(contribution, inputs)); + assertEquals("Expected Exception!", exception.getMessage()); + // first retry + exception = assertThrows(RuntimeException.class, () -> processor.process(contribution, inputs)); + assertEquals("Expected Exception!", exception.getMessage()); // retry exhausted, now scanning processor.process(contribution, inputs); - try { - // skip on this attempt - processor.process(contribution, inputs); - fail("Expected RuntimeException"); - } - catch (RuntimeException e) { - assertEquals("Expected Exception!", e.getMessage()); - } + // skip on this attempt + exception = assertThrows(RuntimeException.class, () -> processor.process(contribution, inputs)); + assertEquals("Expected Exception!", exception.getMessage()); // finish chunk processor.process(contribution, inputs); assertEquals(1, contribution.getSkipCount()); @@ -444,7 +401,7 @@ public void write(List items) throws Exception { } @Test - public void testWriteRetryOnTwoExceptions() throws Exception { + void testWriteRetryOnTwoExceptions() throws Exception { SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(); retryPolicy.setMaxAttempts(2); batchRetryTemplate.setRetryPolicy(retryPolicy); @@ -458,39 +415,19 @@ public void write(List items) throws Exception { } }); Chunk inputs = new Chunk<>(Arrays.asList("3", "fail", "fail", "4")); - try { - processor.process(contribution, inputs); - fail("Expected RuntimeException"); - } - catch (RuntimeException e) { - assertEquals("Expected Exception!", e.getMessage()); - } - try { - // first retry - processor.process(contribution, inputs); - fail("Expected RuntimeException"); - } - catch (RuntimeException e) { - assertEquals("Expected Exception!", e.getMessage()); - } + Exception exception = assertThrows(RuntimeException.class, () -> processor.process(contribution, inputs)); + assertEquals("Expected Exception!", exception.getMessage()); + // first retry + exception = assertThrows(RuntimeException.class, () -> processor.process(contribution, inputs)); + assertEquals("Expected Exception!", exception.getMessage()); // retry exhausted, now scanning processor.process(contribution, inputs); - try { - // skip on this attempt - processor.process(contribution, inputs); - fail("Expected RuntimeException"); - } - catch (RuntimeException e) { - assertEquals("Expected Exception!", e.getMessage()); - } - try { - // 2nd exception detected - processor.process(contribution, inputs); - fail("Expected RuntimeException"); - } - catch (RuntimeException e) { - assertEquals("Expected Exception!", e.getMessage()); - } + // skip on this attempt + exception = assertThrows(RuntimeException.class, () -> processor.process(contribution, inputs)); + assertEquals("Expected Exception!", exception.getMessage()); + // 2nd exception detected + exception = assertThrows(RuntimeException.class, () -> processor.process(contribution, inputs)); + assertEquals("Expected Exception!", exception.getMessage()); // still scanning processor.process(contribution, inputs); assertEquals(2, contribution.getSkipCount()); @@ -500,7 +437,7 @@ public void write(List items) throws Exception { @Test // BATCH-1804 - public void testWriteRetryOnNonSkippableException() throws Exception { + void testWriteRetryOnNonSkippableException() throws Exception { SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(); retryPolicy.setMaxAttempts(2); batchRetryTemplate.setRetryPolicy(retryPolicy); @@ -518,42 +455,21 @@ public void write(List items) throws Exception { } }); Chunk inputs = new Chunk<>(Arrays.asList("3", "fail", "2")); - try { - processor.process(contribution, inputs); - fail("Expected IllegalArgumentException"); - } - catch (IllegalArgumentException e) { - assertEquals("Expected Exception!", e.getMessage()); - } - try { - // first retry - processor.process(contribution, inputs); - fail("Expected IllegalArgumentException"); - } - catch (IllegalArgumentException e) { - assertEquals("Expected Exception!", e.getMessage()); - } + Exception exception = assertThrows(IllegalArgumentException.class, + () -> processor.process(contribution, inputs)); + assertEquals("Expected Exception!", exception.getMessage()); + // first retry + exception = assertThrows(IllegalArgumentException.class, () -> processor.process(contribution, inputs)); + assertEquals("Expected Exception!", exception.getMessage()); // retry exhausted, now scanning processor.process(contribution, inputs); - try { - // skip on this attempt - processor.process(contribution, inputs); - fail("Expected IllegalArgumentException"); - } - catch (IllegalArgumentException e) { - assertEquals("Expected Exception!", e.getMessage()); - } - try { - // should retry - processor.process(contribution, inputs); - fail("Expected RuntimeException"); - } - catch (RetryException e) { - throw e; - } - catch (RuntimeException e) { - assertEquals("Expected Non-Skippable Exception!", e.getMessage()); - } + // skip on this attempt + exception = assertThrows(IllegalArgumentException.class, () -> processor.process(contribution, inputs)); + assertEquals("Expected Exception!", exception.getMessage()); + // should retry + exception = assertThrows(RuntimeException.class, () -> processor.process(contribution, inputs)); + assertFalse(exception instanceof RetryException); + assertEquals("Expected Non-Skippable Exception!", exception.getMessage()); assertEquals(1, contribution.getSkipCount()); assertEquals(1, contribution.getWriteCount()); assertEquals(0, contribution.getFilterCount()); @@ -561,7 +477,7 @@ public void write(List items) throws Exception { @Test // BATCH-2036 - public void testProcessFilterAndSkippableException() throws Exception { + void testProcessFilterAndSkippableException() throws Exception { final List processedItems = new ArrayList<>(); processor.setProcessorTransactional(false); processor.setProcessSkipPolicy(new AlwaysSkipItemSkipPolicy()); @@ -581,20 +497,11 @@ public String process(String item) throws Exception { }); processor.afterPropertiesSet(); Chunk inputs = new Chunk<>(Arrays.asList("1", "2", "skip", "skip", "3", "fail", "fail", "4", "5")); - try { - processor.process(contribution, inputs); - fail("Expected IllegalArgumentException"); - } - catch (IllegalArgumentException e) { - assertEquals("Expected Skippable Exception!", e.getMessage()); - } - try { - processor.process(contribution, inputs); - fail("Expected IllegalArgumentException"); - } - catch (IllegalArgumentException e) { - assertEquals("Expected Skippable Exception!", e.getMessage()); - } + Exception exception = assertThrows(IllegalArgumentException.class, + () -> processor.process(contribution, inputs)); + assertEquals("Expected Skippable Exception!", exception.getMessage()); + exception = assertThrows(IllegalArgumentException.class, () -> processor.process(contribution, inputs)); + assertEquals("Expected Skippable Exception!", exception.getMessage()); processor.process(contribution, inputs); assertEquals(5, list.size()); assertEquals("[1, 2, 3, 4, 5]", list.toString()); @@ -606,7 +513,7 @@ public String process(String item) throws Exception { @Test // BATCH-2036 - public void testProcessFilterAndSkippableExceptionNoRollback() throws Exception { + void testProcessFilterAndSkippableExceptionNoRollback() throws Exception { final List processedItems = new ArrayList<>(); processor.setProcessorTransactional(false); processor.setProcessSkipPolicy(new AlwaysSkipItemSkipPolicy()); @@ -637,14 +544,9 @@ public String process(String item) throws Exception { assertEquals("[1, 2, skip, skip, 3, fail, fail, 4, 5]", processedItems.toString()); } - protected void processAndExpectPlannedRuntimeException(Chunk chunk) throws Exception { - try { - processor.process(contribution, chunk); - fail(); - } - catch (RuntimeException e) { - assertEquals("Planned failure!", e.getMessage()); - } + protected void processAndExpectPlannedRuntimeException(Chunk chunk) { + Exception exception = assertThrows(RuntimeException.class, () -> processor.process(contribution, chunk)); + assertEquals("Planned failure!", exception.getMessage()); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantChunkProviderTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantChunkProviderTests.java index 166816abca..e418b747b8 100755 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantChunkProviderTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantChunkProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2019 the original author or authors. + * Copyright 2010-2022 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. @@ -15,13 +15,13 @@ */ package org.springframework.batch.core.step.item; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.Arrays; import java.util.Collections; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInstance; import org.springframework.batch.core.JobParameters; @@ -35,15 +35,15 @@ import org.springframework.batch.repeat.support.RepeatTemplate; import org.springframework.lang.Nullable; -public class FaultTolerantChunkProviderTests { +class FaultTolerantChunkProviderTests { private FaultTolerantChunkProvider provider; - private StepContribution contribution = new StepContribution( + private final StepContribution contribution = new StepContribution( new StepExecution("foo", new JobExecution(new JobInstance(123L, "job"), new JobParameters()))); @Test - public void testProvide() throws Exception { + void testProvide() throws Exception { provider = new FaultTolerantChunkProvider<>(new ListItemReader<>(Arrays.asList("foo", "bar")), new RepeatTemplate()); Chunk chunk = provider.provide(contribution); @@ -52,7 +52,7 @@ public void testProvide() throws Exception { } @Test - public void testProvideWithOverflow() throws Exception { + void testProvideWithOverflow() throws Exception { provider = new FaultTolerantChunkProvider<>(new ItemReader() { @Nullable @Override diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantExceptionClassesTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantExceptionClassesTests.java index 73f21fd37c..ec486a7636 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantExceptionClassesTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantExceptionClassesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2019 the original author or authors. + * Copyright 2009-2022 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. @@ -15,11 +15,8 @@ */ package org.springframework.batch.core.step.item; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParametersBuilder; @@ -33,25 +30,22 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.transaction.UnexpectedRollbackException; import java.util.ArrayList; import java.util.List; import java.util.UUID; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Dan Garrette * @author Mahmoud Ben Hassine * @since 2.0.2 */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -@FixMethodOrder(MethodSorters.JVM) +@SpringJUnitConfig public class FaultTolerantExceptionClassesTests implements ApplicationContextAware { @Autowired @@ -76,15 +70,15 @@ public void setApplicationContext(ApplicationContext applicationContext) throws this.applicationContext = applicationContext; } - @Before - public void setup() { + @BeforeEach + void setup() { reader.clear(); writer.clear(); tasklet.clear(); } @Test - public void testNonSkippable() throws Exception { + void testNonSkippable() throws Exception { writer.setExceptionType(RuntimeException.class); StepExecution stepExecution = launchStep("nonSkippableStep"); assertEquals(BatchStatus.FAILED, stepExecution.getStatus()); @@ -93,7 +87,7 @@ public void testNonSkippable() throws Exception { } @Test - public void testNonSkippableChecked() throws Exception { + void testNonSkippableChecked() throws Exception { writer.setExceptionType(Exception.class); StepExecution stepExecution = launchStep("nonSkippableStep"); assertEquals(BatchStatus.FAILED, stepExecution.getStatus()); @@ -102,7 +96,7 @@ public void testNonSkippableChecked() throws Exception { } @Test - public void testSkippable() throws Exception { + void testSkippable() throws Exception { writer.setExceptionType(SkippableRuntimeException.class); StepExecution stepExecution = launchStep("skippableStep"); assertEquals(BatchStatus.COMPLETED, stepExecution.getStatus()); @@ -111,7 +105,7 @@ public void testSkippable() throws Exception { } @Test - public void testRegularRuntimeExceptionNotSkipped() throws Exception { + void testRegularRuntimeExceptionNotSkipped() throws Exception { writer.setExceptionType(RuntimeException.class); StepExecution stepExecution = launchStep("skippableStep"); assertEquals(BatchStatus.FAILED, stepExecution.getStatus()); @@ -122,7 +116,7 @@ public void testRegularRuntimeExceptionNotSkipped() throws Exception { } @Test - public void testFatalOverridesSkippable() throws Exception { + void testFatalOverridesSkippable() throws Exception { writer.setExceptionType(FatalRuntimeException.class); StepExecution stepExecution = launchStep("skippableFatalStep"); assertEquals(BatchStatus.FAILED, stepExecution.getStatus()); @@ -131,7 +125,7 @@ public void testFatalOverridesSkippable() throws Exception { } @Test - public void testDefaultFatalChecked() throws Exception { + void testDefaultFatalChecked() throws Exception { writer.setExceptionType(Exception.class); StepExecution stepExecution = launchStep("skippableFatalStep"); assertEquals(BatchStatus.FAILED, stepExecution.getStatus()); @@ -142,7 +136,7 @@ public void testDefaultFatalChecked() throws Exception { } @Test - public void testSkippableChecked() throws Exception { + void testSkippableChecked() throws Exception { writer.setExceptionType(SkippableException.class); StepExecution stepExecution = launchStep("skippableStep"); assertEquals(BatchStatus.COMPLETED, stepExecution.getStatus()); @@ -151,7 +145,7 @@ public void testSkippableChecked() throws Exception { } @Test - public void testNonSkippableUnchecked() throws Exception { + void testNonSkippableUnchecked() throws Exception { writer.setExceptionType(UnexpectedRollbackException.class); StepExecution stepExecution = launchStep("skippableStep"); assertEquals(BatchStatus.FAILED, stepExecution.getStatus()); @@ -160,7 +154,7 @@ public void testNonSkippableUnchecked() throws Exception { } @Test - public void testFatalChecked() throws Exception { + void testFatalChecked() throws Exception { writer.setExceptionType(FatalSkippableException.class); StepExecution stepExecution = launchStep("skippableFatalStep"); assertEquals(BatchStatus.FAILED, stepExecution.getStatus()); @@ -169,7 +163,7 @@ public void testFatalChecked() throws Exception { } @Test - public void testRetryableButNotSkippable() throws Exception { + void testRetryableButNotSkippable() throws Exception { writer.setExceptionType(RuntimeException.class); StepExecution stepExecution = launchStep("retryable"); assertEquals(BatchStatus.FAILED, stepExecution.getStatus()); @@ -179,7 +173,7 @@ public void testRetryableButNotSkippable() throws Exception { } @Test - public void testRetryableSkippable() throws Exception { + void testRetryableSkippable() throws Exception { writer.setExceptionType(SkippableRuntimeException.class); StepExecution stepExecution = launchStep("retryable"); assertEquals(BatchStatus.COMPLETED, stepExecution.getStatus()); @@ -188,7 +182,7 @@ public void testRetryableSkippable() throws Exception { } @Test - public void testRetryableFatal() throws Exception { + void testRetryableFatal() throws Exception { // User wants all exceptions to be retried, but only some are skippable // FatalRuntimeException is not skippable because it is fatal, but is a // subclass of another skippable @@ -201,7 +195,7 @@ public void testRetryableFatal() throws Exception { } @Test - public void testRetryableButNotSkippableChecked() throws Exception { + void testRetryableButNotSkippableChecked() throws Exception { writer.setExceptionType(Exception.class); StepExecution stepExecution = launchStep("retryable"); assertEquals(BatchStatus.FAILED, stepExecution.getStatus()); @@ -211,7 +205,7 @@ public void testRetryableButNotSkippableChecked() throws Exception { } @Test - public void testRetryableSkippableChecked() throws Exception { + void testRetryableSkippableChecked() throws Exception { writer.setExceptionType(SkippableException.class); StepExecution stepExecution = launchStep("retryable"); assertEquals(BatchStatus.COMPLETED, stepExecution.getStatus()); @@ -220,7 +214,7 @@ public void testRetryableSkippableChecked() throws Exception { } @Test - public void testRetryableFatalChecked() throws Exception { + void testRetryableFatalChecked() throws Exception { writer.setExceptionType(FatalSkippableException.class); StepExecution stepExecution = launchStep("retryable"); assertEquals(BatchStatus.FAILED, stepExecution.getStatus()); @@ -231,7 +225,7 @@ public void testRetryableFatalChecked() throws Exception { } @Test - public void testNoRollbackDefaultRollbackException() throws Exception { + void testNoRollbackDefaultRollbackException() throws Exception { // Exception is neither no-rollback nor skippable writer.setExceptionType(Exception.class); StepExecution stepExecution = launchStep("noRollbackDefault"); @@ -244,7 +238,7 @@ public void testNoRollbackDefaultRollbackException() throws Exception { } @Test - public void testNoRollbackDefaultNoRollbackException() throws Exception { + void testNoRollbackDefaultNoRollbackException() throws Exception { // Exception is no-rollback and not skippable writer.setExceptionType(IllegalStateException.class); StepExecution stepExecution = launchStep("noRollbackDefault"); @@ -259,7 +253,7 @@ public void testNoRollbackDefaultNoRollbackException() throws Exception { } @Test - public void testNoRollbackPathology() throws Exception { + void testNoRollbackPathology() throws Exception { // Exception is neither no-rollback nor skippable and no-rollback is // RuntimeException (potentially pathological because other obviously // rollback signalling Exceptions also extend RuntimeException) @@ -273,7 +267,7 @@ public void testNoRollbackPathology() throws Exception { } @Test - public void testNoRollbackSkippableRollbackException() throws Exception { + void testNoRollbackSkippableRollbackException() throws Exception { writer.setExceptionType(SkippableRuntimeException.class); StepExecution stepExecution = launchStep("noRollbackSkippable"); assertEquals(BatchStatus.COMPLETED, stepExecution.getStatus()); @@ -282,7 +276,7 @@ public void testNoRollbackSkippableRollbackException() throws Exception { } @Test - public void testNoRollbackSkippableNoRollbackException() throws Exception { + void testNoRollbackSkippableNoRollbackException() throws Exception { writer.setExceptionType(FatalRuntimeException.class); StepExecution stepExecution = launchStep("noRollbackSkippable"); assertEquals(BatchStatus.COMPLETED, stepExecution.getStatus()); @@ -295,7 +289,7 @@ public void testNoRollbackSkippableNoRollbackException() throws Exception { } @Test - public void testNoRollbackFatalRollbackException() throws Exception { + void testNoRollbackFatalRollbackException() throws Exception { writer.setExceptionType(SkippableRuntimeException.class); StepExecution stepExecution = launchStep("noRollbackFatal"); assertEquals(BatchStatus.FAILED, stepExecution.getStatus()); @@ -304,7 +298,7 @@ public void testNoRollbackFatalRollbackException() throws Exception { } @Test - public void testNoRollbackFatalNoRollbackException() throws Exception { + void testNoRollbackFatalNoRollbackException() throws Exception { // User has asked for no rollback on a fatal exception. What should the // outcome be? As per BATCH-1333 it is interpreted as not skippable, but // retryable if requested. Here it was not requested to be retried, but @@ -321,7 +315,7 @@ public void testNoRollbackFatalNoRollbackException() throws Exception { @Test @DirtiesContext - public void testNoRollbackTaskletRollbackException() throws Exception { + void testNoRollbackTaskletRollbackException() throws Exception { tasklet.setExceptionType(RuntimeException.class); StepExecution stepExecution = launchStep("noRollbackTasklet"); assertEquals(BatchStatus.FAILED, stepExecution.getStatus()); @@ -330,7 +324,7 @@ public void testNoRollbackTaskletRollbackException() throws Exception { @Test @DirtiesContext - public void testNoRollbackTaskletNoRollbackException() throws Exception { + void testNoRollbackTaskletNoRollbackException() throws Exception { tasklet.setExceptionType(SkippableRuntimeException.class); StepExecution stepExecution = launchStep("noRollbackTasklet"); // assertEquals(BatchStatus.FAILED, stepExecution.getStatus()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanNonBufferingTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanNonBufferingTests.java index d233f65e69..975335e290 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanNonBufferingTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanNonBufferingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2021 the original author or authors. + * Copyright 2008-2022 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. @@ -23,8 +23,8 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.JobExecution; @@ -41,31 +41,29 @@ import org.springframework.batch.support.transaction.TransactionAwareProxyFactory; import org.springframework.util.StringUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.mockito.Mockito.mock; -public class FaultTolerantStepFactoryBeanNonBufferingTests { +class FaultTolerantStepFactoryBeanNonBufferingTests { protected final Log logger = LogFactory.getLog(getClass()); - private FaultTolerantStepFactoryBean factory = new FaultTolerantStepFactoryBean<>(); + private final FaultTolerantStepFactoryBean factory = new FaultTolerantStepFactoryBean<>(); - private List items = Arrays.asList("1", "2", "3", "4", "5"); + private final List items = Arrays.asList("1", "2", "3", "4", "5"); - private ListItemReader reader = new ListItemReader<>( + private final ListItemReader reader = new ListItemReader<>( TransactionAwareProxyFactory.createTransactionalList(items)); - private SkipWriterStub writer = new SkipWriterStub(); + private final SkipWriterStub writer = new SkipWriterStub(); private JobExecution jobExecution; private static final SkippableRuntimeException exception = new SkippableRuntimeException("exception in writer"); - int count = 0; - - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { factory.setBeanName("stepName"); factory.setJobRepository(new JobRepositorySupport()); factory.setTransactionManager(new ResourcelessTransactionManager()); @@ -87,7 +85,7 @@ public void setUp() throws Exception { * Check items causing errors are skipped as expected. */ @Test - public void testSkip() throws Exception { + void testSkip() throws Exception { @SuppressWarnings("unchecked") SkipListener skipListener = mock(SkipListener.class); skipListener.onSkipInWrite("3", exception); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanRetryTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanRetryTests.java index 2f5aebe4cb..1a90673aa4 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanRetryTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanRetryTests.java @@ -25,8 +25,8 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; @@ -59,15 +59,15 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.util.StringUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Dave Syer * @author Mahmoud Ben Hassine * */ -public class FaultTolerantStepFactoryBeanRetryTests { +class FaultTolerantStepFactoryBeanRetryTests { protected final Log logger = LogFactory.getLog(getClass()); @@ -97,8 +97,8 @@ public void write(List data) throws Exception { }; @SuppressWarnings("unchecked") - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { EmbeddedDatabase embeddedDatabase = new EmbeddedDatabaseBuilder() .addScript("/org/springframework/batch/core/schema-drop-hsqldb.sql") @@ -130,18 +130,18 @@ public void setUp() throws Exception { } @Test - public void testType() throws Exception { + void testType() { assertTrue(Step.class.isAssignableFrom(factory.getObjectType())); } @SuppressWarnings("cast") @Test - public void testDefaultValue() throws Exception { + void testDefaultValue() throws Exception { assertTrue(factory.getObject() instanceof Step); } @Test - public void testProcessAllItemsWhenErrorInWriterTransformationWhenReaderTransactional() throws Exception { + void testProcessAllItemsWhenErrorInWriterTransformationWhenReaderTransactional() throws Exception { final int RETRY_LIMIT = 3; final List ITEM_LIST = TransactionAwareProxyFactory .createTransactionalList(Arrays.asList("1", "2", "3")); @@ -197,7 +197,7 @@ public Integer process(String item) throws Exception { } @Test - public void testProcessAllItemsWhenErrorInWriter() throws Exception { + void testProcessAllItemsWhenErrorInWriter() throws Exception { final int RETRY_LIMIT = 3; final List ITEM_LIST = Arrays.asList("a", "b", "c"); ItemWriter failingWriter = new ItemWriter() { @@ -245,7 +245,7 @@ public String process(String item) throws Exception { } @Test - public void testNoItemsReprocessedWhenErrorInWriterAndProcessorNotTransactional() throws Exception { + void testNoItemsReprocessedWhenErrorInWriterAndProcessorNotTransactional() throws Exception { ItemWriter failingWriter = new ItemWriter() { @Override public void write(List data) throws Exception { @@ -291,7 +291,7 @@ public String process(String item) throws Exception { */ @SuppressWarnings("unchecked") @Test - public void testSuccessfulRetryWithReadFailure() throws Exception { + void testSuccessfulRetryWithReadFailure() throws Exception { ItemReader provider = new ListItemReader(Arrays.asList("a", "b", "c")) { @Nullable @Override @@ -327,7 +327,7 @@ public String read() { } @Test - public void testRestartAfterFailedWrite() throws Exception { + void testRestartAfterFailedWrite() throws Exception { factory.setSkipLimit(0); factory.setCommitInterval(3); @@ -390,7 +390,7 @@ public void write(List items) throws Exception { } @Test - public void testSkipAndRetry() throws Exception { + void testSkipAndRetry() throws Exception { factory.setSkipLimit(2); ItemReader provider = new ListItemReader(Arrays.asList("a", "b", "c", "d", "e", "f")) { @@ -421,7 +421,7 @@ public String read() { @SuppressWarnings("unchecked") @Test - public void testSkipAndRetryWithWriteFailure() throws Exception { + void testSkipAndRetryWithWriteFailure() throws Exception { factory.setListeners(new StepListener[] { new SkipListener() { @Override @@ -478,7 +478,7 @@ public void write(List item) throws Exception { @SuppressWarnings("unchecked") @Test - public void testSkipAndRetryWithWriteFailureAndNonTrivialCommitInterval() throws Exception { + void testSkipAndRetryWithWriteFailureAndNonTrivialCommitInterval() throws Exception { factory.setCommitInterval(3); factory.setListeners(new StepListener[] { new SkipListener() { @@ -540,7 +540,7 @@ public void write(List item) throws Exception { } @Test - public void testRetryWithNoSkip() throws Exception { + void testRetryWithNoSkip() throws Exception { factory.setRetryLimit(4); factory.setSkipLimit(0); @@ -588,7 +588,7 @@ public void write(List item) throws Exception { @SuppressWarnings("unchecked") @Test - public void testNonSkippableException() throws Exception { + void testNonSkippableException() throws Exception { // Very specific skippable exception factory.setSkippableExceptionClasses(getExceptionMap(UnsupportedOperationException.class)); @@ -623,7 +623,7 @@ public void write(List item) throws Exception { repository.add(stepExecution); step.execute(stepExecution); String message = stepExecution.getFailureExceptions().get(0).getCause().getMessage(); - assertEquals("Wrong message: " + message, "Write error - planned but not skippable.", message); + assertEquals("Write error - planned but not skippable.", message, "Wrong message: " + message); List expectedOutput = Arrays.asList(StringUtils.commaDelimitedListToStringArray("")); assertEquals(expectedOutput, written); @@ -639,7 +639,7 @@ public void write(List item) throws Exception { } @Test - public void testRetryPolicy() throws Exception { + void testRetryPolicy() throws Exception { factory.setRetryPolicy(new SimpleRetryPolicy(4, Collections., Boolean>singletonMap(Exception.class, true))); factory.setSkipLimit(0); @@ -684,7 +684,7 @@ public void write(List item) throws Exception { } @Test - public void testCacheLimitWithRetry() throws Exception { + void testCacheLimitWithRetry() throws Exception { factory.setRetryLimit(2); factory.setCommitInterval(3); // sufficiently high so we never hit it diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanRollbackTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanRollbackTests.java index 1e56ba2d3a..156c18196e 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanRollbackTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanRollbackTests.java @@ -25,9 +25,9 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -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.batch.core.BatchStatus; import org.springframework.batch.core.ChunkListener; @@ -57,15 +57,15 @@ import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.springframework.batch.core.BatchStatus.FAILED; /** * Tests for {@link FaultTolerantStepFactoryBean}. */ -public class FaultTolerantStepFactoryBeanRollbackTests { +class FaultTolerantStepFactoryBeanRollbackTests { protected final Log logger = LogFactory.getLog(getClass()); @@ -84,8 +84,8 @@ public class FaultTolerantStepFactoryBeanRollbackTests { private JobRepository repository; @SuppressWarnings("unchecked") - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { reader = new SkipReaderStub<>(); processor = new SkipProcessorStub<>(); writer = new SkipWriterStub<>(); @@ -124,8 +124,8 @@ public void setUp() throws Exception { repository.add(stepExecution); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() { reader = null; processor = null; writer = null; @@ -133,7 +133,7 @@ public void tearDown() throws Exception { } @Test - public void testBeforeChunkListenerException() throws Exception { + void testBeforeChunkListenerException() throws Exception { factory.setListeners(new StepListener[] { new ExceptionThrowingChunkListener(1) }); Step step = factory.getObject(); step.execute(stepExecution); @@ -147,7 +147,7 @@ public void testBeforeChunkListenerException() throws Exception { } @Test - public void testAfterChunkListenerException() throws Exception { + void testAfterChunkListenerException() throws Exception { factory.setListeners(new StepListener[] { new ExceptionThrowingChunkListener(2) }); Step step = factory.getObject(); step.execute(stepExecution); @@ -161,7 +161,7 @@ public void testAfterChunkListenerException() throws Exception { } @Test - public void testOverrideWithoutChangingRollbackRules() throws Exception { + void testOverrideWithoutChangingRollbackRules() { TransactionAttributeEditor editor = new TransactionAttributeEditor(); editor.setAsText("-RuntimeException"); TransactionAttribute attr = (TransactionAttribute) editor.getValue(); @@ -170,7 +170,7 @@ public void testOverrideWithoutChangingRollbackRules() throws Exception { } @Test - public void testChangeRollbackRules() throws Exception { + void testChangeRollbackRules() { TransactionAttributeEditor editor = new TransactionAttributeEditor(); editor.setAsText("+RuntimeException"); TransactionAttribute attr = (TransactionAttribute) editor.getValue(); @@ -179,7 +179,7 @@ public void testChangeRollbackRules() throws Exception { } @Test - public void testNonDefaultRollbackRules() throws Exception { + void testNonDefaultRollbackRules() { TransactionAttributeEditor editor = new TransactionAttributeEditor(); editor.setAsText("+RuntimeException,+SkippableException"); RuleBasedTransactionAttribute attr = (RuleBasedTransactionAttribute) editor.getValue(); @@ -193,7 +193,7 @@ public void testNonDefaultRollbackRules() throws Exception { * Scenario: Exception in reader that should not cause rollback */ @Test - public void testReaderDefaultNoRollbackOnCheckedException() throws Exception { + void testReaderDefaultNoRollbackOnCheckedException() throws Exception { reader.setItems("1", "2", "3", "4"); reader.setFailures("2", "3"); reader.setExceptionType(SkippableException.class); @@ -211,7 +211,7 @@ public void testReaderDefaultNoRollbackOnCheckedException() throws Exception { */ @SuppressWarnings("unchecked") @Test - public void testReaderAttributesOverrideSkippableNoRollback() throws Exception { + void testReaderAttributesOverrideSkippableNoRollback() throws Exception { reader.setFailures("2", "3"); reader.setItems("1", "2", "3", "4"); reader.setExceptionType(SkippableException.class); @@ -234,7 +234,7 @@ public void testReaderAttributesOverrideSkippableNoRollback() throws Exception { * exception */ @Test - public void testProcessorDefaultRollbackOnCheckedException() throws Exception { + void testProcessorDefaultRollbackOnCheckedException() throws Exception { reader.setItems("1", "2", "3", "4"); processor.setFailures("1", "3"); @@ -252,7 +252,7 @@ public void testProcessorDefaultRollbackOnCheckedException() throws Exception { * Scenario: Exception in processor that should cause rollback */ @Test - public void testProcessorDefaultRollbackOnRuntimeException() throws Exception { + void testProcessorDefaultRollbackOnRuntimeException() throws Exception { reader.setItems("1", "2", "3", "4"); processor.setFailures("1", "3"); @@ -267,7 +267,7 @@ public void testProcessorDefaultRollbackOnRuntimeException() throws Exception { } @Test - public void testNoRollbackInProcessorWhenSkipExceeded() throws Throwable { + void testNoRollbackInProcessorWhenSkipExceeded() throws Throwable { jobExecution = repository.createJobExecution("noRollbackJob", new JobParameters()); @@ -281,7 +281,6 @@ public void testNoRollbackInProcessorWhenSkipExceeded() throws Throwable { processor.clear(); factory.setItemProcessor(processor); - @SuppressWarnings("unchecked") List> exceptions = Arrays.asList(Exception.class); factory.setNoRollbackExceptionClasses(exceptions); @SuppressWarnings("unchecked") @@ -308,7 +307,7 @@ public void testNoRollbackInProcessorWhenSkipExceeded() throws Throwable { } @Test - public void testProcessSkipWithNoRollbackForCheckedException() throws Exception { + void testProcessSkipWithNoRollbackForCheckedException() throws Exception { processor.setFailures("4"); processor.setExceptionType(SkippableException.class); @@ -338,7 +337,7 @@ public void testProcessSkipWithNoRollbackForCheckedException() throws Exception * Scenario: Exception in writer that should not cause rollback and scan */ @Test - public void testWriterDefaultRollbackOnCheckedException() throws Exception { + void testWriterDefaultRollbackOnCheckedException() throws Exception { writer.setFailures("2", "3"); writer.setExceptionType(SkippableException.class); @@ -354,7 +353,7 @@ public void testWriterDefaultRollbackOnCheckedException() throws Exception { * Scenario: Exception in writer that should not cause rollback and scan */ @Test - public void testWriterDefaultRollbackOnError() throws Exception { + void testWriterDefaultRollbackOnError() throws Exception { writer.setFailures("2", "3"); writer.setExceptionType(AssertionError.class); @@ -370,7 +369,7 @@ public void testWriterDefaultRollbackOnError() throws Exception { * Scenario: Exception in writer that should not cause rollback and scan */ @Test - public void testWriterDefaultRollbackOnRuntimeException() throws Exception { + void testWriterDefaultRollbackOnRuntimeException() throws Exception { writer.setFailures("2", "3"); writer.setExceptionType(SkippableRuntimeException.class); @@ -387,7 +386,7 @@ public void testWriterDefaultRollbackOnRuntimeException() throws Exception { * Scenario: Exception in writer that should not cause rollback and scan */ @Test - public void testWriterNoRollbackOnRuntimeException() throws Exception { + void testWriterNoRollbackOnRuntimeException() throws Exception { writer.setFailures("2", "3"); writer.setExceptionType(SkippableRuntimeException.class); @@ -409,7 +408,7 @@ public void testWriterNoRollbackOnRuntimeException() throws Exception { * Scenario: Exception in writer that should not cause rollback and scan */ @Test - public void testWriterNoRollbackOnCheckedException() throws Exception { + void testWriterNoRollbackOnCheckedException() throws Exception { writer.setFailures("2", "3"); writer.setExceptionType(SkippableException.class); @@ -426,7 +425,7 @@ public void testWriterNoRollbackOnCheckedException() throws Exception { } @Test - public void testSkipInProcessor() throws Exception { + void testSkipInProcessor() throws Exception { processor.setFailures("4"); factory.setCommitInterval(30); @@ -442,7 +441,7 @@ public void testSkipInProcessor() throws Exception { } @Test - public void testMultipleSkipsInProcessor() throws Exception { + void testMultipleSkipsInProcessor() throws Exception { processor.setFailures("2", "4"); factory.setCommitInterval(30); @@ -458,7 +457,7 @@ public void testMultipleSkipsInProcessor() throws Exception { } @Test - public void testMultipleSkipsInNonTransactionalProcessor() throws Exception { + void testMultipleSkipsInNonTransactionalProcessor() throws Exception { processor.setFailures("2", "4"); factory.setCommitInterval(30); factory.setProcessorTransactional(false); @@ -475,7 +474,7 @@ public void testMultipleSkipsInNonTransactionalProcessor() throws Exception { } @Test - public void testFilterInProcessor() throws Exception { + void testFilterInProcessor() throws Exception { processor.setFailures("4"); processor.setFilter(true); factory.setCommitInterval(30); @@ -492,7 +491,7 @@ public void testFilterInProcessor() throws Exception { } @Test - public void testSkipInWriter() throws Exception { + void testSkipInWriter() throws Exception { writer.setFailures("4"); factory.setCommitInterval(30); @@ -513,7 +512,7 @@ public void testSkipInWriter() throws Exception { } @Test - public void testSkipInWriterNonTransactionalProcessor() throws Exception { + void testSkipInWriterNonTransactionalProcessor() throws Exception { writer.setFailures("4"); factory.setCommitInterval(30); factory.setProcessorTransactional(false); @@ -529,7 +528,7 @@ public void testSkipInWriterNonTransactionalProcessor() throws Exception { } @Test - public void testSkipInWriterTransactionalReader() throws Exception { + void testSkipInWriterTransactionalReader() throws Exception { writer.setFailures("4"); ItemReader reader = new ListItemReader<>( TransactionAwareProxyFactory.createTransactionalList(Arrays.asList("1", "2", "3", "4", "5"))); @@ -549,7 +548,7 @@ public void testSkipInWriterTransactionalReader() throws Exception { } @Test - public void testMultithreadedSkipInWriter() throws Exception { + void testMultithreadedSkipInWriter() throws Exception { writer.setFailures("1", "2", "3", "4", "5"); factory.setCommitInterval(3); factory.setSkipLimit(10); @@ -566,7 +565,7 @@ public void testMultithreadedSkipInWriter() throws Exception { } @Test - public void testMultipleSkipsInWriter() throws Exception { + void testMultipleSkipsInWriter() throws Exception { writer.setFailures("2", "4"); factory.setCommitInterval(30); @@ -587,7 +586,7 @@ public void testMultipleSkipsInWriter() throws Exception { } @Test - public void testMultipleSkipsInWriterNonTransactionalProcessor() throws Exception { + void testMultipleSkipsInWriterNonTransactionalProcessor() throws Exception { writer.setFailures("2", "4"); factory.setCommitInterval(30); factory.setProcessorTransactional(false); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanTests.java index e9ff018a50..abfeef5cf0 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanTests.java @@ -26,9 +26,8 @@ import org.aopalliance.intercept.MethodInvocation; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.aop.framework.ProxyFactory; import org.springframework.batch.core.BatchStatus; @@ -71,9 +70,10 @@ import org.springframework.test.util.ReflectionTestUtils; import org.springframework.util.StringUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests for {@link FaultTolerantStepFactoryBean}. @@ -84,11 +84,11 @@ public class FaultTolerantStepFactoryBeanTests { private FaultTolerantStepFactoryBean factory; - private SkipReaderStub reader; + private final SkipReaderStub reader; - private SkipProcessorStub processor; + private final SkipProcessorStub processor; - private SkipWriterStub writer; + private final SkipWriterStub writer; private JobExecution jobExecution; @@ -107,12 +107,11 @@ public FaultTolerantStepFactoryBeanTests() throws Exception { } @SuppressWarnings("unchecked") - @Before - public void setUp() throws Exception { - EmbeddedDatabase embeddedDatabase = new EmbeddedDatabaseBuilder() + @BeforeEach + void setUp() throws Exception { + EmbeddedDatabase embeddedDatabase = new EmbeddedDatabaseBuilder().generateUniqueName(true) .addScript("/org/springframework/batch/core/schema-drop-hsqldb.sql") - .addScript("/org/springframework/batch/core/schema-hsqldb-extended.sql").generateUniqueName(true) - .build(); + .addScript("/org/springframework/batch/core/schema-hsqldb-extended.sql").build(); JdbcTransactionManager transactionManager = new JdbcTransactionManager(embeddedDatabase); factory = new FaultTolerantStepFactoryBean<>(); @@ -137,7 +136,7 @@ public void setUp() throws Exception { JobRepositoryFactoryBean repositoryFactoryBean = new JobRepositoryFactoryBean(); repositoryFactoryBean.setDataSource(embeddedDatabase); repositoryFactoryBean.setTransactionManager(transactionManager); - repositoryFactoryBean.setMaxVarCharLength(10000); + repositoryFactoryBean.setMaxVarCharLength(20000); repositoryFactoryBean.afterPropertiesSet(); repository = repositoryFactoryBean.getObject(); factory.setJobRepository(repository); @@ -148,26 +147,26 @@ public void setUp() throws Exception { } @Test - public void testMandatoryReader() { + void testMandatoryReader() { // given factory = new FaultTolerantStepFactoryBean<>(); factory.setItemWriter(writer); // when - final Exception expectedException = Assert.assertThrows(IllegalStateException.class, factory::getObject); + final Exception expectedException = assertThrows(IllegalStateException.class, factory::getObject); // then assertEquals("ItemReader must be provided", expectedException.getMessage()); } @Test - public void testMandatoryWriter() throws Exception { + void testMandatoryWriter() { // given factory = new FaultTolerantStepFactoryBean<>(); factory.setItemReader(reader); // when - final Exception expectedException = Assert.assertThrows(IllegalStateException.class, factory::getObject); + final Exception expectedException = assertThrows(IllegalStateException.class, factory::getObject); // then assertEquals("ItemWriter must be provided", expectedException.getMessage()); @@ -179,7 +178,7 @@ public void testMandatoryWriter() throws Exception { */ @SuppressWarnings("unchecked") @Test - public void testNonSkippableExceptionOnRead() throws Exception { + void testNonSkippableExceptionOnRead() throws Exception { reader.setFailures("2"); // nothing is skippable @@ -198,7 +197,7 @@ public void testNonSkippableExceptionOnRead() throws Exception { @SuppressWarnings("unchecked") @Test - public void testNonSkippableException() throws Exception { + void testNonSkippableException() throws Exception { // nothing is skippable factory.setSkippableExceptionClasses(getExceptionMap(NonExistentException.class)); factory.setCommitInterval(1); @@ -222,7 +221,7 @@ public void testNonSkippableException() throws Exception { * Check items causing errors are skipped as expected. */ @Test - public void testReadSkip() throws Exception { + void testReadSkip() throws Exception { reader.setFailures("2"); Step step = factory.getObject(); @@ -251,7 +250,7 @@ public void testReadSkip() throws Exception { * Check items causing errors are skipped as expected. */ @Test - public void testReadSkipWithPolicy() throws Exception { + void testReadSkipWithPolicy() throws Exception { // Should be ignored factory.setSkipLimit(0); factory.setSkipPolicy(new LimitCheckingItemSkipPolicy(2, @@ -263,7 +262,7 @@ public void testReadSkipWithPolicy() throws Exception { * Check items causing errors are skipped as expected. */ @Test - public void testReadSkipWithPolicyExceptionInReader() throws Exception { + void testReadSkipWithPolicyExceptionInReader() throws Exception { // Should be ignored factory.setSkipLimit(0); @@ -291,7 +290,7 @@ public boolean shouldSkip(Throwable t, long skipCount) throws SkipLimitExceededE * Check items causing errors are skipped as expected. */ @Test - public void testReadSkipWithPolicyExceptionInWriter() throws Exception { + void testReadSkipWithPolicyExceptionInWriter() throws Exception { // Should be ignored factory.setSkipLimit(0); @@ -319,7 +318,7 @@ public boolean shouldSkip(Throwable t, long skipCount) throws SkipLimitExceededE * Check to make sure that ItemStreamException can be skipped. (see BATCH-915) */ @Test - public void testReadSkipItemStreamException() throws Exception { + void testReadSkipItemStreamException() throws Exception { reader.setFailures("2"); reader.setExceptionType(ItemStreamException.class); @@ -353,7 +352,7 @@ public void testReadSkipItemStreamException() throws Exception { * Check items causing errors are skipped as expected. */ @Test - public void testProcessSkip() throws Exception { + void testProcessSkip() throws Exception { processor.setFailures("4"); writer.setFailures("4"); @@ -380,7 +379,7 @@ public void testProcessSkip() throws Exception { } @Test - public void testProcessFilter() throws Exception { + void testProcessFilter() throws Exception { processor.setFailures("4"); processor.setFilter(true); ItemProcessListenerStub listenerStub = new ItemProcessListenerStub<>(); @@ -412,7 +411,7 @@ public void testProcessFilter() throws Exception { * Check items causing errors are skipped as expected. */ @Test - public void testWriteSkip() throws Exception { + void testWriteSkip() throws Exception { writer.setFailures("4"); Step step = factory.getObject(); @@ -442,7 +441,7 @@ public void testWriteSkip() throws Exception { * skippable (note the fatal exception is also classified as rollback). */ @Test - public void testFatalException() throws Exception { + void testFatalException() throws Exception { reader.setFailures("2"); Map, Boolean> map = new HashMap<>(); @@ -461,7 +460,7 @@ public void write(List items) { step.execute(stepExecution); String message = stepExecution.getFailureExceptions().get(0).getCause().getMessage(); - assertEquals("Wrong message: ", "Ouch!", message); + assertEquals("Ouch!", message, "Wrong message: " + message); assertStepExecutionsAreEqual(stepExecution, repository.getLastStepExecution(jobExecution.getJobInstance(), step.getName())); } @@ -470,7 +469,7 @@ public void write(List items) { * Check items causing errors are skipped as expected. */ @Test - public void testSkipOverLimit() throws Exception { + void testSkipOverLimit() throws Exception { reader.setFailures("2"); writer.setFailures("4"); @@ -498,7 +497,7 @@ public void testSkipOverLimit() throws Exception { */ @SuppressWarnings("unchecked") @Test - public void testSkipOverLimitOnRead() throws Exception { + void testSkipOverLimitOnRead() throws Exception { reader.setItems(StringUtils.commaDelimitedListToStringArray("1,2,3,4,5,6")); reader.setFailures(StringUtils.commaDelimitedListToStringArray("2,3,5")); @@ -532,7 +531,7 @@ public void testSkipOverLimitOnRead() throws Exception { * Check items causing errors are skipped as expected. */ @Test - public void testSkipOverLimitOnReadWithListener() throws Exception { + void testSkipOverLimitOnReadWithListener() throws Exception { reader.setFailures("1", "3", "5"); writer.setFailures(); @@ -566,7 +565,7 @@ public void onSkipInRead(Throwable t) { */ @SuppressWarnings("unchecked") @Test - public void testSkipListenerFailsOnRead() throws Exception { + void testSkipListenerFailsOnRead() throws Exception { reader.setItems(StringUtils.commaDelimitedListToStringArray("1,2,3,4,5,6")); reader.setFailures(StringUtils.commaDelimitedListToStringArray("2,3,5")); @@ -602,7 +601,7 @@ public void onSkipInRead(Throwable t) { */ @SuppressWarnings("unchecked") @Test - public void testSkipListenerFailsOnWrite() throws Exception { + void testSkipListenerFailsOnWrite() throws Exception { reader.setItems(StringUtils.commaDelimitedListToStringArray("1,2,3,4,5,6")); writer.setFailures("4"); @@ -632,7 +631,7 @@ public void onSkipInWrite(String item, Throwable t) { * Check items causing errors are skipped as expected. */ @Test - public void testSkipOnReadNotDoubleCounted() throws Exception { + void testSkipOnReadNotDoubleCounted() throws Exception { reader.setItems(StringUtils.commaDelimitedListToStringArray("1,2,3,4,5,6")); reader.setFailures(StringUtils.commaDelimitedListToStringArray("2,3,5")); @@ -662,7 +661,7 @@ public void testSkipOnReadNotDoubleCounted() throws Exception { * Check items causing errors are skipped as expected. */ @Test - public void testSkipOnWriteNotDoubleCounted() throws Exception { + void testSkipOnWriteNotDoubleCounted() throws Exception { reader.setItems(StringUtils.commaDelimitedListToStringArray("1,2,3,4,5,6,7")); reader.setFailures(StringUtils.commaDelimitedListToStringArray("2,3")); @@ -687,7 +686,7 @@ public void testSkipOnWriteNotDoubleCounted() throws Exception { @SuppressWarnings("unchecked") @Test - public void testDefaultSkipPolicy() throws Exception { + void testDefaultSkipPolicy() throws Exception { reader.setItems("a", "b", "c"); reader.setFailures("b"); @@ -709,7 +708,7 @@ public void testDefaultSkipPolicy() throws Exception { */ @SuppressWarnings("unchecked") @Test - public void testSkipOverLimitOnReadWithAllSkipsAtEnd() throws Exception { + void testSkipOverLimitOnReadWithAllSkipsAtEnd() throws Exception { reader.setItems(StringUtils.commaDelimitedListToStringArray("1,2,3,4,5,6,7,8,9,10,11,12,13,14,15")); reader.setFailures(StringUtils.commaDelimitedListToStringArray("6,12,13,14,15")); @@ -723,9 +722,9 @@ public void testSkipOverLimitOnReadWithAllSkipsAtEnd() throws Exception { step.execute(stepExecution); assertEquals(BatchStatus.FAILED, stepExecution.getStatus()); - assertEquals("bad skip count", 3, stepExecution.getSkipCount()); - assertEquals("bad read skip count", 2, stepExecution.getReadSkipCount()); - assertEquals("bad write skip count", 1, stepExecution.getWriteSkipCount()); + assertEquals(3, stepExecution.getSkipCount(), "bad skip count"); + assertEquals(2, stepExecution.getReadSkipCount(), "bad read skip count"); + assertEquals(1, stepExecution.getWriteSkipCount(), "bad write skip count"); // writer did not skip "6" as it never made it to writer, only "4" did assertFalse(reader.getRead().contains("6")); @@ -739,7 +738,7 @@ public void testSkipOverLimitOnReadWithAllSkipsAtEnd() throws Exception { } @Test - public void testReprocessingAfterWriterRollback() throws Exception { + void testReprocessingAfterWriterRollback() throws Exception { reader.setItems("1", "2", "3", "4"); writer.setFailures("4"); @@ -758,7 +757,7 @@ public void testReprocessingAfterWriterRollback() throws Exception { } @Test - public void testAutoRegisterItemListeners() throws Exception { + void testAutoRegisterItemListeners() throws Exception { reader.setFailures("2"); final List listenerCalls = new ArrayList<>(); @@ -848,7 +847,7 @@ public void afterChunkError(ChunkContext context) { assertEquals(BatchStatus.COMPLETED, stepExecution.getStatus()); for (int i = 1; i <= 6; i++) { - assertTrue("didn't call listener " + i, listenerCalls.contains(i)); + assertTrue(listenerCalls.contains(i), "didn't call listener " + i); } } @@ -856,7 +855,7 @@ public void afterChunkError(ChunkContext context) { * Check ItemStream is opened */ @Test - public void testItemStreamOpenedEvenWithTaskExecutor() throws Exception { + void testItemStreamOpenedEvenWithTaskExecutor() throws Exception { writer.setFailures("4"); ItemReader reader = new AbstractItemStreamItemReader() { @@ -895,7 +894,7 @@ public String read() { * Check ItemStream is opened */ @Test - public void testNestedItemStreamOpened() throws Exception { + void testNestedItemStreamOpened() throws Exception { writer.setFailures("4"); ItemStreamReader reader = new ItemStreamReader() { @@ -957,7 +956,7 @@ public String read() throws Exception, UnexpectedInputException, ParseException */ @SuppressWarnings("unchecked") @Test - public void testProxiedItemStreamOpened() throws Exception { + void testProxiedItemStreamOpened() throws Exception { writer.setFailures("4"); ItemStreamReader reader = new ItemStreamReader() { @@ -1057,7 +1056,7 @@ private void assertStepExecutionsAreEqual(StepExecution expected, StepExecution * expected: false; default classification */ @Test - public void testSkippableSubset_unclassified() throws Exception { + void testSkippableSubset_unclassified() throws Exception { assertFalse(getSkippableSubsetSkipPolicy().shouldSkip(new RuntimeException(), 0)); } @@ -1067,7 +1066,7 @@ public void testSkippableSubset_unclassified() throws Exception { * expected: true */ @Test - public void testSkippableSubset_skippable() throws Exception { + void testSkippableSubset_skippable() throws Exception { assertTrue(getSkippableSubsetSkipPolicy().shouldSkip(new WriteFailedException(""), 0)); } @@ -1077,7 +1076,7 @@ public void testSkippableSubset_skippable() throws Exception { * expected: false */ @Test - public void testSkippableSubset_fatal() throws Exception { + void testSkippableSubset_fatal() throws Exception { assertFalse(getSkippableSubsetSkipPolicy().shouldSkip(new WriterNotOpenException(""), 0)); } @@ -1087,7 +1086,7 @@ public void testSkippableSubset_fatal() throws Exception { * expected: false; default classification */ @Test - public void testFatalSubsetUnclassified() throws Exception { + void testFatalSubsetUnclassified() throws Exception { assertFalse(getFatalSubsetSkipPolicy().shouldSkip(new RuntimeException(), 0)); } @@ -1097,7 +1096,7 @@ public void testFatalSubsetUnclassified() throws Exception { * expected: true */ @Test - public void testFatalSubsetSkippable() throws Exception { + void testFatalSubsetSkippable() throws Exception { assertTrue(getFatalSubsetSkipPolicy().shouldSkip(new WriterNotOpenException(""), 0)); } @@ -1107,7 +1106,7 @@ public void testFatalSubsetSkippable() throws Exception { * expected: false */ @Test - public void testFatalSubsetFatal() throws Exception { + void testFatalSubsetFatal() throws Exception { assertFalse(getFatalSubsetSkipPolicy().shouldSkip(new WriteFailedException(""), 0)); } @@ -1143,7 +1142,6 @@ private Map, Boolean> getExceptionMap(Class writer = new SkipWriterStub<>(); FaultTolerantStepFactoryBean factory = new FaultTolerantStepFactoryBean<>(); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/RepeatOperationsStepFactoryBeanTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/RepeatOperationsStepFactoryBeanTests.java index 8a6801af1b..c97d974cb3 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/RepeatOperationsStepFactoryBeanTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/RepeatOperationsStepFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2013 the original author or authors. + * Copyright 2006-2022 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. @@ -18,7 +18,8 @@ import java.util.ArrayList; import java.util.List; -import junit.framework.TestCase; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInstance; @@ -34,20 +35,23 @@ import org.springframework.batch.repeat.RepeatStatus; import org.springframework.batch.support.transaction.ResourcelessTransactionManager; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * @author Dave Syer * */ -public class RepeatOperationsStepFactoryBeanTests extends TestCase { +class RepeatOperationsStepFactoryBeanTests { - private SimpleStepFactoryBean factory = new SimpleStepFactoryBean<>(); + private final SimpleStepFactoryBean factory = new SimpleStepFactoryBean<>(); private List list; - private JobExecution jobExecution = new JobExecution(new JobInstance(0L, "job"), new JobParameters()); + private final JobExecution jobExecution = new JobExecution(new JobInstance(0L, "job"), new JobParameters()); - @Override - protected void setUp() throws Exception { + @BeforeEach + void setUp() { factory.setBeanName("RepeatOperationsStep"); factory.setItemReader(new ListItemReader<>(new ArrayList<>())); factory.setItemWriter(new EmptyItemWriter<>()); @@ -55,16 +59,19 @@ protected void setUp() throws Exception { factory.setTransactionManager(new ResourcelessTransactionManager()); } - public void testType() throws Exception { + @Test + void testType() { assertTrue(Step.class.isAssignableFrom(factory.getObjectType())); } + @Test @SuppressWarnings("cast") - public void testDefaultValue() throws Exception { + void testDefaultValue() throws Exception { assertTrue(factory.getObject() instanceof Step); } - public void testStepOperationsWithoutChunkListener() throws Exception { + @Test + void testStepOperationsWithoutChunkListener() throws Exception { factory.setItemReader(new ListItemReader<>(new ArrayList<>())); factory.setItemWriter(new EmptyItemWriter<>()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/ScriptItemProcessorTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/ScriptItemProcessorTests.java index 0e36fd3703..3b86a7bcf2 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/ScriptItemProcessorTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/ScriptItemProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2022 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. @@ -15,15 +15,13 @@ */ package org.springframework.batch.core.step.item; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.batch.item.ItemWriter; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.util.Assert; import java.util.List; @@ -37,9 +35,8 @@ * @author Chris Schaefer * @since 3.1 */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -public class ScriptItemProcessorTests { +@SpringJUnitConfig +class ScriptItemProcessorTests { @Autowired private Job job; @@ -48,7 +45,7 @@ public class ScriptItemProcessorTests { private JobLauncher jobLauncher; @Test - public void testScriptProcessorJob() throws Exception { + void testScriptProcessorJob() throws Exception { jobLauncher.run(job, new JobParameters()); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleChunkProcessorTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleChunkProcessorTests.java index fcfaca0b09..7b1f48779b 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleChunkProcessorTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleChunkProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2019 the original author or authors. + * Copyright 2008-2022 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. @@ -15,14 +15,14 @@ */ package org.springframework.batch.core.step.item; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.Arrays; 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.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInstance; import org.springframework.batch.core.JobParameters; @@ -32,9 +32,9 @@ import org.springframework.batch.item.ItemWriter; import org.springframework.lang.Nullable; -public class SimpleChunkProcessorTests { +class SimpleChunkProcessorTests { - private SimpleChunkProcessor processor = new SimpleChunkProcessor<>( + private final SimpleChunkProcessor processor = new SimpleChunkProcessor<>( new ItemProcessor() { @Nullable @Override @@ -54,18 +54,18 @@ public void write(List items) throws Exception { } }); - private StepContribution contribution = new StepContribution( + private final StepContribution contribution = new StepContribution( new StepExecution("foo", new JobExecution(new JobInstance(123L, "job"), new JobParameters()))); - private List list = new ArrayList<>(); + private final List list = new ArrayList<>(); - @Before - public void setUp() { + @BeforeEach + void setUp() { list.clear(); } @Test - public void testProcess() throws Exception { + void testProcess() throws Exception { Chunk chunk = new Chunk<>(); chunk.add("foo"); chunk.add("err"); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleChunkProviderTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleChunkProviderTests.java index b9b290b1cb..b4161133c9 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleChunkProviderTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleChunkProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2013 the original author or authors. + * Copyright 2008-2022 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. @@ -15,12 +15,12 @@ */ package org.springframework.batch.core.step.item; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.Arrays; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInstance; import org.springframework.batch.core.JobParameters; @@ -29,15 +29,15 @@ import org.springframework.batch.item.support.ListItemReader; import org.springframework.batch.repeat.support.RepeatTemplate; -public class SimpleChunkProviderTests { +class SimpleChunkProviderTests { private SimpleChunkProvider provider; - private StepContribution contribution = new StepContribution( + private final StepContribution contribution = new StepContribution( new StepExecution("foo", new JobExecution(new JobInstance(123L, "job"), new JobParameters()))); @Test - public void testProvide() throws Exception { + void testProvide() throws Exception { provider = new SimpleChunkProvider<>(new ListItemReader<>(Arrays.asList("foo", "bar")), new RepeatTemplate()); Chunk chunk = provider.provide(contribution); assertNotNull(chunk); @@ -45,7 +45,7 @@ public void testProvide() throws Exception { } @Test - public void testProvideWithOverflow() throws Exception { + void testProvideWithOverflow() throws Exception { provider = new SimpleChunkProvider(new ListItemReader<>(Arrays.asList("foo", "bar")), new RepeatTemplate()) { @Override diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleRetryExceptionHandlerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleRetryExceptionHandlerTests.java index 499350b30b..6a2770a26e 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleRetryExceptionHandlerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleRetryExceptionHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2013 the original author or authors. + * Copyright 2006-2022 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. @@ -17,9 +17,11 @@ import java.util.Collection; import java.util.Collections; +import java.util.Set; -import junit.framework.TestCase; - +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.repeat.RepeatContext; import org.springframework.batch.repeat.context.RepeatContextSupport; import org.springframework.batch.repeat.exception.SimpleLimitExceptionHandler; @@ -29,55 +31,39 @@ import org.springframework.retry.policy.AlwaysRetryPolicy; import org.springframework.retry.policy.NeverRetryPolicy; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + /** * @author Dave Syer * */ -public class SimpleRetryExceptionHandlerTests extends TestCase { +class SimpleRetryExceptionHandlerTests { - private RepeatContext context = new RepeatContextSupport(new RepeatContextSupport(null)); + private final RepeatContext context = new RepeatContextSupport(new RepeatContextSupport(null)); - /* - * (non-Javadoc) - * - * @see junit.framework.TestCase#setUp() - */ - @Override - protected void setUp() throws Exception { + @BeforeEach + void setUp() { RepeatSynchronizationManager.register(context); } - /* - * (non-Javadoc) - * - * @see junit.framework.TestCase#tearDown() - */ - @Override - protected void tearDown() throws Exception { + @AfterEach + void tearDown() { RepeatSynchronizationManager.clear(); } - /** - * Test method for - * {@link org.springframework.batch.core.step.item.SimpleRetryExceptionHandler#handleException(org.springframework.batch.repeat.RepeatContext, java.lang.Throwable)} - * . - */ - public void testRethrowWhenRetryExhausted() throws Throwable { + @Test + void testRethrowWhenRetryExhausted() { RetryPolicy retryPolicy = new NeverRetryPolicy(); RuntimeException ex = new RuntimeException("foo"); - SimpleRetryExceptionHandler handler = getHandlerAfterRetry(retryPolicy, ex, - Collections.>singleton(Error.class)); + SimpleRetryExceptionHandler handler = getHandlerAfterRetry(retryPolicy, ex, Set.of(Error.class)); // Then pretend to handle the exception in the parent context... - try { - handler.handleException(context.getParent(), ex); - fail("Expected RuntimeException"); - } - catch (RuntimeException e) { - assertEquals(ex, e); - } + Exception exception = assertThrows(RuntimeException.class, + () -> handler.handleException(context.getParent(), ex)); + assertEquals(ex, exception); assertEquals(0, context.attributeNames().length); // One for the retry exhausted flag and one for the counter in the @@ -85,12 +71,8 @@ public void testRethrowWhenRetryExhausted() throws Throwable { assertEquals(2, context.getParent().attributeNames().length); } - /** - * Test method for - * {@link org.springframework.batch.core.step.item.SimpleRetryExceptionHandler#handleException(org.springframework.batch.repeat.RepeatContext, java.lang.Throwable)} - * . - */ - public void testNoRethrowWhenRetryNotExhausted() throws Throwable { + @Test + void testNoRethrowWhenRetryNotExhausted() throws Throwable { RetryPolicy retryPolicy = new AlwaysRetryPolicy(); RuntimeException ex = new RuntimeException("foo"); @@ -105,12 +87,8 @@ public void testNoRethrowWhenRetryNotExhausted() throws Throwable { assertEquals(0, context.getParent().attributeNames().length); } - /** - * Test method for - * {@link org.springframework.batch.core.step.item.SimpleRetryExceptionHandler#handleException(org.springframework.batch.repeat.RepeatContext, java.lang.Throwable)} - * . - */ - public void testRethrowWhenFatal() throws Throwable { + @Test + void testRethrowWhenFatal() { RetryPolicy retryPolicy = new AlwaysRetryPolicy(); RuntimeException ex = new RuntimeException("foo"); @@ -119,24 +97,15 @@ public void testRethrowWhenFatal() throws Throwable { Collections.>singleton(RuntimeException.class)); // Then pretend to handle the exception in the parent context... - try { - handler.handleException(context.getParent(), ex); - fail("Expected RuntimeException"); - } - catch (RuntimeException e) { - assertEquals(ex, e); - } + Exception exception = assertThrows(RuntimeException.class, + () -> handler.handleException(context.getParent(), ex)); + assertEquals(ex, exception); assertEquals(0, context.attributeNames().length); // One for the counter in the delegate exception handler assertEquals(1, context.getParent().attributeNames().length); } - /** - * @param retryPolicy - * @param ex - * @return - */ private SimpleRetryExceptionHandler getHandlerAfterRetry(RetryPolicy retryPolicy, RuntimeException ex, Collection> fatalExceptions) { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleStepFactoryBeanTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleStepFactoryBeanTests.java index 84678b6550..0e2a3ef561 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleStepFactoryBeanTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleStepFactoryBeanTests.java @@ -16,19 +16,18 @@ package org.springframework.batch.core.step.item; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ChunkListener; import org.springframework.batch.core.ItemProcessListener; @@ -63,15 +62,15 @@ /** * Tests for {@link SimpleStepFactoryBean}. */ -public class SimpleStepFactoryBeanTests { +class SimpleStepFactoryBeanTests { - private List listened = new ArrayList<>(); + private final List listened = new ArrayList<>(); private JobRepository repository; - private List written = new ArrayList<>(); + private final List written = new ArrayList<>(); - private ItemWriter writer = new ItemWriter() { + private final ItemWriter writer = new ItemWriter() { @Override public void write(List data) throws Exception { written.addAll(data); @@ -80,10 +79,10 @@ public void write(List data) throws Exception { private ItemReader reader = new ListItemReader<>(Arrays.asList("a", "b", "c")); - private SimpleJob job = new SimpleJob(); + private final SimpleJob job = new SimpleJob(); - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { EmbeddedDatabase embeddedDatabase = new EmbeddedDatabaseBuilder() .addScript("/org/springframework/batch/core/schema-drop-hsqldb.sql") .addScript("/org/springframework/batch/core/schema-hsqldb.sql").generateUniqueName(true).build(); @@ -98,39 +97,40 @@ public void setUp() throws Exception { job.setBeanName("simpleJob"); } - @Test(expected = IllegalStateException.class) - public void testMandatoryProperties() throws Exception { - new SimpleStepFactoryBean().getObject(); + @Test + void testMandatoryProperties() { + SimpleStepFactoryBean factoryBean = new SimpleStepFactoryBean<>(); + assertThrows(IllegalStateException.class, factoryBean::getObject); } @Test - public void testMandatoryReader() { + void testMandatoryReader() { // given SimpleStepFactoryBean factory = new SimpleStepFactoryBean<>(); factory.setItemWriter(writer); // when - final Exception expectedException = Assert.assertThrows(IllegalStateException.class, factory::getObject); + final Exception expectedException = assertThrows(IllegalStateException.class, factory::getObject); // then assertEquals("ItemReader must be provided", expectedException.getMessage()); } @Test - public void testMandatoryWriter() { + void testMandatoryWriter() { // given SimpleStepFactoryBean factory = new SimpleStepFactoryBean<>(); factory.setItemReader(reader); // when - final Exception expectedException = Assert.assertThrows(IllegalStateException.class, factory::getObject); + final Exception expectedException = assertThrows(IllegalStateException.class, factory::getObject); // then assertEquals("ItemWriter must be provided", expectedException.getMessage()); } @Test - public void testSimpleJob() throws Exception { + void testSimpleJob() throws Exception { job.setSteps(new ArrayList<>()); AbstractStep step = (AbstractStep) getStepFactory("foo", "bar").getObject(); @@ -149,7 +149,7 @@ public void testSimpleJob() throws Exception { } @Test - public void testSimpleConcurrentJob() throws Exception { + void testSimpleConcurrentJob() throws Exception { SimpleStepFactoryBean factory = getStepFactory("foo", "bar"); factory.setTaskExecutor(new SimpleAsyncTaskExecutor()); @@ -168,7 +168,7 @@ public void testSimpleConcurrentJob() throws Exception { } @Test - public void testSimpleJobWithItemListeners() throws Exception { + void testSimpleJobWithItemListeners() throws Exception { SimpleStepFactoryBean factory = getStepFactory(new String[] { "foo", "bar", "spam" }); @@ -207,7 +207,7 @@ public void onWriteError(Exception ex, List item) { } @Test - public void testExceptionTerminates() throws Exception { + void testExceptionTerminates() throws Exception { SimpleStepFactoryBean factory = getStepFactory(new String[] { "foo", "bar", "spam" }); factory.setBeanName("exceptionStep"); factory.setItemWriter(new ItemWriter() { @@ -227,7 +227,7 @@ public void write(List data) throws Exception { } @Test - public void testExceptionHandler() throws Exception { + void testExceptionHandler() throws Exception { SimpleStepFactoryBean factory = getStepFactory(new String[] { "foo", "bar", "spam" }); factory.setBeanName("exceptionStep"); SimpleLimitExceptionHandler exceptionHandler = new SimpleLimitExceptionHandler(1); @@ -254,7 +254,7 @@ public void write(List data) throws Exception { } @Test - public void testChunkListeners() throws Exception { + void testChunkListeners() throws Exception { String[] items = new String[] { "1", "2", "3", "4", "5", "6", "7", "error" }; int commitInterval = 3; @@ -333,7 +333,7 @@ public void afterChunkError(ChunkContext context) { assertEquals(expectedListenerCallCount, chunkListener.beforeCount); assertEquals(1, chunkListener.failedCount); assertEquals("1234123415", writeListener.trail); - assertTrue("Listener order not as expected: " + writeListener.trail, writeListener.trail.startsWith("1234")); + assertTrue(writeListener.trail.startsWith("1234"), "Listener order not as expected: " + writeListener.trail); } /** @@ -341,7 +341,7 @@ public void afterChunkError(ChunkContext context) { * @throws Exception */ @Test - public void testCommitIntervalMustBeGreaterThanZero() throws Exception { + void testCommitIntervalMustBeGreaterThanZero() throws Exception { SimpleStepFactoryBean factory = getStepFactory("foo"); // nothing wrong here factory.getObject(); @@ -349,13 +349,7 @@ public void testCommitIntervalMustBeGreaterThanZero() throws Exception { factory = getStepFactory("foo"); // but exception expected after setting commit interval to value < 0 factory.setCommitInterval(-1); - try { - factory.getObject(); - fail(); - } - catch (IllegalStateException e) { - // expected - } + assertThrows(IllegalStateException.class, factory::getObject); } /** @@ -363,25 +357,18 @@ public void testCommitIntervalMustBeGreaterThanZero() throws Exception { * @throws Exception */ @Test - public void testCommitIntervalAndCompletionPolicyBothSet() throws Exception { + void testCommitIntervalAndCompletionPolicyBothSet() { SimpleStepFactoryBean factory = getStepFactory("foo"); // but exception expected after setting commit interval and completion // policy factory.setCommitInterval(1); factory.setChunkCompletionPolicy(new SimpleCompletionPolicy(2)); - try { - factory.getObject(); - fail(); - } - catch (IllegalStateException e) { - // expected - } - + assertThrows(IllegalStateException.class, factory::getObject); } @Test - public void testAutoRegisterItemListeners() throws Exception { + void testAutoRegisterItemListeners() throws Exception { SimpleStepFactoryBean factory = getStepFactory(new String[] { "foo", "bar", "spam" }); @@ -469,12 +456,12 @@ public void afterChunkError(ChunkContext context) { assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus()); for (String type : new String[] { "read", "write", "process", "chunk" }) { - assertTrue("Missing listener call: " + type + " from " + listenerCalls, listenerCalls.contains(type)); + assertTrue(listenerCalls.contains(type), "Missing listener call: " + type + " from " + listenerCalls); } } @Test - public void testAutoRegisterItemListenersNoDoubleCounting() throws Exception { + void testAutoRegisterItemListenersNoDoubleCounting() throws Exception { SimpleStepFactoryBean factory = getStepFactory(new String[] { "foo", "bar", "spam" }); @@ -518,7 +505,7 @@ public void onWriteError(Exception exception, List items) { } - private SimpleStepFactoryBean getStepFactory(String... args) throws Exception { + private SimpleStepFactoryBean getStepFactory(String... args) { SimpleStepFactoryBean factory = new SimpleStepFactoryBean<>(); List items = new ArrayList<>(); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SkipWrapperTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SkipWrapperTests.java index b2977f5c4a..32a3cf6678 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SkipWrapperTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SkipWrapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,27 +15,28 @@ */ package org.springframework.batch.core.step.item; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author Dave Syer * */ -public class SkipWrapperTests { +class SkipWrapperTests { - private Exception exception = new RuntimeException(); + private final Exception exception = new RuntimeException(); /** * Test method for {@link SkipWrapper#SkipWrapper(java.lang.Object)}. */ @Test - public void testItemWrapperT() { + void testItemWrapperT() { SkipWrapper wrapper = new SkipWrapper<>("foo"); assertEquals("foo", wrapper.getItem()); - assertEquals(null, wrapper.getException()); + assertNull(wrapper.getException()); } /** @@ -43,7 +44,7 @@ public void testItemWrapperT() { * {@link org.springframework.batch.core.step.item.SkipWrapper#SkipWrapper(java.lang.Object, java.lang.Throwable)}. */ @Test - public void testItemWrapperTException() { + void testItemWrapperTException() { SkipWrapper wrapper = new SkipWrapper<>("foo", exception); assertEquals("foo", wrapper.getItem()); assertEquals(exception, wrapper.getException()); @@ -54,9 +55,9 @@ public void testItemWrapperTException() { * {@link org.springframework.batch.core.step.item.SkipWrapper#toString()}. */ @Test - public void testToString() { + void testToString() { SkipWrapper wrapper = new SkipWrapper<>("foo"); - assertTrue("foo", wrapper.toString().contains("foo")); + assertTrue(wrapper.toString().contains("foo"), "foo"); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/TaskletStepExceptionTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/TaskletStepExceptionTests.java index 481b927202..d869fdac9d 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/TaskletStepExceptionTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/TaskletStepExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2021 the original author or authors. + * Copyright 2008-2022 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. @@ -15,8 +15,8 @@ */ package org.springframework.batch.core.step.item; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInstance; @@ -47,9 +47,9 @@ import java.util.Collection; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.springframework.batch.core.BatchStatus.COMPLETED; import static org.springframework.batch.core.BatchStatus.FAILED; import static org.springframework.batch.core.BatchStatus.STOPPED; @@ -64,7 +64,7 @@ * @author Mahmoud Ben Hassine * */ -public class TaskletStepExceptionTests { +class TaskletStepExceptionTests { TaskletStep taskletStep; @@ -76,8 +76,8 @@ public class TaskletStepExceptionTests { static JobInterruptedException interruptedException = new JobInterruptedException(""); - @Before - public void init() { + @BeforeEach + void init() { taskletStep = new TaskletStep(); taskletStep.setTasklet(new ExceptionTasklet()); jobRepository = new UpdateCountingJobRepository(); @@ -90,14 +90,14 @@ public void init() { } @Test - public void testApplicationException() throws Exception { + void testApplicationException() throws Exception { taskletStep.execute(stepExecution); assertEquals(FAILED, stepExecution.getStatus()); assertEquals(FAILED.toString(), stepExecution.getExitStatus().getExitCode()); } @Test - public void testInterrupted() throws Exception { + void testInterrupted() throws Exception { taskletStep.setStepExecutionListeners(new StepExecutionListener[] { new InterruptionListener() }); taskletStep.execute(stepExecution); assertEquals(STOPPED, stepExecution.getStatus()); @@ -105,7 +105,7 @@ public void testInterrupted() throws Exception { } @Test - public void testInterruptedWithCustomStatus() throws Exception { + void testInterruptedWithCustomStatus() throws Exception { taskletStep.setTasklet(new Tasklet() { @Nullable @Override @@ -120,7 +120,7 @@ public RepeatStatus execute(StepContribution contribution, ChunkContext chunkCon } @Test - public void testOpenFailure() throws Exception { + void testOpenFailure() throws Exception { final RuntimeException exception = new RuntimeException(); taskletStep.setStreams(new ItemStream[] { new ItemStreamSupport() { @Override @@ -136,7 +136,7 @@ public void open(ExecutionContext executionContext) throws ItemStreamException { } @Test - public void testBeforeStepFailure() throws Exception { + void testBeforeStepFailure() throws Exception { final RuntimeException exception = new RuntimeException(); taskletStep.setStepExecutionListeners(new StepExecutionListener[] { new StepExecutionListener() { @@ -152,7 +152,7 @@ public void beforeStep(StepExecution stepExecution) { } @Test - public void testAfterStepFailureWhenTaskletSucceeds() throws Exception { + void testAfterStepFailureWhenTaskletSucceeds() throws Exception { final RuntimeException exception = new RuntimeException(); taskletStep.setStepExecutionListeners(new StepExecutionListener[] { new StepExecutionListener() { @@ -177,11 +177,11 @@ public RepeatStatus execute(StepContribution contribution, ChunkContext attribut assertEquals(3, jobRepository.getUpdateCount()); } - @Test /* * Exception in afterStep is ignored (only logged). */ - public void testAfterStepFailureWhenTaskletFails() throws Exception { + @Test + void testAfterStepFailureWhenTaskletFails() throws Exception { final RuntimeException exception = new RuntimeException(); taskletStep.setStepExecutionListeners(new StepExecutionListener[] { new StepExecutionListener() { @@ -199,7 +199,7 @@ public ExitStatus afterStep(StepExecution stepExecution) { } @Test - public void testCloseError() throws Exception { + void testCloseError() throws Exception { final RuntimeException exception = new RuntimeException(); taskletStep.setStreams(new ItemStream[] { new ItemStreamSupport() { @@ -217,9 +217,8 @@ public void close() throws ItemStreamException { assertEquals(2, jobRepository.getUpdateCount()); } - @SuppressWarnings("serial") @Test - public void testCommitError() throws Exception { + void testCommitError() throws Exception { taskletStep.setTransactionManager(new ResourcelessTransactionManager() { @Override @@ -257,9 +256,8 @@ public RepeatStatus execute(StepContribution contribution, ChunkContext attribut assertTrue(stepExecution.getExecutionContext().containsKey(TaskletStep.TASKLET_TYPE_KEY)); } - @SuppressWarnings("serial") @Test - public void testUnexpectedRollback() throws Exception { + void testUnexpectedRollback() throws Exception { taskletStep.setTransactionManager(new ResourcelessTransactionManager() { @Override @@ -294,7 +292,7 @@ public RepeatStatus execute(StepContribution contribution, ChunkContext attribut } @Test - public void testRepositoryErrorOnExecutionContext() throws Exception { + void testRepositoryErrorOnExecutionContext() throws Exception { taskletStep.setTasklet(new Tasklet() { @@ -315,7 +313,7 @@ public RepeatStatus execute(StepContribution contribution, ChunkContext attribut } @Test - public void testRepositoryErrorOnExecutionContextInTransaction() throws Exception { + void testRepositoryErrorOnExecutionContextInTransaction() throws Exception { taskletStep.setTasklet(new Tasklet() { @@ -337,7 +335,7 @@ public RepeatStatus execute(StepContribution contribution, ChunkContext attribut } @Test - public void testRepositoryErrorOnExecutionContextInTransactionRollbackFailed() throws Exception { + void testRepositoryErrorOnExecutionContextInTransactionRollbackFailed() throws Exception { taskletStep.setTasklet(new Tasklet() { @@ -361,7 +359,7 @@ public RepeatStatus execute(StepContribution contribution, ChunkContext attribut } @Test - public void testRepositoryErrorOnUpdateStepExecution() throws Exception { + void testRepositoryErrorOnUpdateStepExecution() throws Exception { taskletStep.setTasklet(new Tasklet() { @@ -382,7 +380,7 @@ public RepeatStatus execute(StepContribution contribution, ChunkContext attribut } @Test - public void testRepositoryErrorOnUpdateStepExecutionInTransaction() throws Exception { + void testRepositoryErrorOnUpdateStepExecutionInTransaction() throws Exception { taskletStep.setTasklet(new Tasklet() { @@ -404,7 +402,7 @@ public RepeatStatus execute(StepContribution contribution, ChunkContext attribut } @Test - public void testRepositoryErrorOnUpdateStepExecutionInTransactionRollbackFailed() throws Exception { + void testRepositoryErrorOnUpdateStepExecutionInTransactionRollbackFailed() throws Exception { taskletStep.setTasklet(new Tasklet() { @@ -428,7 +426,7 @@ public RepeatStatus execute(StepContribution contribution, ChunkContext attribut } @Test - public void testRepositoryErrorOnFailure() throws Exception { + void testRepositoryErrorOnFailure() throws Exception { taskletStep.setTasklet(new Tasklet() { @@ -449,7 +447,7 @@ public RepeatStatus execute(StepContribution contribution, ChunkContext attribut } @Test - public void testUpdateError() throws Exception { + void testUpdateError() throws Exception { final RuntimeException exception = new RuntimeException(); taskletStep.setJobRepository(new UpdateCountingJobRepository() { @@ -587,7 +585,6 @@ public JobInstance createJobInstance(String jobName, JobParameters jobParameters } - @SuppressWarnings("serial") private static class FailingRollbackTransactionManager extends ResourcelessTransactionManager { @Override diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/job/DefaultJobParametersExtractorJobParametersTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/job/DefaultJobParametersExtractorJobParametersTests.java index b6d159d03d..448c9a0ec7 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/job/DefaultJobParametersExtractorJobParametersTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/job/DefaultJobParametersExtractorJobParametersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2010 the original author or authors. + * Copyright 2006-2022 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. @@ -15,12 +15,12 @@ */ package org.springframework.batch.core.step.job; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.text.SimpleDateFormat; import java.util.Date; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInstance; import org.springframework.batch.core.JobParameters; @@ -32,12 +32,12 @@ * @author Dave Syer * */ -public class DefaultJobParametersExtractorJobParametersTests { +class DefaultJobParametersExtractorJobParametersTests { - private DefaultJobParametersExtractor extractor = new DefaultJobParametersExtractor(); + private final DefaultJobParametersExtractor extractor = new DefaultJobParametersExtractor(); @Test - public void testGetNamedJobParameters() throws Exception { + void testGetNamedJobParameters() { StepExecution stepExecution = getStepExecution("foo=bar"); extractor.setKeys(new String[] { "foo", "bar" }); JobParameters jobParameters = extractor.getJobParameters(null, stepExecution); @@ -45,7 +45,7 @@ public void testGetNamedJobParameters() throws Exception { } @Test - public void testGetAllJobParameters() throws Exception { + void testGetAllJobParameters() { StepExecution stepExecution = getStepExecution("foo=bar,spam=bucket"); extractor.setKeys(new String[] { "foo", "bar" }); JobParameters jobParameters = extractor.getJobParameters(null, stepExecution); @@ -54,7 +54,7 @@ public void testGetAllJobParameters() throws Exception { } @Test - public void testGetNamedLongStringParameters() throws Exception { + void testGetNamedLongStringParameters() { StepExecution stepExecution = getStepExecution("foo=bar"); extractor.setKeys(new String[] { "foo(string)", "bar" }); JobParameters jobParameters = extractor.getJobParameters(null, stepExecution); @@ -62,7 +62,7 @@ public void testGetNamedLongStringParameters() throws Exception { } @Test - public void testGetNamedLongJobParameters() throws Exception { + void testGetNamedLongJobParameters() { StepExecution stepExecution = getStepExecution("foo(long)=11"); extractor.setKeys(new String[] { "foo(long)", "bar" }); JobParameters jobParameters = extractor.getJobParameters(null, stepExecution); @@ -70,7 +70,7 @@ public void testGetNamedLongJobParameters() throws Exception { } @Test - public void testGetNamedIntJobParameters() throws Exception { + void testGetNamedIntJobParameters() { StepExecution stepExecution = getStepExecution("foo(long)=11"); extractor.setKeys(new String[] { "foo(int)", "bar" }); JobParameters jobParameters = extractor.getJobParameters(null, stepExecution); @@ -78,7 +78,7 @@ public void testGetNamedIntJobParameters() throws Exception { } @Test - public void testGetNamedDoubleJobParameters() throws Exception { + void testGetNamedDoubleJobParameters() { StepExecution stepExecution = getStepExecution("foo(double)=11.1"); extractor.setKeys(new String[] { "foo(double)" }); JobParameters jobParameters = extractor.getJobParameters(null, stepExecution); @@ -86,7 +86,7 @@ public void testGetNamedDoubleJobParameters() throws Exception { } @Test - public void testGetNamedDateJobParameters() throws Exception { + void testGetNamedDateJobParameters() throws Exception { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); Date date = dateFormat.parse(dateFormat.format(new Date())); StepExecution stepExecution = getStepExecution("foo(date)=" + dateFormat.format(date)); @@ -95,10 +95,6 @@ public void testGetNamedDateJobParameters() throws Exception { assertEquals("{foo=" + date.getTime() + "}", jobParameters.toString()); } - /** - * @param parameters - * @return - */ private StepExecution getStepExecution(String parameters) { JobParameters jobParameters = new DefaultJobParametersConverter() .getJobParameters(PropertiesConverter.stringToProperties(parameters)); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/job/DefaultJobParametersExtractorTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/job/DefaultJobParametersExtractorTests.java index 3fd1a23e1c..af304e1992 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/job/DefaultJobParametersExtractorTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/job/DefaultJobParametersExtractorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2010 the original author or authors. + * Copyright 2006-2022 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. @@ -15,11 +15,11 @@ */ package org.springframework.batch.core.step.job; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.util.Date; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.JobParametersBuilder; @@ -29,20 +29,20 @@ * @author Dave Syer * */ -public class DefaultJobParametersExtractorTests { +class DefaultJobParametersExtractorTests { - private DefaultJobParametersExtractor extractor = new DefaultJobParametersExtractor(); + private final DefaultJobParametersExtractor extractor = new DefaultJobParametersExtractor(); - private StepExecution stepExecution = new StepExecution("step", new JobExecution(0L)); + private final StepExecution stepExecution = new StepExecution("step", new JobExecution(0L)); @Test - public void testGetEmptyJobParameters() throws Exception { + void testGetEmptyJobParameters() { JobParameters jobParameters = extractor.getJobParameters(null, stepExecution); assertEquals("{}", jobParameters.toString()); } @Test - public void testGetNamedJobParameters() throws Exception { + void testGetNamedJobParameters() { stepExecution.getExecutionContext().put("foo", "bar"); extractor.setKeys(new String[] { "foo", "bar" }); JobParameters jobParameters = extractor.getJobParameters(null, stepExecution); @@ -50,7 +50,7 @@ public void testGetNamedJobParameters() throws Exception { } @Test - public void testGetNamedLongStringParameters() throws Exception { + void testGetNamedLongStringParameters() { stepExecution.getExecutionContext().putString("foo", "bar"); extractor.setKeys(new String[] { "foo(string)", "bar" }); JobParameters jobParameters = extractor.getJobParameters(null, stepExecution); @@ -58,7 +58,7 @@ public void testGetNamedLongStringParameters() throws Exception { } @Test - public void testGetNamedLongJobParameters() throws Exception { + void testGetNamedLongJobParameters() { stepExecution.getExecutionContext().putLong("foo", 11L); extractor.setKeys(new String[] { "foo(long)", "bar" }); JobParameters jobParameters = extractor.getJobParameters(null, stepExecution); @@ -66,7 +66,7 @@ public void testGetNamedLongJobParameters() throws Exception { } @Test - public void testGetNamedIntJobParameters() throws Exception { + void testGetNamedIntJobParameters() { stepExecution.getExecutionContext().putInt("foo", 11); extractor.setKeys(new String[] { "foo(int)", "bar" }); JobParameters jobParameters = extractor.getJobParameters(null, stepExecution); @@ -74,7 +74,7 @@ public void testGetNamedIntJobParameters() throws Exception { } @Test - public void testGetNamedDoubleJobParameters() throws Exception { + void testGetNamedDoubleJobParameters() { stepExecution.getExecutionContext().putDouble("foo", 11.1); extractor.setKeys(new String[] { "foo(double)" }); JobParameters jobParameters = extractor.getJobParameters(null, stepExecution); @@ -82,7 +82,7 @@ public void testGetNamedDoubleJobParameters() throws Exception { } @Test - public void testGetNamedDateJobParameters() throws Exception { + void testGetNamedDateJobParameters() { Date date = new Date(); stepExecution.getExecutionContext().put("foo", date); extractor.setKeys(new String[] { "foo(date)" }); @@ -91,7 +91,7 @@ public void testGetNamedDateJobParameters() throws Exception { } @Test - public void testUseParentParameters() throws Exception { + void testUseParentParameters() { JobExecution jobExecution = new JobExecution(0L, new JobParametersBuilder().addString("parentParam", "val").toJobParameters()); @@ -103,12 +103,12 @@ public void testUseParentParameters() throws Exception { String jobParams = jobParameters.toString(); - assertTrue("Job parameters must contain parentParam=val", jobParams.contains("parentParam=val")); - assertTrue("Job parameters must contain foo=11.1", jobParams.contains("foo=11.1")); + assertTrue(jobParams.contains("parentParam=val"), "Job parameters must contain parentParam=val"); + assertTrue(jobParams.contains("foo=11.1"), "Job parameters must contain foo=11.1"); } @Test - public void testDontUseParentParameters() throws Exception { + void testDontUseParentParameters() { DefaultJobParametersExtractor extractor = new DefaultJobParametersExtractor(); extractor.setUseAllParentParameters(false); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/job/JobStepTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/job/JobStepTests.java index 1e8563452a..3cb2f82b3b 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/job/JobStepTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/job/JobStepTests.java @@ -17,8 +17,8 @@ import java.util.Date; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; @@ -35,24 +35,25 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Dave Syer * @author Mahmoud Ben Hassine * */ -public class JobStepTests { +class JobStepTests { - private JobStep step = new JobStep(); + private final JobStep step = new JobStep(); private StepExecution stepExecution; private JobRepository jobRepository; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { step.setName("step"); EmbeddedDatabase embeddedDatabase = new EmbeddedDatabaseBuilder() .addScript("/org/springframework/batch/core/schema-drop-hsqldb.sql") @@ -72,24 +73,16 @@ public void setUp() throws Exception { step.setJobLauncher(jobLauncher); } - /** - * Test method for - * {@link org.springframework.batch.core.step.job.JobStep#afterPropertiesSet()} . - */ - @Test(expected = IllegalStateException.class) - public void testAfterPropertiesSet() throws Exception { - step.afterPropertiesSet(); + @Test + void testAfterPropertiesSet() { + assertThrows(IllegalStateException.class, step::afterPropertiesSet); } - /** - * Test method for - * {@link org.springframework.batch.core.step.job.JobStep#afterPropertiesSet()} . - */ - @Test(expected = IllegalStateException.class) - public void testAfterPropertiesSetWithNoLauncher() throws Exception { + @Test + void testAfterPropertiesSetWithNoLauncher() { step.setJob(new JobSupport("child")); step.setJobLauncher(null); - step.afterPropertiesSet(); + assertThrows(IllegalStateException.class, step::afterPropertiesSet); } /** @@ -98,7 +91,7 @@ public void testAfterPropertiesSetWithNoLauncher() throws Exception { * . */ @Test - public void testExecuteSunnyDay() throws Exception { + void testExecuteSunnyDay() throws Exception { step.setJob(new JobSupport("child") { @Override public void execute(JobExecution execution) throws UnexpectedJobExecutionException { @@ -109,12 +102,12 @@ public void execute(JobExecution execution) throws UnexpectedJobExecutionExcepti step.afterPropertiesSet(); step.execute(stepExecution); assertEquals(BatchStatus.COMPLETED, stepExecution.getStatus()); - assertTrue("Missing job parameters in execution context: " + stepExecution.getExecutionContext(), - stepExecution.getExecutionContext().containsKey(JobStep.class.getName() + ".JOB_PARAMETERS")); + assertTrue(stepExecution.getExecutionContext().containsKey(JobStep.class.getName() + ".JOB_PARAMETERS"), + "Missing job parameters in execution context: " + stepExecution.getExecutionContext()); } @Test - public void testExecuteFailure() throws Exception { + void testExecuteFailure() throws Exception { step.setJob(new JobSupport("child") { @Override public void execute(JobExecution execution) throws UnexpectedJobExecutionException { @@ -128,7 +121,7 @@ public void execute(JobExecution execution) throws UnexpectedJobExecutionExcepti } @Test - public void testExecuteException() throws Exception { + void testExecuteException() throws Exception { step.setJob(new JobSupport("child") { @Override public void execute(JobExecution execution) throws UnexpectedJobExecutionException { @@ -142,7 +135,7 @@ public void execute(JobExecution execution) throws UnexpectedJobExecutionExcepti } @Test - public void testExecuteRestart() throws Exception { + void testExecuteRestart() throws Exception { DefaultJobParametersExtractor jobParametersExtractor = new DefaultJobParametersExtractor(); jobParametersExtractor.setKeys(new String[] { "foo" }); @@ -183,7 +176,7 @@ public boolean isRestartable() { } @Test - public void testStoppedChild() throws Exception { + void testStoppedChild() throws Exception { DefaultJobParametersExtractor jobParametersExtractor = new DefaultJobParametersExtractor(); jobParametersExtractor.setKeys(new String[] { "foo" }); @@ -216,7 +209,7 @@ public boolean isRestartable() { } @Test - public void testStepExecutionExitStatus() throws Exception { + void testStepExecutionExitStatus() throws Exception { step.setJob(new JobSupport("child") { @Override public void execute(JobExecution execution) throws UnexpectedJobExecutionException { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/skip/LimitCheckingItemSkipPolicyTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/skip/LimitCheckingItemSkipPolicyTests.java index 64345cfc49..74ea51f8f7 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/skip/LimitCheckingItemSkipPolicyTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/skip/LimitCheckingItemSkipPolicyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2008 the original author or authors. + * Copyright 2006-2022 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. @@ -15,16 +15,16 @@ */ package org.springframework.batch.core.step.skip; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.Map; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.item.ItemWriterException; import org.springframework.batch.item.WriteFailedException; import org.springframework.batch.item.WriterNotOpenException; @@ -35,35 +35,30 @@ * @author Dave Syer * */ -public class LimitCheckingItemSkipPolicyTests { +class LimitCheckingItemSkipPolicyTests { private LimitCheckingItemSkipPolicy failurePolicy; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { Map, Boolean> skippableExceptions = new HashMap<>(); skippableExceptions.put(FlatFileParseException.class, true); failurePolicy = new LimitCheckingItemSkipPolicy(1, skippableExceptions); } @Test - public void testLimitExceed() { - try { - failurePolicy.shouldSkip(new FlatFileParseException("", ""), 2); - fail(); - } - catch (SkipLimitExceededException ex) { - // expected - } + void testLimitExceed() { + assertThrows(SkipLimitExceededException.class, + () -> failurePolicy.shouldSkip(new FlatFileParseException("", ""), 2)); } @Test - public void testNonSkippableException() { + void testNonSkippableException() { assertFalse(failurePolicy.shouldSkip(new FileNotFoundException(), 2)); } @Test - public void testSkip() { + void testSkip() { assertTrue(failurePolicy.shouldSkip(new FlatFileParseException("", ""), 0)); } @@ -80,7 +75,7 @@ private LimitCheckingItemSkipPolicy getSkippableSubsetSkipPolicy() { * expected: false; default classification */ @Test - public void testSkippableSubset_unclassified() { + void testSkippableSubset_unclassified() { assertFalse(getSkippableSubsetSkipPolicy().shouldSkip(new RuntimeException(), 0)); } @@ -90,7 +85,7 @@ public void testSkippableSubset_unclassified() { * expected: true */ @Test - public void testSkippableSubset_skippable() { + void testSkippableSubset_skippable() { assertTrue(getSkippableSubsetSkipPolicy().shouldSkip(new WriteFailedException(""), 0)); } @@ -100,7 +95,7 @@ public void testSkippableSubset_skippable() { * expected: false */ @Test - public void testSkippableSubset_fatal() { + void testSkippableSubset_fatal() { assertFalse(getSkippableSubsetSkipPolicy().shouldSkip(new WriterNotOpenException(""), 0)); } @@ -117,7 +112,7 @@ private LimitCheckingItemSkipPolicy getFatalSubsetSkipPolicy() { * expected: false; default classification */ @Test - public void testFatalSubset_unclassified() { + void testFatalSubset_unclassified() { assertFalse(getFatalSubsetSkipPolicy().shouldSkip(new RuntimeException(), 0)); } @@ -127,7 +122,7 @@ public void testFatalSubset_unclassified() { * expected: true */ @Test - public void testFatalSubset_skippable() { + void testFatalSubset_skippable() { assertTrue(getFatalSubsetSkipPolicy().shouldSkip(new WriterNotOpenException(""), 0)); } @@ -137,7 +132,7 @@ public void testFatalSubset_skippable() { * expected: false */ @Test - public void testFatalSubset_fatal() { + void testFatalSubset_fatal() { assertFalse(getFatalSubsetSkipPolicy().shouldSkip(new WriteFailedException(""), 0)); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/skip/ReprocessExceptionTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/skip/ReprocessExceptionTests.java index 7189d24010..ea4bce0a50 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/skip/ReprocessExceptionTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/skip/ReprocessExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2022 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. @@ -15,8 +15,7 @@ */ package org.springframework.batch.core.step.skip; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -26,18 +25,16 @@ import org.springframework.batch.item.ItemWriter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.lang.Nullable; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author mminella */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) +@SpringJUnitConfig public class ReprocessExceptionTests { @Autowired @@ -47,7 +44,7 @@ public class ReprocessExceptionTests { public JobLauncher jobLauncher; @Test - public void testReprocessException() throws Exception { + void testReprocessException() throws Exception { JobExecution execution = jobLauncher.run(job, new JobParametersBuilder().toJobParameters()); assertEquals(BatchStatus.COMPLETED, execution.getStatus()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/AsyncChunkOrientedStepIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/AsyncChunkOrientedStepIntegrationTests.java index 6abaa5d928..f117d73954 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/AsyncChunkOrientedStepIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/AsyncChunkOrientedStepIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2017 the original author or authors. + * Copyright 2006-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,11 +21,10 @@ import java.util.List; import org.apache.commons.dbcp2.BasicDataSource; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; +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.batch.core.BatchStatus; import org.springframework.batch.core.Job; @@ -43,29 +42,27 @@ import org.springframework.batch.repeat.support.TaskExecutorRepeatTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.task.SimpleAsyncTaskExecutor; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; /** * @author Dave Syer * */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = "/org/springframework/batch/core/repository/dao/sql-dao-test.xml") -public class AsyncChunkOrientedStepIntegrationTests { +@SpringJUnitConfig(locations = "/org/springframework/batch/core/repository/dao/sql-dao-test.xml") +class AsyncChunkOrientedStepIntegrationTests { private TaskletStep step; private Job job; - private List written = new ArrayList<>(); + private final List written = new ArrayList<>(); @Autowired private PlatformTransactionManager transactionManager; @@ -86,15 +83,15 @@ private ItemReader getReader(String[] args) { return new ListItemReader<>(Arrays.asList(args)); } - @After - public void reset() { + @AfterEach + void reset() { // Reset concurrency settings to something reasonable dataSource.setMaxTotal(maxActive); dataSource.setMaxIdle(maxIdle); } - @Before - public void init() throws Exception { + @BeforeEach + void init() { maxActive = dataSource.getMaxTotal(); maxIdle = dataSource.getMaxIdle(); @@ -121,8 +118,8 @@ public void init() throws Exception { } @Test - @Ignore - public void testStatus() throws Exception { + @Disabled + void testStatus() throws Exception { step.setTasklet(new TestingChunkOrientedTasklet<>( getReader(new String[] { "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c" }), @@ -150,7 +147,7 @@ public StepExecution doInTransaction(TransactionStatus status) { } }); assertEquals(lastStepExecution, stepExecution); - assertFalse(lastStepExecution == stepExecution); + assertNotSame(lastStepExecution, stepExecution); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/AsyncTaskletStepTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/AsyncTaskletStepTests.java index c1a93773da..f81e3d23b9 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/AsyncTaskletStepTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/AsyncTaskletStepTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2019 the original author or authors. + * Copyright 2006-2022 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.batch.core.step.tasklet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Arrays; @@ -26,7 +26,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; @@ -47,11 +47,11 @@ import org.springframework.lang.Nullable; import org.springframework.util.StringUtils; -public class AsyncTaskletStepTests { +class AsyncTaskletStepTests { - private static Log logger = LogFactory.getLog(AsyncTaskletStepTests.class); + private static final Log logger = LogFactory.getLog(AsyncTaskletStepTests.class); - private List processed = new CopyOnWriteArrayList<>(); + private final List processed = new CopyOnWriteArrayList<>(); private TaskletStep step; @@ -77,7 +77,7 @@ public void write(List data) throws Exception { private ItemProcessor itemProcessor = new PassThroughItemProcessor<>(); - private void setUp() throws Exception { + private void setUp() { step = new TaskletStep("stepName"); @@ -115,7 +115,7 @@ public void update(ExecutionContext executionContext) { * StepExecution should be updated after every chunk commit. */ @Test - public void testStepExecutionUpdates() throws Exception { + void testStepExecutionUpdates() throws Exception { items = new ArrayList<>(Arrays.asList(StringUtils .commaDelimitedListToStringArray("1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25"))); @@ -137,10 +137,10 @@ public void testStepExecutionUpdates() throws Exception { // System.err.println(processed); // Check commit count didn't spin out of control waiting for other // threads to finish... - assertTrue("Not enough commits: " + stepExecution.getCommitCount(), - stepExecution.getCommitCount() > processed.size() / 2); - assertTrue("Too many commits: " + stepExecution.getCommitCount(), - stepExecution.getCommitCount() <= processed.size() / 2 + throttleLimit + 1); + assertTrue(stepExecution.getCommitCount() > processed.size() / 2, + "Not enough commits: " + stepExecution.getCommitCount()); + assertTrue(stepExecution.getCommitCount() <= processed.size() / 2 + throttleLimit + 1, + "Too many commits: " + stepExecution.getCommitCount()); } @@ -148,7 +148,7 @@ public void testStepExecutionUpdates() throws Exception { * StepExecution should fail immediately on error. */ @Test - public void testStepExecutionFails() throws Exception { + void testStepExecutionFails() throws Exception { throttleLimit = 1; concurrencyLimit = 1; @@ -170,7 +170,7 @@ public void testStepExecutionFails() throws Exception { * StepExecution should fail immediately on error in processor. */ @Test - public void testStepExecutionFailsWithProcessor() throws Exception { + void testStepExecutionFailsWithProcessor() throws Exception { throttleLimit = 1; concurrencyLimit = 1; @@ -204,7 +204,7 @@ public String process(String item) throws Exception { * StepExecution should fail immediately on error. */ @Test - public void testStepExecutionFailsOnLastItem() throws Exception { + void testStepExecutionFailsOnLastItem() throws Exception { throttleLimit = 1; concurrencyLimit = 1; diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/CallableTaskletAdapterTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/CallableTaskletAdapterTests.java index af4cda610c..8d4773cda5 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/CallableTaskletAdapterTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/CallableTaskletAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2013 the original author or authors. + * Copyright 2006-2022 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. @@ -15,20 +15,20 @@ */ package org.springframework.batch.core.step.tasklet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.concurrent.Callable; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.repeat.RepeatStatus; -public class CallableTaskletAdapterTests { +class CallableTaskletAdapterTests { - private CallableTaskletAdapter adapter = new CallableTaskletAdapter(); + private final CallableTaskletAdapter adapter = new CallableTaskletAdapter(); @Test - public void testHandle() throws Exception { + void testHandle() throws Exception { adapter.setCallable(new Callable() { @Override public RepeatStatus call() throws Exception { @@ -39,14 +39,8 @@ public RepeatStatus call() throws Exception { } @Test - public void testAfterPropertiesSet() throws Exception { - try { - adapter.afterPropertiesSet(); - fail("Expected IllegalArgumentException"); - } - catch (IllegalArgumentException e) { - // expected - } + void testAfterPropertiesSet() { + assertThrows(IllegalArgumentException.class, adapter::afterPropertiesSet); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/ChunkOrientedStepIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/ChunkOrientedStepIntegrationTests.java index 8cb116b27e..9192bcd83c 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/ChunkOrientedStepIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/ChunkOrientedStepIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,10 +15,9 @@ */ package org.springframework.batch.core.step.tasklet; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -33,8 +32,7 @@ import org.springframework.batch.repeat.policy.SimpleCompletionPolicy; import org.springframework.batch.repeat.support.RepeatTemplate; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -42,16 +40,15 @@ import java.util.Arrays; import java.util.Collections; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; /** * @author Dave Syer * */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = "/org/springframework/batch/core/repository/dao/sql-dao-test.xml") -public class ChunkOrientedStepIntegrationTests { +@SpringJUnitConfig(locations = "/org/springframework/batch/core/repository/dao/sql-dao-test.xml") +class ChunkOrientedStepIntegrationTests { private TaskletStep step; @@ -69,8 +66,8 @@ private ItemReader getReader(String[] args) { return new ListItemReader<>(Arrays.asList(args)); } - @Before - public void onSetUp() throws Exception { + @BeforeEach + void onSetUp() { step = new TaskletStep("stepName"); step.setJobRepository(jobRepository); @@ -86,10 +83,9 @@ public void onSetUp() throws Exception { } - @SuppressWarnings("serial") @Test - @Ignore - public void testStatusForCommitFailedException() throws Exception { + @Disabled + void testStatusForCommitFailedException() throws Exception { step.setTasklet(new TestingChunkOrientedTasklet<>(getReader(new String[] { "a", "b", "c" }), data -> TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { @@ -116,7 +112,7 @@ public void beforeCommit(boolean readOnly) { StepExecution lastStepExecution = jobRepository.getLastStepExecution(jobExecution.getJobInstance(), step.getName()); assertEquals(lastStepExecution, stepExecution); - assertFalse(lastStepExecution == stepExecution); + assertNotSame(lastStepExecution, stepExecution); // If the StepExecution is not saved after the failure it will be // STARTED instead of FAILED diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/ConfigurableSystemProcessExitCodeMapperTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/ConfigurableSystemProcessExitCodeMapperTests.java index 51ac0d44e5..b2ee8dd85f 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/ConfigurableSystemProcessExitCodeMapperTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/ConfigurableSystemProcessExitCodeMapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2014 the original author or authors. + * Copyright 2008-2022 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. @@ -15,30 +15,27 @@ */ package org.springframework.batch.core.step.tasklet; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; -import java.util.Collections; import java.util.HashMap; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.ExitStatus; -import org.springframework.batch.core.step.tasklet.ConfigurableSystemProcessExitCodeMapper; /** * Tests for {@link ConfigurableSystemProcessExitCodeMapper} */ -public class ConfigurableSystemProcessExitCodeMapperTests { +class ConfigurableSystemProcessExitCodeMapperTests { - private ConfigurableSystemProcessExitCodeMapper mapper = new ConfigurableSystemProcessExitCodeMapper(); + private final ConfigurableSystemProcessExitCodeMapper mapper = new ConfigurableSystemProcessExitCodeMapper(); /** * Regular usage scenario - mapping adheres to injected values */ @Test - public void testMapping() { - @SuppressWarnings("serial") + void testMapping() { Map mappings = new HashMap() { { put(0, ExitStatus.COMPLETED); @@ -69,18 +66,12 @@ public void testMapping() { * Else clause is required in the injected map - setter checks its presence. */ @Test - public void testSetMappingsMissingElseClause() { + void testSetMappingsMissingElseClause() { Map missingElse = new HashMap<>(); - try { - mapper.setMappings(missingElse); - fail(); - } - catch (IllegalArgumentException e) { - // expected - } + assertThrows(IllegalArgumentException.class, () -> mapper.setMappings(missingElse)); - Map containsElse = Collections - .singletonMap(ConfigurableSystemProcessExitCodeMapper.ELSE_KEY, ExitStatus.FAILED); + Map containsElse = Map.of(ConfigurableSystemProcessExitCodeMapper.ELSE_KEY, + ExitStatus.FAILED); // no error expected now mapper.setMappings(containsElse); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/MethodInvokingTaskletAdapterTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/MethodInvokingTaskletAdapterTests.java index 2942b9aabb..5adc41058a 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/MethodInvokingTaskletAdapterTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/MethodInvokingTaskletAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -15,21 +15,22 @@ */ package org.springframework.batch.core.step.tasklet; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.StepContribution; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.batch.repeat.RepeatStatus; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; /** * @author Mahmoud Ben Hassine */ -public class MethodInvokingTaskletAdapterTests { +class MethodInvokingTaskletAdapterTests { private StepContribution stepContribution; @@ -39,8 +40,8 @@ public class MethodInvokingTaskletAdapterTests { private MethodInvokingTaskletAdapter adapter; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { stepContribution = new StepContribution(mock(StepExecution.class)); chunkContext = mock(ChunkContext.class); tasklet = new TestTasklet(); @@ -49,7 +50,7 @@ public void setUp() throws Exception { } @Test - public void testExactlySameSignature() throws Exception { + void testExactlySameSignature() throws Exception { adapter.setTargetMethod("execute"); RepeatStatus repeatStatus = adapter.execute(stepContribution, chunkContext); assertEquals(RepeatStatus.FINISHED, repeatStatus); @@ -58,7 +59,7 @@ public void testExactlySameSignature() throws Exception { } @Test - public void testSameSignatureWithDifferentMethodName() throws Exception { + void testSameSignatureWithDifferentMethodName() throws Exception { adapter.setTargetMethod("execute1"); RepeatStatus repeatStatus = adapter.execute(stepContribution, chunkContext); assertEquals(RepeatStatus.FINISHED, repeatStatus); @@ -67,7 +68,7 @@ public void testSameSignatureWithDifferentMethodName() throws Exception { } @Test - public void testDifferentParametersOrder() throws Exception { + void testDifferentParametersOrder() throws Exception { adapter.setTargetMethod("execute2"); RepeatStatus repeatStatus = adapter.execute(stepContribution, chunkContext); assertEquals(RepeatStatus.FINISHED, repeatStatus); @@ -76,7 +77,7 @@ public void testDifferentParametersOrder() throws Exception { } @Test - public void testArgumentSubsetWithOnlyChunkContext() throws Exception { + void testArgumentSubsetWithOnlyChunkContext() throws Exception { adapter.setTargetMethod("execute3"); RepeatStatus repeatStatus = adapter.execute(stepContribution, chunkContext); assertEquals(RepeatStatus.FINISHED, repeatStatus); @@ -84,7 +85,7 @@ public void testArgumentSubsetWithOnlyChunkContext() throws Exception { } @Test - public void testArgumentSubsetWithOnlyStepContribution() throws Exception { + void testArgumentSubsetWithOnlyStepContribution() throws Exception { adapter.setTargetMethod("execute4"); RepeatStatus repeatStatus = adapter.execute(stepContribution, chunkContext); assertEquals(RepeatStatus.FINISHED, repeatStatus); @@ -92,28 +93,28 @@ public void testArgumentSubsetWithOnlyStepContribution() throws Exception { } @Test - public void testArgumentSubsetWithoutArguments() throws Exception { + void testArgumentSubsetWithoutArguments() throws Exception { adapter.setTargetMethod("execute5"); RepeatStatus repeatStatus = adapter.execute(stepContribution, chunkContext); assertEquals(RepeatStatus.FINISHED, repeatStatus); } @Test - public void testCompatibleReturnTypeWhenBoolean() throws Exception { + void testCompatibleReturnTypeWhenBoolean() throws Exception { adapter.setTargetMethod("execute6"); RepeatStatus repeatStatus = adapter.execute(stepContribution, chunkContext); assertEquals(RepeatStatus.FINISHED, repeatStatus); } @Test - public void testCompatibleReturnTypeWhenVoid() throws Exception { + void testCompatibleReturnTypeWhenVoid() throws Exception { adapter.setTargetMethod("execute7"); RepeatStatus repeatStatus = adapter.execute(stepContribution, chunkContext); assertEquals(RepeatStatus.FINISHED, repeatStatus); } @Test - public void testArgumentSubsetWithOnlyStepContributionAndCompatibleReturnTypeBoolean() throws Exception { + void testArgumentSubsetWithOnlyStepContributionAndCompatibleReturnTypeBoolean() throws Exception { adapter.setTargetMethod("execute8"); RepeatStatus repeatStatus = adapter.execute(stepContribution, chunkContext); assertEquals(RepeatStatus.FINISHED, repeatStatus); @@ -121,28 +122,28 @@ public void testArgumentSubsetWithOnlyStepContributionAndCompatibleReturnTypeBoo } @Test - public void testArgumentSubsetWithOnlyChunkContextAndCompatibleReturnTypeVoid() throws Exception { + void testArgumentSubsetWithOnlyChunkContextAndCompatibleReturnTypeVoid() throws Exception { adapter.setTargetMethod("execute9"); RepeatStatus repeatStatus = adapter.execute(stepContribution, chunkContext); assertEquals(RepeatStatus.FINISHED, repeatStatus); assertEquals(tasklet.getChunkContext(), chunkContext); } - @Test(expected = IllegalArgumentException.class) - public void testIncorrectSignatureWithExtraParameter() throws Exception { + @Test + void testIncorrectSignatureWithExtraParameter() { adapter.setTargetMethod("execute10"); - adapter.execute(stepContribution, chunkContext); + assertThrows(IllegalArgumentException.class, () -> adapter.execute(stepContribution, chunkContext)); } @Test - public void testExitStatusReturnType() throws Exception { + void testExitStatusReturnType() throws Exception { adapter.setTargetMethod("execute11"); adapter.execute(stepContribution, chunkContext); assertEquals(new ExitStatus("DONE"), stepContribution.getExitStatus()); } @Test - public void testNonExitStatusReturnType() throws Exception { + void testNonExitStatusReturnType() throws Exception { adapter.setTargetMethod("execute12"); RepeatStatus repeatStatus = adapter.execute(stepContribution, chunkContext); assertEquals(RepeatStatus.FINISHED, repeatStatus); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/SimpleSystemProcessExitCodeMapperTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/SimpleSystemProcessExitCodeMapperTests.java index 66d0edf562..a6df66f121 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/SimpleSystemProcessExitCodeMapperTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/SimpleSystemProcessExitCodeMapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2009 the original author or authors. + * Copyright 2008-2022 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. @@ -15,24 +15,23 @@ */ package org.springframework.batch.core.step.tasklet; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.ExitStatus; -import org.springframework.batch.core.step.tasklet.SimpleSystemProcessExitCodeMapper; /** * Tests for {@link SimpleSystemProcessExitCodeMapper}. */ -public class SimpleSystemProcessExitCodeMapperTests { +class SimpleSystemProcessExitCodeMapperTests { - private SimpleSystemProcessExitCodeMapper mapper = new SimpleSystemProcessExitCodeMapper(); + private final SimpleSystemProcessExitCodeMapper mapper = new SimpleSystemProcessExitCodeMapper(); /** * 0 -> ExitStatus.FINISHED else -> ExitStatus.FAILED */ @Test - public void testMapping() { + void testMapping() { assertEquals(ExitStatus.COMPLETED, mapper.getExitStatus(0)); assertEquals(ExitStatus.FAILED, mapper.getExitStatus(1)); assertEquals(ExitStatus.FAILED, mapper.getExitStatus(-1)); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/StepExecutorInterruptionTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/StepExecutorInterruptionTests.java index 2b77ccfdd9..384b89f6fd 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/StepExecutorInterruptionTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/StepExecutorInterruptionTests.java @@ -16,16 +16,16 @@ package org.springframework.batch.core.step.tasklet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import java.util.concurrent.Semaphore; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInterruptedException; @@ -48,8 +48,8 @@ import org.springframework.transaction.PlatformTransactionManager; // FIXME This test fails with an embedded database. Need to check if the datasource should be configured with mvcc enabled -@Ignore -public class StepExecutorInterruptionTests { +@Disabled +class StepExecutorInterruptionTests { private TaskletStep step; @@ -63,8 +63,8 @@ public class StepExecutorInterruptionTests { private PlatformTransactionManager transactionManager; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { EmbeddedDatabase embeddedDatabase = new EmbeddedDatabaseBuilder() .addScript("/org/springframework/batch/core/schema-drop-hsqldb.sql") .addScript("/org/springframework/batch/core/schema-hsqldb.sql").generateUniqueName(true).build(); @@ -95,7 +95,7 @@ public void write(List item) throws Exception { } @Test - public void testInterruptStep() throws Exception { + void testInterruptStep() throws Exception { configureStep(new TaskletStep("step")); @@ -133,14 +133,14 @@ public Object read() throws Exception { count++; } - assertTrue("Timed out waiting for step to be interrupted.", count < 1000); + assertTrue(count < 1000, "Timed out waiting for step to be interrupted."); assertFalse(processingThread.isAlive()); assertEquals(BatchStatus.STOPPED, stepExecution.getStatus()); } @Test - public void testInterruptOnInterruptedException() throws Exception { + void testInterruptOnInterruptedException() throws Exception { // This simulates the unlikely sounding, but in practice all too common // in Bamboo situation where the thread is interrupted before the lock @@ -184,14 +184,14 @@ public Object read() throws Exception { count++; } - assertTrue("Timed out waiting for step to be interrupted.", count < 1000); + assertTrue(count < 1000, "Timed out waiting for step to be interrupted."); assertFalse(processingThread.isAlive()); assertEquals(BatchStatus.STOPPED, stepExecution.getStatus()); } @Test - public void testLockNotReleasedIfChunkFails() throws Exception { + void testLockNotReleasedIfChunkFails() throws Exception { configureStep(new TaskletStep("step") { @SuppressWarnings("serial") @@ -207,7 +207,7 @@ public void acquire() throws InterruptedException { @Override public void release() { - assertTrue("Lock released before it is acquired", locked); + assertTrue(locked, "Lock released before it is acquired"); } }; } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/StepHandlerAdapterTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/StepHandlerAdapterTests.java index 4a82225f91..420bc1c9da 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/StepHandlerAdapterTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/StepHandlerAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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. @@ -15,10 +15,10 @@ */ package org.springframework.batch.core.step.tasklet; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInstance; @@ -30,13 +30,13 @@ * @author Dave Syer * */ -public class StepHandlerAdapterTests { +class StepHandlerAdapterTests { - private MethodInvokingTaskletAdapter tasklet = new MethodInvokingTaskletAdapter(); + private final MethodInvokingTaskletAdapter tasklet = new MethodInvokingTaskletAdapter(); private Object result = null; - private StepExecution stepExecution = new StepExecution("systemCommandStep", + private final StepExecution stepExecution = new StepExecution("systemCommandStep", new JobExecution(new JobInstance(1L, "systemCommandJob"), new JobParameters())); public ExitStatus execute() { @@ -47,13 +47,13 @@ public Object process() { return result; } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { tasklet.setTargetObject(this); } @Test - public void testExecuteWithExitStatus() throws Exception { + void testExecuteWithExitStatus() throws Exception { tasklet.setTargetMethod("execute"); StepContribution contribution = stepExecution.createStepContribution(); tasklet.execute(contribution, null); @@ -61,7 +61,7 @@ public void testExecuteWithExitStatus() throws Exception { } @Test - public void testMapResultWithNull() throws Exception { + void testMapResultWithNull() throws Exception { tasklet.setTargetMethod("process"); StepContribution contribution = stepExecution.createStepContribution(); tasklet.execute(contribution, null); @@ -69,7 +69,7 @@ public void testMapResultWithNull() throws Exception { } @Test - public void testMapResultWithNonNull() throws Exception { + void testMapResultWithNonNull() throws Exception { tasklet.setTargetMethod("process"); this.result = "foo"; StepContribution contribution = stepExecution.createStepContribution(); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/SystemCommandTaskletIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/SystemCommandTaskletIntegrationTests.java index 9f728012c1..d752bdfe08 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/SystemCommandTaskletIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/SystemCommandTaskletIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2021 the original author or authors. + * Copyright 2008-2022 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. @@ -19,12 +19,11 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -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.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; @@ -40,31 +39,29 @@ import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.util.Assert; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.when; /** * Tests for {@link SystemCommandTasklet}. */ -public class SystemCommandTaskletIntegrationTests { - - @Rule - public MockitoRule rule = MockitoJUnit.rule().silent(); +@ExtendWith(MockitoExtension.class) +class SystemCommandTaskletIntegrationTests { private static final Log log = LogFactory.getLog(SystemCommandTaskletIntegrationTests.class); private SystemCommandTasklet tasklet; - private StepExecution stepExecution = new StepExecution("systemCommandStep", + private final StepExecution stepExecution = new StepExecution("systemCommandStep", new JobExecution(new JobInstance(1L, "systemCommandJob"), 1L, new JobParameters())); @Mock private JobExplorer jobExplorer; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { initializeTasklet(); tasklet.afterPropertiesSet(); @@ -88,7 +85,7 @@ private void initializeTasklet() { * Regular usage scenario - successful execution of system command. */ @Test - public void testExecute() throws Exception { + void testExecute() throws Exception { String command = getJavaCommand() + " --version"; tasklet.setCommand(command); tasklet.afterPropertiesSet(); @@ -103,7 +100,7 @@ public void testExecute() throws Exception { * Failed execution scenario - error exit code returned by system command. */ @Test - public void testExecuteFailure() throws Exception { + void testExecuteFailure() throws Exception { String command = getJavaCommand() + " org.springframework.batch.sample.tasklet.UnknownClass"; tasklet.setCommand(command); tasklet.setTimeout(200L); @@ -125,95 +122,68 @@ public void testExecuteFailure() throws Exception { /* * The attempt to execute the system command results in exception */ - @Test(expected = java.util.concurrent.ExecutionException.class) - public void testExecuteException() throws Exception { + @Test + void testExecuteException() throws Exception { String command = "non-sense-that-should-cause-exception-when-attempted-to-execute"; tasklet.setCommand(command); tasklet.afterPropertiesSet(); - tasklet.execute(null, null); + assertThrows(java.util.concurrent.ExecutionException.class, () -> tasklet.execute(null, null)); } /* * Failed execution scenario - execution time exceeds timeout. */ @Test - public void testExecuteTimeout() throws Exception { + void testExecuteTimeout() throws Exception { String command = isRunningOnWindows() ? "ping 127.0.0.1" : "sleep 3"; tasklet.setCommand(command); tasklet.setTimeout(10); tasklet.afterPropertiesSet(); log.info("Executing command: " + command); - try { - tasklet.execute(null, null); - fail(); - } - catch (SystemCommandException e) { - assertTrue(e.getMessage().contains("did not finish within the timeout")); - } + Exception exception = assertThrows(SystemCommandException.class, () -> tasklet.execute(null, null)); + assertTrue(exception.getMessage().contains("did not finish within the timeout")); } /* * Job interrupted scenario. */ @Test - public void testInterruption() throws Exception { + void testInterruption() throws Exception { String command = isRunningOnWindows() ? "ping 127.0.0.1" : "sleep 5"; tasklet.setCommand(command); tasklet.setTerminationCheckInterval(10); tasklet.afterPropertiesSet(); stepExecution.setTerminateOnly(); - try { - tasklet.execute(null, null); - fail(); - } - catch (JobInterruptedException e) { - System.out.println(e.getMessage()); - assertTrue(e.getMessage().contains("Job interrupted while executing system command")); - assertTrue(e.getMessage().contains(command)); - } + Exception exception = assertThrows(JobInterruptedException.class, () -> tasklet.execute(null, null)); + String message = exception.getMessage(); + System.out.println(message); + assertTrue(message.contains("Job interrupted while executing system command")); + assertTrue(message.contains(command)); } /* * Command property value is required to be set. */ @Test - public void testCommandNotSet() throws Exception { + void testCommandNotSet() { tasklet.setCommand(null); - try { - tasklet.afterPropertiesSet(); - fail(); - } - catch (IllegalArgumentException e) { - // expected - } + assertThrows(IllegalArgumentException.class, tasklet::afterPropertiesSet); tasklet.setCommand(""); - try { - tasklet.afterPropertiesSet(); - fail(); - } - catch (IllegalArgumentException e) { - // expected - } + assertThrows(IllegalArgumentException.class, tasklet::afterPropertiesSet); } /* * Timeout must be set to non-zero value. */ @Test - public void testTimeoutNotSet() throws Exception { + void testTimeoutNotSet() { tasklet.setCommand("not-empty placeholder"); tasklet.setTimeout(0); - try { - tasklet.afterPropertiesSet(); - fail(); - } - catch (IllegalArgumentException e) { - // expected - } + assertThrows(IllegalArgumentException.class, tasklet::afterPropertiesSet); } /* @@ -221,29 +191,19 @@ public void testTimeoutNotSet() throws Exception { * directory */ @Test - public void testWorkingDirectory() throws Exception { + void testWorkingDirectory() throws Exception { File notExistingFile = new File("not-existing-path"); Assert.state(!notExistingFile.exists(), "not-existing-path does actually exist"); - try { - tasklet.setWorkingDirectory(notExistingFile.getCanonicalPath()); - fail(); - } - catch (IllegalArgumentException e) { - // expected - } + assertThrows(IllegalArgumentException.class, + () -> tasklet.setWorkingDirectory(notExistingFile.getCanonicalPath())); File notDirectory = File.createTempFile(this.getClass().getName(), null); Assert.state(notDirectory.exists(), "The file does not exist"); Assert.state(!notDirectory.isDirectory(), "The file is actually a directory"); - try { - tasklet.setWorkingDirectory(notDirectory.getCanonicalPath()); - fail(); - } - catch (IllegalArgumentException e) { - // expected - } + assertThrows(IllegalArgumentException.class, + () -> tasklet.setWorkingDirectory(notDirectory.getCanonicalPath())); File directory = notDirectory.getParentFile(); Assert.state(directory.exists(), "The directory does not exist"); @@ -257,7 +217,7 @@ public void testWorkingDirectory() throws Exception { * test stopping a tasklet */ @Test - public void testStopped() throws Exception { + void testStopped() throws Exception { initializeTasklet(); tasklet.setJobExplorer(jobExplorer); tasklet.afterPropertiesSet(); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/TaskletStepTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/TaskletStepTests.java index 76e5416115..36492f9807 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/TaskletStepTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/TaskletStepTests.java @@ -16,18 +16,19 @@ package org.springframework.batch.core.step.tasklet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Map; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.Job; @@ -66,11 +67,11 @@ import org.springframework.transaction.interceptor.DefaultTransactionAttribute; import org.springframework.transaction.support.DefaultTransactionStatus; -public class TaskletStepTests { +class TaskletStepTests { List processed = new ArrayList<>(); - private List list = new ArrayList<>(); + private final List list = new ArrayList<>(); ItemWriter itemWriter = new ItemWriter() { @Override @@ -89,12 +90,7 @@ public void write(List data) throws Exception { private ResourcelessTransactionManager transactionManager; - @SuppressWarnings("serial") - private ExecutionContext foobarEc = new ExecutionContext() { - { - put("foo", "bar"); - } - }; + private final ExecutionContext foobarEc = new ExecutionContext(Map.of("foo", "bar")); private ItemReader getReader(String[] args) { return new ListItemReader<>(Arrays.asList(args)); @@ -115,8 +111,8 @@ private TaskletStep getStep(String[] strings, int commitInterval) throws Excepti return step; } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { transactionManager = new ResourcelessTransactionManager(); @@ -135,7 +131,7 @@ public void setUp() throws Exception { } @Test - public void testStepExecutor() throws Exception { + void testStepExecutor() throws Exception { JobExecution jobExecutionContext = new JobExecution(jobInstance, jobParameters); StepExecution stepExecution = new StepExecution(step.getName(), jobExecutionContext); step.execute(stepExecution); @@ -145,7 +141,7 @@ public void testStepExecutor() throws Exception { } @Test - public void testCommitCount_Even() throws Exception { + void testCommitCount_Even() throws Exception { JobExecution jobExecutionContext = new JobExecution(jobInstance, jobParameters); step = getStep(new String[] { "foo", "bar", "spam", "eggs" }, 2); step.setTransactionManager(transactionManager); @@ -155,11 +151,11 @@ public void testCommitCount_Even() throws Exception { assertEquals(4, stepExecution.getReadCount()); assertEquals(4, stepExecution.getWriteCount()); assertEquals(3, stepExecution.getCommitCount()); // the empty chunk is the 3rd - // commit + // commit } @Test - public void testCommitCount_Uneven() throws Exception { + void testCommitCount_Uneven() throws Exception { JobExecution jobExecutionContext = new JobExecution(jobInstance, jobParameters); step = getStep(new String[] { "foo", "bar", "spam" }, 2); step.setTransactionManager(transactionManager); @@ -172,7 +168,7 @@ public void testCommitCount_Uneven() throws Exception { } @Test - public void testEmptyReader() throws Exception { + void testEmptyReader() throws Exception { JobExecution jobExecutionContext = new JobExecution(jobInstance, jobParameters); StepExecution stepExecution = new StepExecution(step.getName(), jobExecutionContext); step = getStep(new String[0]); @@ -191,7 +187,7 @@ public void testEmptyReader() throws Exception { * StepExecution should be updated after every chunk commit. */ @Test - public void testStepExecutionUpdates() throws Exception { + void testStepExecutionUpdates() throws Exception { JobExecution jobExecution = new JobExecution(jobInstance, jobParameters); StepExecution stepExecution = new StepExecution(step.getName(), jobExecution); @@ -212,7 +208,7 @@ public void testStepExecutionUpdates() throws Exception { * Failure to update StepExecution after chunk commit is fatal. */ @Test - public void testStepExecutionUpdateFailure() throws Exception { + void testStepExecutionUpdateFailure() throws Exception { JobExecution jobExecution = new JobExecution(jobInstance, jobParameters); StepExecution stepExecution = new StepExecution(step.getName(), jobExecution); @@ -227,7 +223,7 @@ public void testStepExecutionUpdateFailure() throws Exception { } @Test - public void testRepository() throws Exception { + void testRepository() throws Exception { EmbeddedDatabase embeddedDatabase = new EmbeddedDatabaseBuilder() .addScript("/org/springframework/batch/core/schema-drop-hsqldb.sql") .addScript("/org/springframework/batch/core/schema-hsqldb.sql").build(); @@ -248,7 +244,7 @@ public void testRepository() throws Exception { } @Test - public void testIncrementRollbackCount() { + void testIncrementRollbackCount() { ItemReader itemReader = new ItemReader() { @@ -274,7 +270,7 @@ public String read() throws Exception { } @Test - public void testExitCodeDefaultClassification() throws Exception { + void testExitCodeDefaultClassification() { ItemReader itemReader = new ItemReader() { @@ -301,7 +297,7 @@ public String read() throws Exception { } @Test - public void testExitCodeCustomClassification() throws Exception { + void testExitCodeCustomClassification() { ItemReader itemReader = new ItemReader() { @@ -332,7 +328,7 @@ public ExitStatus afterStep(StepExecution stepExecution) { ExitStatus status = stepExecution.getExitStatus(); assertEquals(ExitStatus.FAILED.getExitCode(), status.getExitCode()); String description = status.getExitDescription(); - assertTrue("Description does not include 'FOO': " + description, description.indexOf("FOO") >= 0); + assertTrue(description.contains("FOO"), "Description does not include 'FOO': " + description); } } @@ -341,7 +337,7 @@ public ExitStatus afterStep(StepExecution stepExecution) { * saveExecutionAttributes = true, doesn't have restoreFrom called on it. */ @Test - public void testNonRestartedJob() throws Exception { + void testNonRestartedJob() throws Exception { MockRestartableItemReader tasklet = new MockRestartableItemReader(); step.setTasklet(new TestingChunkOrientedTasklet<>(tasklet, itemWriter)); step.registerStream(tasklet); @@ -355,7 +351,7 @@ public void testNonRestartedJob() throws Exception { } @Test - public void testSuccessfulExecutionWithExecutionContext() throws Exception { + void testSuccessfulExecutionWithExecutionContext() throws Exception { final JobExecution jobExecution = new JobExecution(jobInstance, jobParameters); final StepExecution stepExecution = new StepExecution(step.getName(), jobExecution); step.setJobRepository(new JobRepositorySupport() { @@ -372,7 +368,7 @@ public void updateExecutionContext(StepExecution stepExecution) { } @Test - public void testSuccessfulExecutionWithFailureOnSaveOfExecutionContext() throws Exception { + void testSuccessfulExecutionWithFailureOnSaveOfExecutionContext() throws Exception { final JobExecution jobExecution = new JobExecution(jobInstance, jobParameters); final StepExecution stepExecution = new StepExecution(step.getName(), jobExecution); step.setJobRepository(new JobRepositorySupport() { @@ -399,19 +395,13 @@ public void updateExecutionContext(StepExecution stepExecution) { * false, doesn't have restore or getExecutionAttributes called on it. */ @Test - public void testNoSaveExecutionAttributesRestartableJob() { + void testNoSaveExecutionAttributesRestartableJob() { MockRestartableItemReader tasklet = new MockRestartableItemReader(); step.setTasklet(new TestingChunkOrientedTasklet<>(tasklet, itemWriter)); JobExecution jobExecutionContext = new JobExecution(jobInstance, jobParameters); StepExecution stepExecution = new StepExecution(step.getName(), jobExecutionContext); - try { - step.execute(stepExecution); - } - catch (Throwable t) { - fail(); - } - + assertDoesNotThrow(() -> step.execute(stepExecution)); assertFalse(tasklet.isRestoreFromCalled()); } @@ -420,7 +410,7 @@ public void testNoSaveExecutionAttributesRestartableJob() { * be restored because the Tasklet does not implement Restartable. */ @Test - public void testRestartJobOnNonRestartableTasklet() throws Exception { + void testRestartJobOnNonRestartableTasklet() throws Exception { step.setTasklet(new TestingChunkOrientedTasklet<>(new ItemReader() { @Nullable @Override @@ -435,7 +425,7 @@ public String read() throws Exception { } @Test - public void testStreamManager() throws Exception { + void testStreamManager() throws Exception { MockRestartableItemReader reader = new MockRestartableItemReader() { @Nullable @Override @@ -464,7 +454,7 @@ public void update(ExecutionContext executionContext) { } @Test - public void testDirectlyInjectedItemStream() throws Exception { + void testDirectlyInjectedItemStream() throws Exception { step.setStreams(new ItemStream[] { new ItemStreamSupport() { @Override public void update(ExecutionContext executionContext) { @@ -483,7 +473,7 @@ public void update(ExecutionContext executionContext) { } @Test - public void testDirectlyInjectedListener() throws Exception { + void testDirectlyInjectedListener() throws Exception { step.registerStepExecutionListener(new StepExecutionListener() { @Override public void beforeStep(StepExecution stepExecution) { @@ -504,7 +494,7 @@ public ExitStatus afterStep(StepExecution stepExecution) { } @Test - public void testListenerCalledBeforeStreamOpened() throws Exception { + void testListenerCalledBeforeStreamOpened() throws Exception { MockRestartableItemReader reader = new MockRestartableItemReader() { @Override public void beforeStep(StepExecution stepExecution) { @@ -525,7 +515,7 @@ public void open(ExecutionContext executionContext) throws ItemStreamException { } @Test - public void testAfterStep() throws Exception { + void testAfterStep() throws Exception { final ExitStatus customStatus = new ExitStatus("COMPLETED_CUSTOM"); @@ -552,7 +542,7 @@ public ExitStatus afterStep(StepExecution stepExecution) { } @Test - public void testDirectlyInjectedListenerOnError() throws Exception { + void testDirectlyInjectedListenerOnError() throws Exception { step.registerStepExecutionListener(new StepExecutionListener() { @Nullable @Override @@ -576,7 +566,7 @@ public String read() throws RuntimeException { } @Test - public void testDirectlyInjectedStreamWhichIsAlsoReader() throws Exception { + void testDirectlyInjectedStreamWhichIsAlsoReader() throws Exception { MockRestartableItemReader reader = new MockRestartableItemReader() { @Nullable @Override @@ -605,7 +595,7 @@ public void update(ExecutionContext executionContext) { } @Test - public void testStatusForInterruptedException() throws Exception { + void testStatusForInterruptedException() throws Exception { StepInterruptionPolicy interruptionPolicy = new StepInterruptionPolicy() { @@ -638,12 +628,12 @@ public String read() throws Exception { step.execute(stepExecution); assertEquals(BatchStatus.STOPPED, stepExecution.getStatus()); String msg = stepExecution.getExitStatus().getExitDescription(); - assertTrue("Message does not contain 'JobInterruptedException': " + msg, - msg.contains("JobInterruptedException")); + assertTrue(msg.contains("JobInterruptedException"), + "Message does not contain 'JobInterruptedException': " + msg); } @Test - public void testStatusForNormalFailure() throws Exception { + void testStatusForNormalFailure() throws Exception { ItemReader itemReader = new ItemReader() { @Nullable @@ -668,7 +658,7 @@ public String read() throws Exception { } @Test - public void testStatusForErrorFailure() throws Exception { + void testStatusForErrorFailure() throws Exception { ItemReader itemReader = new ItemReader() { @Nullable @@ -694,7 +684,7 @@ public String read() throws Exception { @SuppressWarnings("serial") @Test - public void testStatusForResetFailedException() throws Exception { + void testStatusForResetFailedException() throws Exception { ItemReader itemReader = new ItemReader() { @Nullable @@ -722,14 +712,13 @@ protected void doRollback(DefaultTransactionStatus status) throws TransactionExc step.execute(stepExecution); assertEquals(BatchStatus.UNKNOWN, stepExecution.getStatus()); String msg = stepExecution.getExitStatus().getExitDescription(); - assertTrue("Message does not contain ResetFailedException: " + msg, msg.contains("ResetFailedException")); + assertTrue(msg.contains("ResetFailedException"), "Message does not contain ResetFailedException: " + msg); // The original rollback was caused by this one: assertEquals("Bar", stepExecution.getFailureExceptions().get(0).getMessage()); } - @SuppressWarnings("serial") @Test - public void testStatusForCommitFailedException() throws Exception { + void testStatusForCommitFailedException() throws Exception { step.setTransactionManager(new ResourcelessTransactionManager() { @Override @@ -758,7 +747,7 @@ protected void doRollback(DefaultTransactionStatus status) throws TransactionExc } @Test - public void testStatusForFinalUpdateFailedException() throws Exception { + void testStatusForFinalUpdateFailedException() throws Exception { step.setJobRepository(new JobRepositorySupport()); step.setStreams(new ItemStream[] { new ItemStreamSupport() { @@ -784,7 +773,7 @@ public void close() throws ItemStreamException { } @Test - public void testStatusForCloseFailedException() throws Exception { + void testStatusForCloseFailedException() throws Exception { MockRestartableItemReader itemReader = new MockRestartableItemReader() { @Override @@ -818,7 +807,7 @@ public void close() throws ItemStreamException { * chunk - otherwise ItemStreams won't recognize it is restart scenario on next run. */ @Test - public void testRestartAfterFailureInFirstChunk() throws Exception { + void testRestartAfterFailureInFirstChunk() throws Exception { MockRestartableItemReader reader = new MockRestartableItemReader() { @Nullable @Override @@ -837,11 +826,11 @@ public String read() throws RuntimeException { Throwable expected = stepExecution.getFailureExceptions().get(0); assertEquals("CRASH!", expected.getMessage()); assertFalse(stepExecution.getExecutionContext().isEmpty()); - assertTrue(stepExecution.getExecutionContext().getString("spam").equals("bucket")); + assertEquals("bucket", stepExecution.getExecutionContext().getString("spam")); } @Test - public void testStepToCompletion() throws Exception { + void testStepToCompletion() throws Exception { RepeatTemplate template = new RepeatTemplate(); @@ -863,7 +852,7 @@ public void testStepToCompletion() throws Exception { * @throws JobInterruptedException */ @Test - public void testStepFailureInAfterStepCallback() throws JobInterruptedException { + void testStepFailureInAfterStepCallback() throws JobInterruptedException { StepExecutionListener listener = new StepExecutionListener() { @Nullable @Override @@ -880,7 +869,7 @@ public ExitStatus afterStep(StepExecution stepExecution) { } @Test - public void testNoRollbackFor() throws Exception { + void testNoRollbackFor() throws Exception { step.setTasklet(new Tasklet() { @Nullable @@ -893,7 +882,6 @@ public RepeatStatus execute(StepContribution contribution, ChunkContext chunkCon JobExecution jobExecutionContext = new JobExecution(jobInstance, jobParameters); StepExecution stepExecution = new StepExecution(step.getName(), jobExecutionContext); - @SuppressWarnings("serial") DefaultTransactionAttribute transactionAttribute = new DefaultTransactionAttribute() { @Override public boolean rollbackOn(Throwable ex) { @@ -907,7 +895,7 @@ public boolean rollbackOn(Throwable ex) { } @Test - public void testTaskletExecuteReturnNull() throws Exception { + void testTaskletExecuteReturnNull() throws Exception { step.setTasklet(new Tasklet() { @Nullable @Override diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/AbstractIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/AbstractIntegrationTests.java index e136803682..a487985a43 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/AbstractIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/AbstractIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2019 the original author or authors. + * Copyright 2006-2022 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. @@ -17,7 +17,7 @@ import javax.sql.DataSource; -import org.junit.Before; +import org.junit.jupiter.api.BeforeEach; import org.springframework.core.io.ClassPathResource; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; @@ -29,8 +29,8 @@ public class AbstractIntegrationTests { protected DataSource dataSource; - @Before - public void setUp() { + @BeforeEach + void setUp() { ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); databasePopulator.addScript(new ClassPathResource("/org/springframework/batch/core/schema-drop-hsqldb.sql")); databasePopulator.addScript(new ClassPathResource("/org/springframework/batch/core/schema-hsqldb.sql")); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/concurrent/ConcurrentTransactionTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/concurrent/ConcurrentTransactionTests.java index 726b22dff1..107ea8dda0 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/concurrent/ConcurrentTransactionTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/concurrent/ConcurrentTransactionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2021 the original author or authors. + * Copyright 2015-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,8 +21,7 @@ import java.sql.Statement; import javax.sql.DataSource; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; @@ -56,20 +55,18 @@ import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; import org.springframework.lang.Nullable; import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.transaction.annotation.Isolation; import org.springframework.util.ClassUtils; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Michael Minella * @author Mahmoud Ben Hassine */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = ConcurrentTransactionTests.ConcurrentJobConfiguration.class) -public class ConcurrentTransactionTests { +@SpringJUnitConfig(classes = ConcurrentTransactionTests.ConcurrentJobConfiguration.class) +class ConcurrentTransactionTests { @Autowired private Job concurrentJob; @@ -79,7 +76,7 @@ public class ConcurrentTransactionTests { @DirtiesContext @Test - public void testConcurrentLongRunningJobExecutions() throws Exception { + void testConcurrentLongRunningJobExecutions() throws Exception { JobExecution jobExecution = jobLauncher.run(concurrentJob, new JobParameters()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/football/FootballJobIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/football/FootballJobIntegrationTests.java index bad61b3ace..362c281872 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/football/FootballJobIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/football/FootballJobIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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,14 +16,13 @@ package org.springframework.batch.core.test.football; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import javax.sql.DataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -32,16 +31,14 @@ import org.springframework.batch.core.launch.JobLauncher; import org.springframework.batch.core.test.AbstractIntegrationTests; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * @author Mahmoud Ben Hassine * */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/META-INF/batch/footballJob.xml" }) +@SpringJUnitConfig(locations = { "/simple-job-launcher-context.xml", "/META-INF/batch/footballJob.xml" }) public class FootballJobIntegrationTests extends AbstractIntegrationTests { /** Logger */ @@ -59,7 +56,7 @@ public void setDataSource(DataSource dataSource) { } @Test - public void testLaunchJob() throws Exception { + void testLaunchJob() throws Exception { JobExecution execution = jobLauncher.run(job, new JobParametersBuilder().addLong("commit.interval", 10L).toJobParameters()); assertEquals(BatchStatus.COMPLETED, execution.getStatus()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/football/FootballJobSkipIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/football/FootballJobSkipIntegrationTests.java index de990f41cc..8c2e1751bf 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/football/FootballJobSkipIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/football/FootballJobSkipIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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,14 +16,13 @@ package org.springframework.batch.core.test.football; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import javax.sql.DataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -34,16 +33,14 @@ import org.springframework.batch.support.DatabaseType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer * @author Mahmoud Ben Hassine * */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/META-INF/batch/footballSkipJob.xml" }) +@SpringJUnitConfig(locations = { "/simple-job-launcher-context.xml", "/META-INF/batch/footballSkipJob.xml" }) public class FootballJobSkipIntegrationTests extends AbstractIntegrationTests { /** Logger */ @@ -67,7 +64,7 @@ public void setDataSource(DataSource dataSource) throws Exception { } @Test - public void testLaunchJob() throws Exception { + void testLaunchJob() throws Exception { try { if (databaseType == DatabaseType.POSTGRES || databaseType == DatabaseType.ORACLE) { // Extra special test for these platforms (would have failed diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/football/ParallelJobIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/football/ParallelJobIntegrationTests.java index baabdf7114..8a97177365 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/football/ParallelJobIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/football/ParallelJobIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2009 the original author or authors. + * Copyright 2006-2022 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,15 +16,14 @@ package org.springframework.batch.core.test.football; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import javax.sql.DataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -33,16 +32,14 @@ import org.springframework.batch.core.launch.JobLauncher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.jdbc.JdbcTestUtils; /** * @author Dave Syer * */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/META-INF/batch/parallelJob.xml" }) +@SpringJUnitConfig(locations = { "/simple-job-launcher-context.xml", "/META-INF/batch/parallelJob.xml" }) public class ParallelJobIntegrationTests { /** Logger */ @@ -61,13 +58,13 @@ public void setDataSource(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } - @Before - public void clear() { + @BeforeEach + void clear() { JdbcTestUtils.deleteFromTables(jdbcTemplate, "PLAYER_SUMMARY", "GAMES", "PLAYERS"); } @Test - public void testLaunchJob() throws Exception { + void testLaunchJob() throws Exception { JobExecution execution = jobLauncher.run(job, new JobParametersBuilder().toJobParameters()); assertEquals(BatchStatus.COMPLETED, execution.getStatus()); for (StepExecution stepExecution : execution.getStepExecutions()) { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/ldif/LdifReaderTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/ldif/LdifReaderTests.java index 87e292268f..2d5ad4aa46 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/ldif/LdifReaderTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/ldif/LdifReaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2021 the original author or authors. + * Copyright 2005-2022 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. @@ -15,16 +15,16 @@ */ package org.springframework.batch.core.test.ldif; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.net.MalformedURLException; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -35,17 +35,15 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.util.Assert; -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/applicationContext-test1.xml" }) +@SpringJUnitConfig(locations = { "/simple-job-launcher-context.xml", "/applicationContext-test1.xml" }) public class LdifReaderTests { - private Resource expected; + private final Resource expected; - private Resource actual; + private final Resource actual; @Autowired private JobLauncher jobLauncher; @@ -63,13 +61,13 @@ public LdifReaderTests() throws MalformedURLException { actual = new UrlResource("file:target/test-outputs/output.ldif"); } - @Before - public void checkFiles() { + @BeforeEach + void checkFiles() { Assert.isTrue(expected.exists(), "Expected does not exist."); } @Test - public void testValidRun() throws Exception { + void testValidRun() throws Exception { JobExecution jobExecution = jobLauncher.run(job1, new JobParameters()); // Ensure job completed successfully. @@ -82,7 +80,7 @@ public void testValidRun() throws Exception { } @Test - public void testResourceNotExists() throws Exception { + void testResourceNotExists() throws Exception { JobExecution jobExecution = jobLauncher.run(job2, new JobParameters()); Assert.isTrue(jobExecution.getExitStatus().getExitCode().equals("FAILED"), @@ -93,22 +91,16 @@ public void testResourceNotExists() throws Exception { } private void compareFiles(File expected, File actual) throws Exception { - BufferedReader expectedReader = new BufferedReader(new FileReader(expected)); - BufferedReader actualReader = new BufferedReader(new FileReader(actual)); - try { + try (BufferedReader expectedReader = new BufferedReader(new FileReader(expected)); + BufferedReader actualReader = new BufferedReader(new FileReader(actual))) { int lineNum = 1; for (String expectedLine = null; (expectedLine = expectedReader.readLine()) != null; lineNum++) { String actualLine = actualReader.readLine(); - assertEquals("Line number " + lineNum + " does not match.", expectedLine, actualLine); + assertEquals(expectedLine, actualLine, "Line number " + lineNum + " does not match."); } String actualLine = actualReader.readLine(); - assertEquals("More lines than expected. There should not be a line number " + lineNum + ".", null, - actualLine); - } - finally { - expectedReader.close(); - actualReader.close(); + assertNull(actualLine, "More lines than expected. There should not be a line number " + lineNum + "."); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/ldif/MappingLdifReaderTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/ldif/MappingLdifReaderTests.java index e1a92e13c3..e2c977d7ba 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/ldif/MappingLdifReaderTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/ldif/MappingLdifReaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2021 the original author or authors. + * Copyright 2005-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,9 +21,8 @@ import java.io.InputStreamReader; import java.net.MalformedURLException; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -37,19 +36,17 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.util.Assert; -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/applicationContext-test2.xml" }) +@SpringJUnitConfig(locations = { "/simple-job-launcher-context.xml", "/applicationContext-test2.xml" }) public class MappingLdifReaderTests { - private static Logger log = LoggerFactory.getLogger(MappingLdifReaderTests.class); + private static final Logger log = LoggerFactory.getLogger(MappingLdifReaderTests.class); - private Resource expected; + private final Resource expected; - private Resource actual; + private final Resource actual; @Autowired private JobLauncher launcher; @@ -67,13 +64,13 @@ public MappingLdifReaderTests() throws MalformedURLException { actual = new UrlResource("file:target/test-outputs/output.ldif"); } - @Before - public void checkFiles() { + @BeforeEach + void checkFiles() { Assert.isTrue(expected.exists(), "Expected does not exist."); } @Test - public void testValidRun() throws Exception { + void testValidRun() throws Exception { JobExecution jobExecution = launcher.run(job1, new JobParameters()); // Ensure job completed successfully. @@ -86,7 +83,7 @@ public void testValidRun() throws Exception { } @Test - public void testResourceNotExists() throws Exception { + void testResourceNotExists() throws Exception { JobExecution jobExecution = launcher.run(job2, new JobParameters()); Assert.isTrue(jobExecution.getExitStatus().getExitCode().equals("FAILED"), diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/ldif/builder/LdifReaderBuilderTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/ldif/builder/LdifReaderBuilderTests.java index ecd58168e7..cda0324926 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/ldif/builder/LdifReaderBuilderTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/ldif/builder/LdifReaderBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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,9 +16,8 @@ package org.springframework.batch.core.test.ldif.builder; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemStreamException; @@ -29,18 +28,18 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.ldap.core.LdapAttributes; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * @author Glenn Renfro * @author Mahmoud Ben Hassine */ -@RunWith(SpringRunner.class) -public class LdifReaderBuilderTests { +@SpringJUnitConfig +class LdifReaderBuilderTests { @Autowired private ApplicationContext context; @@ -49,8 +48,8 @@ public class LdifReaderBuilderTests { private String callbackAttributeName; - @After - public void tearDown() { + @AfterEach + void tearDown() { this.callbackAttributeName = null; if (this.ldifReader != null) { this.ldifReader.close(); @@ -58,85 +57,83 @@ public void tearDown() { } @Test - public void testSkipRecord() throws Exception { + void testSkipRecord() throws Exception { this.ldifReader = new LdifReaderBuilder().recordsToSkip(1).resource(context.getResource("classpath:/test.ldif")) .name("foo").build(); LdapAttributes ldapAttributes = firstRead(); - assertEquals("The attribute name for the second record did not match expected result", - "cn=Bjorn Jensen, ou=Accounting, dc=airius, dc=com", ldapAttributes.getName().toString()); + assertEquals("cn=Bjorn Jensen, ou=Accounting, dc=airius, dc=com", ldapAttributes.getName().toString(), + "The attribute name for the second record did not match expected result"); } @Test - public void testBasicRead() throws Exception { + void testBasicRead() throws Exception { this.ldifReader = new LdifReaderBuilder().resource(context.getResource("classpath:/test.ldif")).name("foo") .build(); LdapAttributes ldapAttributes = firstRead(); - assertEquals("The attribute name for the first record did not match expected result", - "cn=Barbara Jensen, ou=Product Development, dc=airius, dc=com", ldapAttributes.getName().toString()); + assertEquals("cn=Barbara Jensen, ou=Product Development, dc=airius, dc=com", + ldapAttributes.getName().toString(), + "The attribute name for the first record did not match expected result"); } @Test - public void testCurrentItemCount() throws Exception { + void testCurrentItemCount() throws Exception { this.ldifReader = new LdifReaderBuilder().currentItemCount(3) .resource(context.getResource("classpath:/test.ldif")).name("foo").build(); LdapAttributes ldapAttributes = firstRead(); - assertEquals("The attribute name for the third record did not match expected result", - "cn=Gern Jensen, ou=Product Testing, dc=airius, dc=com", ldapAttributes.getName().toString()); + assertEquals("cn=Gern Jensen, ou=Product Testing, dc=airius, dc=com", ldapAttributes.getName().toString(), + "The attribute name for the third record did not match expected result"); } @Test - public void testMaxItemCount() throws Exception { + void testMaxItemCount() throws Exception { this.ldifReader = new LdifReaderBuilder().maxItemCount(1).resource(context.getResource("classpath:/test.ldif")) .name("foo").build(); LdapAttributes ldapAttributes = firstRead(); - assertEquals("The attribute name for the first record did not match expected result", - "cn=Barbara Jensen, ou=Product Development, dc=airius, dc=com", ldapAttributes.getName().toString()); + assertEquals("cn=Barbara Jensen, ou=Product Development, dc=airius, dc=com", + ldapAttributes.getName().toString(), + "The attribute name for the first record did not match expected result"); ldapAttributes = this.ldifReader.read(); - assertNull("The second read should have returned null", ldapAttributes); + assertNull(ldapAttributes, "The second read should have returned null"); } @Test - public void testSkipRecordCallback() throws Exception { + void testSkipRecordCallback() throws Exception { this.ldifReader = new LdifReaderBuilder().recordsToSkip(1).skippedRecordsCallback(new TestCallBackHandler()) .resource(context.getResource("classpath:/test.ldif")).name("foo").build(); firstRead(); - assertEquals("The attribute name from the callback handler did not match the expected result", - "cn=Barbara Jensen, ou=Product Development, dc=airius, dc=com", this.callbackAttributeName); + assertEquals("cn=Barbara Jensen, ou=Product Development, dc=airius, dc=com", this.callbackAttributeName, + "The attribute name from the callback handler did not match the expected result"); } @Test - public void testSaveState() throws Exception { + void testSaveState() throws Exception { this.ldifReader = new LdifReaderBuilder().resource(context.getResource("classpath:/test.ldif")).name("foo") .build(); ExecutionContext executionContext = new ExecutionContext(); firstRead(executionContext); this.ldifReader.update(executionContext); - assertEquals("foo.read.count did not have the expected result", 1, executionContext.getInt("foo.read.count")); + assertEquals(1, executionContext.getInt("foo.read.count"), "foo.read.count did not have the expected result"); } @Test - public void testSaveStateDisabled() throws Exception { + void testSaveStateDisabled() throws Exception { this.ldifReader = new LdifReaderBuilder().saveState(false).resource(context.getResource("classpath:/test.ldif")) .build(); ExecutionContext executionContext = new ExecutionContext(); firstRead(executionContext); this.ldifReader.update(executionContext); - assertEquals("ExecutionContext should have been empty", 0, executionContext.size()); + assertEquals(0, executionContext.size(), "ExecutionContext should have been empty"); } @Test - public void testStrict() { + void testStrict() { // Test that strict when enabled will throw an exception. - try { - this.ldifReader = new LdifReaderBuilder().resource(context.getResource("classpath:/teadsfst.ldif")) - .name("foo").build(); - this.ldifReader.open(new ExecutionContext()); - fail("IllegalStateException should have been thrown, because strict was set to true"); - } - catch (ItemStreamException ise) { - assertEquals("IllegalStateException message did not match the expected result.", - "Failed to initialize the reader", ise.getMessage()); - } + this.ldifReader = new LdifReaderBuilder().resource(context.getResource("classpath:/teadsfst.ldif")).name("foo") + .build(); + Exception exception = assertThrows(ItemStreamException.class, + () -> this.ldifReader.open(new ExecutionContext())); + assertEquals("Failed to initialize the reader", exception.getMessage(), + "IllegalStateException message did not match the expected result."); // Test that strict when disabled will still allow the ldap resource to be opened. this.ldifReader = new LdifReaderBuilder().strict(false) .resource(context.getResource("classpath:/teadsfst.ldif")).name("foo").build(); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/ldif/builder/MappingLdifReaderBuilderTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/ldif/builder/MappingLdifReaderBuilderTests.java index ef4c415651..6e738cf349 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/ldif/builder/MappingLdifReaderBuilderTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/ldif/builder/MappingLdifReaderBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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,9 +16,8 @@ package org.springframework.batch.core.test.ldif.builder; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemStreamException; @@ -31,18 +30,18 @@ import org.springframework.context.annotation.Configuration; import org.springframework.lang.Nullable; import org.springframework.ldap.core.LdapAttributes; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * @author Glenn Renfro * @author Mahmoud Ben Hassine */ -@RunWith(SpringRunner.class) -public class MappingLdifReaderBuilderTests { +@SpringJUnitConfig +class MappingLdifReaderBuilderTests { @Autowired private ApplicationContext context; @@ -51,8 +50,8 @@ public class MappingLdifReaderBuilderTests { private String callbackAttributeName; - @After - public void tearDown() { + @AfterEach + void tearDown() { this.callbackAttributeName = null; if (this.mappingLdifReader != null) { this.mappingLdifReader.close(); @@ -60,89 +59,87 @@ public void tearDown() { } @Test - public void testSkipRecord() throws Exception { + void testSkipRecord() throws Exception { this.mappingLdifReader = new MappingLdifReaderBuilder().recordsToSkip(1) .recordMapper(new TestMapper()).resource(context.getResource("classpath:/test.ldif")).name("foo") .build(); LdapAttributes ldapAttributes = firstRead(); - assertEquals("The attribute name for the second record did not match expected result", - "cn=Bjorn Jensen, ou=Accounting, dc=airius, dc=com", ldapAttributes.getName().toString()); + assertEquals("cn=Bjorn Jensen, ou=Accounting, dc=airius, dc=com", ldapAttributes.getName().toString(), + "The attribute name for the second record did not match expected result"); } @Test - public void testBasicRead() throws Exception { + void testBasicRead() throws Exception { this.mappingLdifReader = new MappingLdifReaderBuilder().recordMapper(new TestMapper()) .resource(context.getResource("classpath:/test.ldif")).name("foo").build(); LdapAttributes ldapAttributes = firstRead(); - assertEquals("The attribute name for the first record did not match expected result", - "cn=Barbara Jensen, ou=Product Development, dc=airius, dc=com", ldapAttributes.getName().toString()); + assertEquals("cn=Barbara Jensen, ou=Product Development, dc=airius, dc=com", + ldapAttributes.getName().toString(), + "The attribute name for the first record did not match expected result"); } @Test - public void testCurrentItemCount() throws Exception { + void testCurrentItemCount() throws Exception { this.mappingLdifReader = new MappingLdifReaderBuilder().currentItemCount(3) .recordMapper(new TestMapper()).resource(context.getResource("classpath:/test.ldif")).name("foo") .build(); LdapAttributes ldapAttributes = firstRead(); - assertEquals("The attribute name for the third record did not match expected result", - "cn=Gern Jensen, ou=Product Testing, dc=airius, dc=com", ldapAttributes.getName().toString()); + assertEquals("cn=Gern Jensen, ou=Product Testing, dc=airius, dc=com", ldapAttributes.getName().toString(), + "The attribute name for the third record did not match expected result"); } @Test - public void testMaxItemCount() throws Exception { + void testMaxItemCount() throws Exception { this.mappingLdifReader = new MappingLdifReaderBuilder().maxItemCount(1) .recordMapper(new TestMapper()).resource(context.getResource("classpath:/test.ldif")).name("foo") .build(); LdapAttributes ldapAttributes = firstRead(); - assertEquals("The attribute name for the first record did not match expected result", - "cn=Barbara Jensen, ou=Product Development, dc=airius, dc=com", ldapAttributes.getName().toString()); + assertEquals("cn=Barbara Jensen, ou=Product Development, dc=airius, dc=com", + ldapAttributes.getName().toString(), + "The attribute name for the first record did not match expected result"); ldapAttributes = this.mappingLdifReader.read(); - assertNull("The second read should have returned null", ldapAttributes); + assertNull(ldapAttributes, "The second read should have returned null"); } @Test - public void testSkipRecordCallback() throws Exception { + void testSkipRecordCallback() throws Exception { this.mappingLdifReader = new MappingLdifReaderBuilder().recordsToSkip(1) .recordMapper(new TestMapper()).skippedRecordsCallback(new TestCallBackHandler()) .resource(context.getResource("classpath:/test.ldif")).name("foo").build(); firstRead(); - assertEquals("The attribute name from the callback handler did not match the expected result", - "cn=Barbara Jensen, ou=Product Development, dc=airius, dc=com", this.callbackAttributeName); + assertEquals("cn=Barbara Jensen, ou=Product Development, dc=airius, dc=com", this.callbackAttributeName, + "The attribute name from the callback handler did not match the expected result"); } @Test - public void testSaveState() throws Exception { + void testSaveState() throws Exception { this.mappingLdifReader = new MappingLdifReaderBuilder().recordMapper(new TestMapper()) .resource(context.getResource("classpath:/test.ldif")).name("foo").build(); ExecutionContext executionContext = new ExecutionContext(); firstRead(executionContext); this.mappingLdifReader.update(executionContext); - assertEquals("foo.read.count did not have the expected result", 1, executionContext.getInt("foo.read.count")); + assertEquals(1, executionContext.getInt("foo.read.count"), "foo.read.count did not have the expected result"); } @Test - public void testSaveStateDisabled() throws Exception { + void testSaveStateDisabled() throws Exception { this.mappingLdifReader = new MappingLdifReaderBuilder().saveState(false) .recordMapper(new TestMapper()).resource(context.getResource("classpath:/test.ldif")).build(); ExecutionContext executionContext = new ExecutionContext(); firstRead(executionContext); this.mappingLdifReader.update(executionContext); - assertEquals("ExecutionContext should have been empty", 0, executionContext.size()); + assertEquals(0, executionContext.size(), "ExecutionContext should have been empty"); } @Test - public void testStrict() { + void testStrict() { // Test that strict when enabled will throw an exception. - try { - this.mappingLdifReader = new MappingLdifReaderBuilder().recordMapper(new TestMapper()) - .resource(context.getResource("classpath:/teadsfst.ldif")).name("foo").build(); - this.mappingLdifReader.open(new ExecutionContext()); - fail("IllegalStateException should have been thrown, because strict was set to true"); - } - catch (ItemStreamException ise) { - assertEquals("IllegalStateException message did not match the expected result.", - "Failed to initialize the reader", ise.getMessage()); - } + this.mappingLdifReader = new MappingLdifReaderBuilder().recordMapper(new TestMapper()) + .resource(context.getResource("classpath:/teadsfst.ldif")).name("foo").build(); + Exception exception = assertThrows(ItemStreamException.class, + () -> this.mappingLdifReader.open(new ExecutionContext())); + assertEquals("Failed to initialize the reader", exception.getMessage(), + "IllegalStateException message did not match the expected result."); // Test that strict when disabled will still allow the ldap resource to be opened. this.mappingLdifReader = new MappingLdifReaderBuilder().strict(false).name("foo") .recordMapper(new TestMapper()).resource(context.getResource("classpath:/teadsfst.ldif")).build(); @@ -150,17 +147,12 @@ public void testStrict() { } @Test - public void testNullRecordMapper() { - try { - this.mappingLdifReader = new MappingLdifReaderBuilder() - .resource(context.getResource("classpath:/teadsfst.ldif")).build(); - fail("IllegalArgumentException should have been thrown"); - } - catch (IllegalArgumentException ise) { - assertEquals("IllegalArgumentException message did not match the expected result.", - "RecordMapper is required.", ise.getMessage()); - } - + void testNullRecordMapper() { + Exception exception = assertThrows(IllegalArgumentException.class, + () -> new MappingLdifReaderBuilder() + .resource(context.getResource("classpath:/teadsfst.ldif")).build()); + assertEquals("RecordMapper is required.", exception.getMessage(), + "IllegalArgumentException message did not match the expected result."); } private LdapAttributes firstRead() throws Exception { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/Db2JobRepositoryIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/Db2JobRepositoryIntegrationTests.java index bfacd9ee0a..bcf3e9fd4b 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/Db2JobRepositoryIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/Db2JobRepositoryIntegrationTests.java @@ -18,12 +18,11 @@ import javax.sql.DataSource; import com.ibm.db2.jcc.DB2SimpleDataSource; -import org.junit.Assert; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.testcontainers.containers.Db2Container; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.utility.DockerImageName; import org.springframework.batch.core.ExitStatus; @@ -41,20 +40,22 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Mahmoud Ben Hassine */ -@RunWith(SpringRunner.class) -@ContextConfiguration -public class Db2JobRepositoryIntegrationTests { +@Testcontainers +@SpringJUnitConfig +class Db2JobRepositoryIntegrationTests { // TODO find the best way to externalize and manage image versions private static final DockerImageName DB2_IMAGE = DockerImageName.parse("ibmcom/db2:11.5.5.1"); - @ClassRule + @Container public static Db2Container db2 = new Db2Container(DB2_IMAGE).acceptLicense(); @Autowired @@ -66,15 +67,15 @@ public class Db2JobRepositoryIntegrationTests { @Autowired private Job job; - @Before - public void setUp() { + @BeforeEach + void setUp() { ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); databasePopulator.addScript(new ClassPathResource("/org/springframework/batch/core/schema-db2.sql")); databasePopulator.execute(this.dataSource); } @Test - public void testJobExecution() throws Exception { + void testJobExecution() throws Exception { // given JobParameters jobParameters = new JobParametersBuilder().toJobParameters(); @@ -82,8 +83,8 @@ public void testJobExecution() throws Exception { JobExecution jobExecution = this.jobLauncher.run(this.job, jobParameters); // then - Assert.assertNotNull(jobExecution); - Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); + assertNotNull(jobExecution); + assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); } @Configuration diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/DerbyJobRepositoryIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/DerbyJobRepositoryIntegrationTests.java index fff5577f3f..9b069a7cc9 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/DerbyJobRepositoryIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/DerbyJobRepositoryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2021 the original author or authors. + * Copyright 2020-2022 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. @@ -17,9 +17,7 @@ import javax.sql.DataSource; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.Job; @@ -36,15 +34,16 @@ import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Mahmoud Ben Hassine */ -@RunWith(SpringRunner.class) -@ContextConfiguration -public class DerbyJobRepositoryIntegrationTests { +@SpringJUnitConfig +class DerbyJobRepositoryIntegrationTests { @Autowired private JobLauncher jobLauncher; @@ -53,7 +52,7 @@ public class DerbyJobRepositoryIntegrationTests { private Job job; @Test - public void testJobExecution() throws Exception { + void testJobExecution() throws Exception { // given JobParameters jobParameters = new JobParametersBuilder().toJobParameters(); @@ -61,8 +60,8 @@ public void testJobExecution() throws Exception { JobExecution jobExecution = this.jobLauncher.run(this.job, jobParameters); // then - Assert.assertNotNull(jobExecution); - Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); + assertNotNull(jobExecution); + assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); } @Configuration diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/H2CompatibilityModeJobRepositoryIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/H2CompatibilityModeJobRepositoryIntegrationTests.java index dbd690a95b..f21c62a551 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/H2CompatibilityModeJobRepositoryIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/H2CompatibilityModeJobRepositoryIntegrationTests.java @@ -15,17 +15,13 @@ */ package org.springframework.batch.core.test.repository; -import java.util.Arrays; -import java.util.List; import java.util.UUID; import javax.sql.DataSource; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.h2.engine.Mode.ModeEnum; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.Job; @@ -44,39 +40,36 @@ import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + /** * @author Henning Pƶttker */ -@RunWith(Parameterized.class) -public class H2CompatibilityModeJobRepositoryIntegrationTests { - - private final String compatibilityMode; - - public H2CompatibilityModeJobRepositoryIntegrationTests(String compatibilityMode) { - this.compatibilityMode = compatibilityMode; - } +class H2CompatibilityModeJobRepositoryIntegrationTests { - @Test - public void testJobExecution() throws Exception { + @EnumSource(ModeEnum.class) + @ParameterizedTest + void testJobExecution(ModeEnum compatibilityMode) throws Exception { var context = new AnnotationConfigApplicationContext(); context.register(TestConfiguration.class); - context.registerBean(DataSource.class, this::buildDataSource); + context.registerBean(DataSource.class, () -> buildDataSource(compatibilityMode)); context.refresh(); var jobLauncher = context.getBean(JobLauncher.class); var job = context.getBean(Job.class); var jobExecution = jobLauncher.run(job, new JobParameters()); - Assert.assertNotNull(jobExecution); - Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); + assertNotNull(jobExecution); + assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); var jdbcTemplate = new JdbcTemplate(context.getBean(DataSource.class)); jdbcTemplate.execute("SHUTDOWN"); } - private DataSource buildDataSource() { + private static DataSource buildDataSource(ModeEnum compatibilityMode) { var connectionUrl = String.format("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false;MODE=%s", - UUID.randomUUID(), this.compatibilityMode); + UUID.randomUUID(), compatibilityMode); var dataSource = new SimpleDriverDataSource(new org.h2.Driver(), connectionUrl, "sa", ""); var populator = new ResourceDatabasePopulator(); var resource = new DefaultResourceLoader().getResource("/org/springframework/batch/core/schema-h2.sql"); @@ -98,10 +91,4 @@ Job job(JobBuilderFactory jobs, StepBuilderFactory steps) { } - @Parameters - public static List data() throws Exception { - return Arrays.stream(org.h2.engine.Mode.ModeEnum.values()).map(mode -> new Object[] { mode.toString() }) - .toList(); - } - } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/H2JobRepositoryIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/H2JobRepositoryIntegrationTests.java index d43836d6bd..3f55519e4c 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/H2JobRepositoryIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/H2JobRepositoryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2021 the original author or authors. + * Copyright 2020-2022 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. @@ -17,9 +17,7 @@ import javax.sql.DataSource; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.Job; @@ -36,15 +34,16 @@ import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Mahmoud Ben Hassine */ -@RunWith(SpringRunner.class) -@ContextConfiguration -public class H2JobRepositoryIntegrationTests { +@SpringJUnitConfig +class H2JobRepositoryIntegrationTests { @Autowired private JobLauncher jobLauncher; @@ -53,7 +52,7 @@ public class H2JobRepositoryIntegrationTests { private Job job; @Test - public void testJobExecution() throws Exception { + void testJobExecution() throws Exception { // given JobParameters jobParameters = new JobParametersBuilder().toJobParameters(); @@ -61,8 +60,8 @@ public void testJobExecution() throws Exception { JobExecution jobExecution = this.jobLauncher.run(this.job, jobParameters); // then - Assert.assertNotNull(jobExecution); - Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); + assertNotNull(jobExecution); + assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); } @Configuration diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/HANAJobRepositoryIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/HANAJobRepositoryIntegrationTests.java index e9aaf3d4f6..888f9f36f3 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/HANAJobRepositoryIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/HANAJobRepositoryIntegrationTests.java @@ -17,21 +17,16 @@ import java.time.Duration; import java.time.temporal.ChronoUnit; -import java.util.Arrays; import java.util.HashMap; -import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.sql.DataSource; import com.github.dockerjava.api.model.Ulimit; -import org.junit.Assert; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -47,16 +42,20 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.testcontainers.containers.JdbcDatabaseContainer; import org.testcontainers.containers.wait.strategy.LogMessageWaitStrategy; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.utility.DockerImageName; import com.sap.db.jdbcext.HanaDataSource; import org.testcontainers.utility.LicenseAcceptance; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + /** * The official Docker image for SAP HANA is not publicly available. SAP HANA support is * tested manually. See @@ -67,15 +66,15 @@ * @author Jonathan Bregler * @author Mahmoud Ben Hassine */ -@RunWith(SpringRunner.class) -@ContextConfiguration -@Ignore("Official Docker image for SAP HANA not publicly available and works only on Linux") -public class HANAJobRepositoryIntegrationTests { +@Testcontainers +@SpringJUnitConfig +@Disabled("Official Docker image for SAP HANA not publicly available and works only on Linux") +class HANAJobRepositoryIntegrationTests { private static final DockerImageName HANA_IMAGE = DockerImageName .parse("store/saplabs/hanaexpress:2.00.057.00.20211207.1"); - @ClassRule + @Container public static HANAContainer hana = new HANAContainer<>(HANA_IMAGE).acceptLicense(); @Autowired @@ -87,15 +86,15 @@ public class HANAJobRepositoryIntegrationTests { @Autowired private Job job; - @Before - public void setUp() { + @BeforeEach + void setUp() { ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); databasePopulator.addScript(new ClassPathResource("/org/springframework/batch/core/schema-hana.sql")); databasePopulator.execute(this.dataSource); } @Test - public void testJobExecution() throws Exception { + void testJobExecution() throws Exception { // given JobParameters jobParameters = new JobParametersBuilder().toJobParameters(); @@ -103,8 +102,8 @@ public void testJobExecution() throws Exception { JobExecution jobExecution = this.jobLauncher.run(this.job, jobParameters); // then - Assert.assertNotNull(jobExecution); - Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); + assertNotNull(jobExecution); + assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); } @Configuration @@ -132,7 +131,7 @@ public Job job(JobBuilderFactory jobs, StepBuilderFactory steps) { /** * @author Jonathan Bregler */ - public static class HANAContainer> extends JdbcDatabaseContainer { + static class HANAContainer> extends JdbcDatabaseContainer { private static final Integer PORT = 39041; @@ -197,7 +196,7 @@ public SELF acceptLicense() { @Override public Set getLivenessCheckPortNumbers() { - return new HashSet<>(Arrays.asList(new Integer[] { getMappedPort(PORT) })); + return Set.of(getMappedPort(PORT)); } @Override diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/HSQLDBJobRepositoryIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/HSQLDBJobRepositoryIntegrationTests.java index 049c3f61e0..eecdd73aa1 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/HSQLDBJobRepositoryIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/HSQLDBJobRepositoryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2021 the original author or authors. + * Copyright 2020-2022 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. @@ -17,9 +17,7 @@ import javax.sql.DataSource; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.Job; @@ -36,15 +34,16 @@ import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Mahmoud Ben Hassine */ -@RunWith(SpringRunner.class) -@ContextConfiguration -public class HSQLDBJobRepositoryIntegrationTests { +@SpringJUnitConfig +class HSQLDBJobRepositoryIntegrationTests { @Autowired private JobLauncher jobLauncher; @@ -53,7 +52,7 @@ public class HSQLDBJobRepositoryIntegrationTests { private Job job; @Test - public void testJobExecution() throws Exception { + void testJobExecution() throws Exception { // given JobParameters jobParameters = new JobParametersBuilder().toJobParameters(); @@ -61,8 +60,8 @@ public void testJobExecution() throws Exception { JobExecution jobExecution = this.jobLauncher.run(this.job, jobParameters); // then - Assert.assertNotNull(jobExecution); - Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); + assertNotNull(jobExecution); + assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); } @Configuration diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/JdbcJobRepositoryTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/JdbcJobRepositoryTests.java index 149dae03e4..d8778602bb 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/JdbcJobRepositoryTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/JdbcJobRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -26,9 +26,8 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.JobExecution; @@ -38,26 +37,24 @@ import org.springframework.batch.core.test.AbstractIntegrationTests; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.jdbc.JdbcTestUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = { "/simple-job-launcher-context.xml" }) -public class JdbcJobRepositoryTests extends AbstractIntegrationTests { +@SpringJUnitConfig(locations = { "/simple-job-launcher-context.xml" }) +class JdbcJobRepositoryTests extends AbstractIntegrationTests { private JobSupport job; - private Set jobExecutionIds = new HashSet<>(); + private final Set jobExecutionIds = new HashSet<>(); - private Set jobIds = new HashSet<>(); + private final Set jobIds = new HashSet<>(); - private List list = new ArrayList<>(); + private final List list = new ArrayList<>(); private JdbcTemplate jdbcTemplate; @@ -73,26 +70,24 @@ public void setDataSource(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } - @Before - public void onSetUpInTransaction() throws Exception { - super.setUp(); + @BeforeEach + void onSetUpInTransaction() { job = new JobSupport("test-job"); job.setRestartable(true); } @Test - public void testFindOrCreateJob() throws Exception { + void testFindOrCreateJob() throws Exception { job.setName("foo"); int before = 0; JobExecution execution = repository.createJobExecution(job.getName(), new JobParameters()); int after = JdbcTestUtils.countRowsInTable(jdbcTemplate, "BATCH_JOB_INSTANCE"); - ; assertEquals(before + 1, after); assertNotNull(execution.getId()); } @Test - public void testFindOrCreateJobWithExecutionContext() throws Exception { + void testFindOrCreateJobWithExecutionContext() throws Exception { job.setName("foo"); int before = 0; JobExecution execution = repository.createJobExecution(job.getName(), new JobParameters()); @@ -107,7 +102,7 @@ public void testFindOrCreateJobWithExecutionContext() throws Exception { } @Test - public void testFindOrCreateJobConcurrently() throws Exception { + void testFindOrCreateJobConcurrently() { job.setName("bar"); @@ -115,13 +110,7 @@ public void testFindOrCreateJobConcurrently() throws Exception { assertEquals(0, before); long t0 = System.currentTimeMillis(); - try { - doConcurrentStart(); - fail("Expected JobExecutionAlreadyRunningException"); - } - catch (JobExecutionAlreadyRunningException e) { - // expected - } + assertThrows(JobExecutionAlreadyRunningException.class, this::doConcurrentStart); long t1 = System.currentTimeMillis(); JobExecution execution = (JobExecution) list.get(0); @@ -137,7 +126,7 @@ public void testFindOrCreateJobConcurrently() throws Exception { } @Test - public void testFindOrCreateJobConcurrentlyWhenJobAlreadyExists() throws Exception { + void testFindOrCreateJobConcurrentlyWhenJobAlreadyExists() throws Exception { job = new JobSupport("test-job"); job.setRestartable(true); @@ -153,13 +142,7 @@ public void testFindOrCreateJobConcurrentlyWhenJobAlreadyExists() throws Excepti assertEquals(1, before); long t0 = System.currentTimeMillis(); - try { - doConcurrentStart(); - fail("Expected JobExecutionAlreadyRunningException"); - } - catch (JobExecutionAlreadyRunningException e) { - // expected - } + assertThrows(JobExecutionAlreadyRunningException.class, this::doConcurrentStart); long t1 = System.currentTimeMillis(); int after = JdbcTestUtils.countRowsInTable(jdbcTemplate, "BATCH_JOB_INSTANCE"); @@ -210,8 +193,8 @@ public void run() { Thread.sleep(200); } - assertEquals("Timed out waiting for JobExecution to be created", 1, list.size()); - assertTrue("JobExecution not created in thread: " + list.get(0), list.get(0) instanceof JobExecution); + assertEquals(1, list.size(), "Timed out waiting for JobExecution to be created"); + assertTrue(list.get(0) instanceof JobExecution, "JobExecution not created in thread: " + list.get(0)); return (JobExecution) list.get(0); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/MySQLJdbcJobRepositoryIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/MySQLJdbcJobRepositoryIntegrationTests.java index b107f8cb8e..a73f8f347f 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/MySQLJdbcJobRepositoryIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/MySQLJdbcJobRepositoryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2021 the original author or authors. + * Copyright 2020-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,12 +21,11 @@ import javax.sql.DataSource; import com.mysql.cj.jdbc.MysqlDataSource; -import org.junit.Assert; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.testcontainers.containers.MySQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.utility.DockerImageName; import org.springframework.batch.core.Job; @@ -48,21 +47,22 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Mahmoud Ben Hassine */ -@RunWith(SpringRunner.class) -@ContextConfiguration -public class MySQLJdbcJobRepositoryIntegrationTests { +@Testcontainers +@SpringJUnitConfig +class MySQLJdbcJobRepositoryIntegrationTests { // TODO find the best way to externalize and manage image versions // when implementing https://github.com/spring-projects/spring-batch/issues/3092 private static final DockerImageName MYSQL_IMAGE = DockerImageName.parse("mysql:8.0.24"); - @ClassRule + @Container public static MySQLContainer mysql = new MySQLContainer<>(MYSQL_IMAGE); @Autowired @@ -77,8 +77,8 @@ public class MySQLJdbcJobRepositoryIntegrationTests { @Autowired private Job job; - @Before - public void setUp() { + @BeforeEach + void setUp() { ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); databasePopulator.addScript(new ClassPathResource("/org/springframework/batch/core/schema-mysql.sql")); databasePopulator.execute(this.dataSource); @@ -98,7 +98,7 @@ public void setUp() { * addLong("date", date.getTime()) for instance). */ @Test - public void testDateMillisecondPrecision() throws Exception { + void testDateMillisecondPrecision() throws Exception { // given Date date = new Date(); JobParameters jobParameters = new JobParametersBuilder().addDate("date", date).toJobParameters(); @@ -111,9 +111,9 @@ public void testDateMillisecondPrecision() throws Exception { // then List jobInstances = this.jobOperator.getJobInstances("job", 0, 100); - Assert.assertEquals(1, jobInstances.size()); + assertEquals(1, jobInstances.size()); List jobExecutions = this.jobOperator.getExecutions(jobInstances.get(0)); - Assert.assertEquals(2, jobExecutions.size()); + assertEquals(2, jobExecutions.size()); } @Configuration diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/MySQLJobRepositoryIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/MySQLJobRepositoryIntegrationTests.java index f2f8b1396c..524e586e00 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/MySQLJobRepositoryIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/MySQLJobRepositoryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2021 the original author or authors. + * Copyright 2020-2022 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. @@ -18,12 +18,11 @@ import javax.sql.DataSource; import com.mysql.cj.jdbc.MysqlDataSource; -import org.junit.Assert; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.testcontainers.containers.MySQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.utility.DockerImageName; import org.springframework.batch.core.ExitStatus; @@ -41,20 +40,22 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Mahmoud Ben Hassine */ -@RunWith(SpringRunner.class) -@ContextConfiguration -public class MySQLJobRepositoryIntegrationTests { +@Testcontainers +@SpringJUnitConfig +class MySQLJobRepositoryIntegrationTests { // TODO find the best way to externalize and manage image versions private static final DockerImageName MYSQL_IMAGE = DockerImageName.parse("mysql:8.0.25"); - @ClassRule + @Container public static MySQLContainer mysql = new MySQLContainer<>(MYSQL_IMAGE); @Autowired @@ -66,15 +67,15 @@ public class MySQLJobRepositoryIntegrationTests { @Autowired private Job job; - @Before - public void setUp() { + @BeforeEach + void setUp() { ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); databasePopulator.addScript(new ClassPathResource("/org/springframework/batch/core/schema-mysql.sql")); databasePopulator.execute(this.dataSource); } @Test - public void testJobExecution() throws Exception { + void testJobExecution() throws Exception { // given JobParameters jobParameters = new JobParametersBuilder().toJobParameters(); @@ -82,8 +83,8 @@ public void testJobExecution() throws Exception { JobExecution jobExecution = this.jobLauncher.run(this.job, jobParameters); // then - Assert.assertNotNull(jobExecution); - Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); + assertNotNull(jobExecution); + assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); } @Configuration diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/OracleJobRepositoryIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/OracleJobRepositoryIntegrationTests.java index 20ea0663ea..70376d6136 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/OracleJobRepositoryIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/OracleJobRepositoryIntegrationTests.java @@ -18,13 +18,12 @@ import javax.sql.DataSource; import oracle.jdbc.pool.OracleDataSource; -import org.junit.Assert; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.testcontainers.containers.OracleContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.utility.DockerImageName; import org.springframework.batch.core.ExitStatus; @@ -42,8 +41,10 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Official Docker images for Oracle are not publicly available. Oracle support is tested @@ -53,15 +54,15 @@ * * @author Mahmoud Ben Hassine */ -@RunWith(SpringRunner.class) -@ContextConfiguration -@Ignore("Official Docker images for Oracle are not publicly available") -public class OracleJobRepositoryIntegrationTests { +@Testcontainers +@SpringJUnitConfig +@Disabled("Official Docker images for Oracle are not publicly available") +class OracleJobRepositoryIntegrationTests { // TODO find the best way to externalize and manage image versions private static final DockerImageName ORACLE_IMAGE = DockerImageName.parse("oracle/database:11.2.0.2-xe"); - @ClassRule + @Container public static OracleContainer oracle = new OracleContainer(ORACLE_IMAGE); @Autowired @@ -73,15 +74,15 @@ public class OracleJobRepositoryIntegrationTests { @Autowired private Job job; - @Before - public void setUp() { + @BeforeEach + void setUp() { ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); databasePopulator.addScript(new ClassPathResource("/org/springframework/batch/core/schema-oracle.sql")); databasePopulator.execute(this.dataSource); } @Test - public void testJobExecution() throws Exception { + void testJobExecution() throws Exception { // given JobParameters jobParameters = new JobParametersBuilder().toJobParameters(); @@ -89,8 +90,8 @@ public void testJobExecution() throws Exception { JobExecution jobExecution = this.jobLauncher.run(this.job, jobParameters); // then - Assert.assertNotNull(jobExecution); - Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); + assertNotNull(jobExecution); + assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); } @Configuration diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/PostgreSQLJobRepositoryIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/PostgreSQLJobRepositoryIntegrationTests.java index 721a663fdd..7ba2d27bc4 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/PostgreSQLJobRepositoryIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/PostgreSQLJobRepositoryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2021 the original author or authors. + * Copyright 2020-2022 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. @@ -17,13 +17,12 @@ import javax.sql.DataSource; -import org.junit.Assert; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.postgresql.ds.PGSimpleDataSource; import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.utility.DockerImageName; import org.springframework.batch.core.ExitStatus; @@ -41,20 +40,22 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Mahmoud Ben Hassine */ -@RunWith(SpringRunner.class) -@ContextConfiguration -public class PostgreSQLJobRepositoryIntegrationTests { +@Testcontainers +@SpringJUnitConfig +class PostgreSQLJobRepositoryIntegrationTests { // TODO find the best way to externalize and manage image versions private static final DockerImageName POSTGRESQL_IMAGE = DockerImageName.parse("postgres:13.3"); - @ClassRule + @Container public static PostgreSQLContainer postgres = new PostgreSQLContainer<>(POSTGRESQL_IMAGE); @Autowired @@ -66,15 +67,15 @@ public class PostgreSQLJobRepositoryIntegrationTests { @Autowired private Job job; - @Before - public void setUp() { + @BeforeEach + void setUp() { ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); databasePopulator.addScript(new ClassPathResource("/org/springframework/batch/core/schema-postgresql.sql")); databasePopulator.execute(this.dataSource); } @Test - public void testJobExecution() throws Exception { + void testJobExecution() throws Exception { // given JobParameters jobParameters = new JobParametersBuilder().toJobParameters(); @@ -82,8 +83,8 @@ public void testJobExecution() throws Exception { JobExecution jobExecution = this.jobLauncher.run(this.job, jobParameters); // then - Assert.assertNotNull(jobExecution); - Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); + assertNotNull(jobExecution); + assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); } @Configuration diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/SQLServerJobRepositoryIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/SQLServerJobRepositoryIntegrationTests.java index c83bc8b9a2..1c9d8b3122 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/SQLServerJobRepositoryIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/SQLServerJobRepositoryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2021 the original author or authors. + * Copyright 2020-2022 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. @@ -18,12 +18,11 @@ import javax.sql.DataSource; import com.microsoft.sqlserver.jdbc.SQLServerDataSource; -import org.junit.Assert; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.testcontainers.containers.MSSQLServerContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.utility.DockerImageName; import org.springframework.batch.core.ExitStatus; @@ -41,21 +40,23 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Mahmoud Ben Hassine */ -@RunWith(SpringRunner.class) -@ContextConfiguration -public class SQLServerJobRepositoryIntegrationTests { +@Testcontainers +@SpringJUnitConfig +class SQLServerJobRepositoryIntegrationTests { // TODO find the best way to externalize and manage image versions private static final DockerImageName SQLSERVER_IMAGE = DockerImageName .parse("mcr.microsoft.com/mssql/server:2019-CU11-ubuntu-20.04"); - @ClassRule + @Container public static MSSQLServerContainer sqlserver = new MSSQLServerContainer<>(SQLSERVER_IMAGE).acceptLicense(); @Autowired @@ -67,15 +68,15 @@ public class SQLServerJobRepositoryIntegrationTests { @Autowired private Job job; - @Before - public void setUp() { + @BeforeEach + void setUp() { ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); databasePopulator.addScript(new ClassPathResource("/org/springframework/batch/core/schema-sqlserver.sql")); databasePopulator.execute(this.dataSource); } @Test - public void testJobExecution() throws Exception { + void testJobExecution() throws Exception { // given JobParameters jobParameters = new JobParametersBuilder().toJobParameters(); @@ -83,8 +84,8 @@ public void testJobExecution() throws Exception { JobExecution jobExecution = this.jobLauncher.run(this.job, jobParameters); // then - Assert.assertNotNull(jobExecution); - Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); + assertNotNull(jobExecution); + assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); } @Configuration diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/SQLiteJobRepositoryIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/SQLiteJobRepositoryIntegrationTests.java index 081a458092..2aa5a4d6c5 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/SQLiteJobRepositoryIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/SQLiteJobRepositoryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2021 the original author or authors. + * Copyright 2020-2022 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. @@ -17,9 +17,7 @@ import javax.sql.DataSource; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.sqlite.SQLiteDataSource; import org.springframework.batch.core.ExitStatus; @@ -37,15 +35,16 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Mahmoud Ben Hassine */ -@RunWith(SpringRunner.class) -@ContextConfiguration -public class SQLiteJobRepositoryIntegrationTests { +@SpringJUnitConfig +class SQLiteJobRepositoryIntegrationTests { @Autowired private JobLauncher jobLauncher; @@ -54,7 +53,7 @@ public class SQLiteJobRepositoryIntegrationTests { private Job job; @Test - public void testJobExecution() throws Exception { + void testJobExecution() throws Exception { // given JobParameters jobParameters = new JobParametersBuilder().toJobParameters(); @@ -62,8 +61,8 @@ public void testJobExecution() throws Exception { JobExecution jobExecution = this.jobLauncher.run(this.job, jobParameters); // then - Assert.assertNotNull(jobExecution); - Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); + assertNotNull(jobExecution); + assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); } @Configuration diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/SybaseJobRepositoryIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/SybaseJobRepositoryIntegrationTests.java index 2cb31ab812..a0879a7f69 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/SybaseJobRepositoryIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/repository/SybaseJobRepositoryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2021 the original author or authors. + * Copyright 2020-2022 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. @@ -18,11 +18,9 @@ import javax.sql.DataSource; import net.sourceforge.jtds.jdbcx.JtdsDataSource; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.Job; @@ -39,8 +37,10 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * The Sybase official jdbc driver is not freely available. This test uses the @@ -53,10 +53,9 @@ * * @author Mahmoud Ben Hassine */ -@RunWith(SpringRunner.class) -@ContextConfiguration -@Ignore("No support for Sybase in testcontainers") -public class SybaseJobRepositoryIntegrationTests { +@SpringJUnitConfig +@Disabled("No support for Sybase in testcontainers") +class SybaseJobRepositoryIntegrationTests { @Autowired private DataSource dataSource; @@ -67,15 +66,15 @@ public class SybaseJobRepositoryIntegrationTests { @Autowired private Job job; - @Before - public void setUp() { + @BeforeEach + void setUp() { ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); databasePopulator.addScript(new ClassPathResource("/org/springframework/batch/core/schema-sybase.sql")); databasePopulator.execute(this.dataSource); } @Test - public void testJobExecution() throws Exception { + void testJobExecution() throws Exception { // given JobParameters jobParameters = new JobParametersBuilder().toJobParameters(); @@ -83,8 +82,8 @@ public void testJobExecution() throws Exception { JobExecution jobExecution = this.jobLauncher.run(this.job, jobParameters); // then - Assert.assertNotNull(jobExecution); - Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); + assertNotNull(jobExecution); + assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); } @Configuration diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/step/FaultTolerantStepFactoryBeanIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/step/FaultTolerantStepFactoryBeanIntegrationTests.java index f42adbf843..946f578b01 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/step/FaultTolerantStepFactoryBeanIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/step/FaultTolerantStepFactoryBeanIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2021 the original author or authors. + * Copyright 2010-2022 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. @@ -15,7 +15,7 @@ */ package org.springframework.batch.core.test.step; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.sql.ResultSet; import java.sql.SQLException; @@ -29,9 +29,8 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.JobExecution; @@ -50,8 +49,7 @@ import org.springframework.jdbc.core.RowMapper; import org.springframework.lang.Nullable; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.jdbc.JdbcTestUtils; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.util.Assert; @@ -59,9 +57,8 @@ /** * Tests for {@link FaultTolerantStepFactoryBean}. */ -@ContextConfiguration(locations = "/simple-job-launcher-context.xml") -@RunWith(SpringJUnit4ClassRunner.class) -public class FaultTolerantStepFactoryBeanIntegrationTests { +@SpringJUnitConfig(locations = "/simple-job-launcher-context.xml") +class FaultTolerantStepFactoryBeanIntegrationTests { private static final int MAX_COUNT = 1000; @@ -86,8 +83,8 @@ public class FaultTolerantStepFactoryBeanIntegrationTests { @Autowired private PlatformTransactionManager transactionManager; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { writer = new SkipWriterStub(dataSource); processor = new SkipProcessorStub(dataSource); @@ -110,7 +107,7 @@ public void setUp() throws Exception { } @Test - public void testUpdatesNoRollback() throws Exception { + void testUpdatesNoRollback() throws Exception { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); @@ -125,7 +122,7 @@ public void testUpdatesNoRollback() throws Exception { } @Test - public void testMultithreadedSunnyDay() throws Throwable { + void testMultithreadedSunnyDay() throws Throwable { jobExecution = repository.createJobExecution("vanillaJob", new JobParameters()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/step/FaultTolerantStepFactoryBeanRollbackIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/step/FaultTolerantStepFactoryBeanRollbackIntegrationTests.java index f98b1b642a..ddffda568f 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/step/FaultTolerantStepFactoryBeanRollbackIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/step/FaultTolerantStepFactoryBeanRollbackIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2021 the original author or authors. + * Copyright 2010-2022 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. @@ -29,9 +29,8 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.JobExecution; @@ -50,20 +49,18 @@ import org.springframework.jdbc.core.RowMapper; import org.springframework.lang.Nullable; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.jdbc.JdbcTestUtils; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.util.Assert; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests for {@link FaultTolerantStepFactoryBean}. */ -@ContextConfiguration(locations = "/simple-job-launcher-context.xml") -@RunWith(SpringJUnit4ClassRunner.class) -public class FaultTolerantStepFactoryBeanRollbackIntegrationTests { +@SpringJUnitConfig(locations = "/simple-job-launcher-context.xml") +class FaultTolerantStepFactoryBeanRollbackIntegrationTests { private static final int MAX_COUNT = 1000; @@ -88,8 +85,8 @@ public class FaultTolerantStepFactoryBeanRollbackIntegrationTests { @Autowired private PlatformTransactionManager transactionManager; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { writer = new SkipWriterStub(dataSource); processor = new SkipProcessorStub(dataSource); @@ -107,7 +104,7 @@ public void setUp() throws Exception { } @Test - public void testUpdatesNoRollback() throws Exception { + void testUpdatesNoRollback() throws Exception { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); @@ -122,7 +119,7 @@ public void testUpdatesNoRollback() throws Exception { } @Test - public void testMultithreadedSkipInWriter() throws Throwable { + void testMultithreadedSkipInWriter() throws Throwable { ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); taskExecutor.setCorePoolSize(3); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/step/FaultTolerantStepIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/step/FaultTolerantStepIntegrationTests.java index c540b700a7..08513018fb 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/step/FaultTolerantStepIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/step/FaultTolerantStepIntegrationTests.java @@ -19,9 +19,9 @@ import java.util.Arrays; import java.util.List; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; @@ -41,19 +41,17 @@ import org.springframework.batch.item.support.ListItemReader; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.lang.Nullable; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.transaction.PlatformTransactionManager; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests for fault tolerant * {@link org.springframework.batch.core.step.item.ChunkOrientedTasklet}. */ -@ContextConfiguration(locations = "/simple-job-launcher-context.xml") -@RunWith(SpringJUnit4ClassRunner.class) -public class FaultTolerantStepIntegrationTests { +@SpringJUnitConfig(locations = "/simple-job-launcher-context.xml") +class FaultTolerantStepIntegrationTests { private static final int TOTAL_ITEMS = 30; @@ -69,8 +67,8 @@ public class FaultTolerantStepIntegrationTests { private FaultTolerantStepBuilder stepBuilder; - @Before - public void setUp() { + @BeforeEach + void setUp() { ItemReader itemReader = new ListItemReader<>(createItems()); ItemWriter itemWriter = chunk -> { if (chunk.contains(1)) { @@ -84,7 +82,7 @@ public void setUp() { } @Test - public void testFilterCountWithTransactionalProcessorWhenSkipInWrite() throws Exception { + void testFilterCountWithTransactionalProcessorWhenSkipInWrite() throws Exception { // Given Step step = stepBuilder.skipPolicy(skipPolicy).build(); @@ -99,7 +97,7 @@ public void testFilterCountWithTransactionalProcessorWhenSkipInWrite() throws Ex } @Test - public void testFilterCountWithNonTransactionalProcessorWhenSkipInWrite() throws Exception { + void testFilterCountWithNonTransactionalProcessorWhenSkipInWrite() throws Exception { // Given Step step = stepBuilder.skipPolicy(skipPolicy).processorNonTransactional().build(); @@ -114,7 +112,7 @@ public void testFilterCountWithNonTransactionalProcessorWhenSkipInWrite() throws } @Test - public void testFilterCountOnRetryWithTransactionalProcessorWhenSkipInWrite() throws Exception { + void testFilterCountOnRetryWithTransactionalProcessorWhenSkipInWrite() throws Exception { // Given Step step = stepBuilder.retry(IllegalArgumentException.class).retryLimit(2).skipPolicy(skipPolicy).build(); @@ -130,7 +128,7 @@ public void testFilterCountOnRetryWithTransactionalProcessorWhenSkipInWrite() th } @Test - public void testFilterCountOnRetryWithNonTransactionalProcessorWhenSkipInWrite() throws Exception { + void testFilterCountOnRetryWithNonTransactionalProcessorWhenSkipInWrite() throws Exception { // Given Step step = stepBuilder.retry(IllegalArgumentException.class).retryLimit(2).skipPolicy(skipPolicy) .processorNonTransactional().build(); @@ -146,8 +144,9 @@ public void testFilterCountOnRetryWithNonTransactionalProcessorWhenSkipInWrite() assertEquals(1, stepExecution.getWriteSkipCount()); } - @Test(timeout = 3000) - public void testExceptionInProcessDuringChunkScan() throws Exception { + @Test + @Timeout(3) + void testExceptionInProcessDuringChunkScan() throws Exception { // Given ListItemReader itemReader = new ListItemReader<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7)); @@ -193,8 +192,9 @@ public void write(List items) throws Exception { assertEquals(1, stepExecution.getProcessSkipCount()); } - @Test(timeout = 3000) - public void testExceptionInProcessAndWriteDuringChunkScan() throws Exception { + @Test + @Timeout(3000) + void testExceptionInProcessAndWriteDuringChunkScan() throws Exception { // Given ListItemReader itemReader = new ListItemReader<>(Arrays.asList(1, 2, 3)); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/step/StepExecutionSerializationUtilsTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/step/StepExecutionSerializationUtilsTests.java index 3108eab72b..b288afb4bb 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/step/StepExecutionSerializationUtilsTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/step/StepExecutionSerializationUtilsTests.java @@ -15,7 +15,7 @@ */ package org.springframework.batch.core.test.step; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.concurrent.CompletionService; import java.util.concurrent.Executor; @@ -24,7 +24,7 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInstance; import org.springframework.batch.core.JobParameters; @@ -36,10 +36,10 @@ * @author Michael Minella * @author Mahmoud Ben Hassine */ -public class StepExecutionSerializationUtilsTests { +class StepExecutionSerializationUtilsTests { @Test - public void testCycle() { + void testCycle() { StepExecution stepExecution = new StepExecution("step", new JobExecution(new JobInstance(123L, "job"), 321L, new JobParameters()), 11L); stepExecution.getExecutionContext().put("foo.bar.spam", 123); @@ -48,7 +48,7 @@ public void testCycle() { } @Test - public void testMultipleCycles() throws Throwable { + void testMultipleCycles() throws Throwable { int count = 0; int repeats = 100; diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/timeout/TimeoutJobIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/timeout/TimeoutJobIntegrationTests.java index 64721f6cae..50e9464632 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/timeout/TimeoutJobIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/timeout/TimeoutJobIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014 the original author or authors. + * Copyright 2014-2022 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. @@ -17,12 +17,11 @@ import javax.sql.DataSource; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; @@ -31,11 +30,9 @@ import org.springframework.batch.core.test.AbstractIntegrationTests; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/META-INF/batch/timeoutJob.xml" }) +@SpringJUnitConfig(locations = { "/simple-job-launcher-context.xml", "/META-INF/batch/timeoutJob.xml" }) public class TimeoutJobIntegrationTests extends AbstractIntegrationTests { /** Logger */ @@ -59,14 +56,14 @@ public void setDataSource(DataSource dataSource) { } @Test - public void testChunkTimeoutShouldFail() throws Exception { + void testChunkTimeoutShouldFail() throws Exception { JobExecution execution = jobLauncher.run(chunkTimeoutJob, new JobParametersBuilder().addLong("id", System.currentTimeMillis()).toJobParameters()); assertEquals(BatchStatus.FAILED, execution.getStatus()); } @Test - public void testTaskletTimeoutShouldFail() throws Exception { + void testTaskletTimeoutShouldFail() throws Exception { JobExecution execution = jobLauncher.run(taskletTimeoutJob, new JobParametersBuilder().addLong("id", System.currentTimeMillis()).toJobParameters()); assertEquals(BatchStatus.FAILED, execution.getStatus()); diff --git a/spring-batch-core/src/test/resources/org/springframework/batch/core/schema-hsqldb-extended.sql b/spring-batch-core/src/test/resources/org/springframework/batch/core/schema-hsqldb-extended.sql index e2fe276e46..946ef887b3 100644 --- a/spring-batch-core/src/test/resources/org/springframework/batch/core/schema-hsqldb-extended.sql +++ b/spring-batch-core/src/test/resources/org/springframework/batch/core/schema-hsqldb-extended.sql @@ -20,8 +20,8 @@ CREATE TABLE BATCH_JOB_EXECUTION ( START_TIME TIMESTAMP DEFAULT NULL , END_TIME TIMESTAMP DEFAULT NULL , STATUS VARCHAR(10) , - EXIT_CODE VARCHAR(10000) , - EXIT_MESSAGE VARCHAR(10000) , + EXIT_CODE VARCHAR(20000) , + EXIT_MESSAGE VARCHAR(20000) , LAST_UPDATED TIMESTAMP, constraint JOB_INST_EXEC_FK foreign key (JOB_INSTANCE_ID) references BATCH_JOB_INSTANCE(JOB_INSTANCE_ID) @@ -57,8 +57,8 @@ CREATE TABLE BATCH_STEP_EXECUTION ( WRITE_SKIP_COUNT BIGINT , PROCESS_SKIP_COUNT BIGINT , ROLLBACK_COUNT BIGINT , - EXIT_CODE VARCHAR(10000) , - EXIT_MESSAGE VARCHAR(10000) , + EXIT_CODE VARCHAR(20000) , + EXIT_MESSAGE VARCHAR(20000) , LAST_UPDATED TIMESTAMP, constraint JOB_EXEC_STEP_FK foreign key (JOB_EXECUTION_ID) references BATCH_JOB_EXECUTION(JOB_EXECUTION_ID) @@ -66,7 +66,7 @@ CREATE TABLE BATCH_STEP_EXECUTION ( CREATE TABLE BATCH_STEP_EXECUTION_CONTEXT ( STEP_EXECUTION_ID BIGINT NOT NULL PRIMARY KEY, - SHORT_CONTEXT VARCHAR(10000) NOT NULL, + SHORT_CONTEXT VARCHAR(20000) NOT NULL, SERIALIZED_CONTEXT LONGVARCHAR , constraint STEP_EXEC_CTX_FK foreign key (STEP_EXECUTION_ID) references BATCH_STEP_EXECUTION(STEP_EXECUTION_ID) @@ -74,7 +74,7 @@ CREATE TABLE BATCH_STEP_EXECUTION_CONTEXT ( CREATE TABLE BATCH_JOB_EXECUTION_CONTEXT ( JOB_EXECUTION_ID BIGINT NOT NULL PRIMARY KEY, - SHORT_CONTEXT VARCHAR(10000) NOT NULL, + SHORT_CONTEXT VARCHAR(20000) NOT NULL, SERIALIZED_CONTEXT LONGVARCHAR , constraint JOB_EXEC_CTX_FK foreign key (JOB_EXECUTION_ID) references BATCH_JOB_EXECUTION(JOB_EXECUTION_ID)