diff --git a/pom.xml b/pom.xml index 2188899..bf2cdb8 100644 --- a/pom.xml +++ b/pom.xml @@ -32,6 +32,9 @@ true UTF-8 UTF-8 + 5.8.2 + 3.21.0 + 2.17.2 6.0.0-SNAPSHOT @@ -123,6 +126,13 @@ pom import + + org.junit + junit-bom + ${junit-jupiter.version} + pom + import + @@ -135,26 +145,45 @@ org.springframework spring-core - true - junit - junit - 4.13.1 + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.jupiter + junit-jupiter-params + test + + + org.junit.platform + junit-platform-launcher + test + + + org.assertj + assertj-core + ${assertj.version} test org.apache.logging.log4j log4j-core - 2.17.1 + ${log4j.version} test org.apache.logging.log4j log4j-jcl - 2.17.1 + ${log4j.version} test diff --git a/src/test/java/org/springframework/classify/BackToBackPatternClassifierTests.java b/src/test/java/org/springframework/classify/BackToBackPatternClassifierTests.java index 9e34ae9..58e1bf9 100644 --- a/src/test/java/org/springframework/classify/BackToBackPatternClassifierTests.java +++ b/src/test/java/org/springframework/classify/BackToBackPatternClassifierTests.java @@ -15,16 +15,18 @@ */ package org.springframework.classify; -import static org.junit.Assert.assertEquals; - import java.util.Collections; 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.classify.annotation.Classifier; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + /** * @author Dave Syer * @@ -35,16 +37,16 @@ public class BackToBackPatternClassifierTests { private Map map; - @Before + @BeforeEach public void createMap() { map = new HashMap<>(); map.put("foo", "bar"); map.put("*", "spam"); } - @Test(expected = NullPointerException.class) + @Test public void testNoClassifiers() { - classifier.classify("foo"); + assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> classifier.classify("foo")); } @Test @@ -52,7 +54,7 @@ public class BackToBackPatternClassifierTests { classifier = new BackToBackPatternClassifier<>( new PatternMatchingClassifier<>(Collections.singletonMap("oof", "bucket")), new PatternMatchingClassifier<>(map)); - assertEquals("spam", classifier.classify("oof")); + assertThat(classifier.classify("oof")).isEqualTo("spam"); } @Test @@ -64,7 +66,7 @@ public class BackToBackPatternClassifierTests { } }); classifier.setMatcherMap(map); - assertEquals("spam", classifier.classify("oof")); + assertThat(classifier.classify("oof")).isEqualTo("spam"); } @Test @@ -72,7 +74,7 @@ public class BackToBackPatternClassifierTests { classifier = new BackToBackPatternClassifier<>(); classifier.setRouterDelegate(new RouterDelegate()); classifier.setMatcherMap(map); - assertEquals("spam", classifier.classify("oof")); + assertThat(classifier.classify("oof")).isEqualTo("spam"); } @SuppressWarnings("serial") diff --git a/src/test/java/org/springframework/classify/BinaryExceptionClassifierBuilderTests.java b/src/test/java/org/springframework/classify/BinaryExceptionClassifierBuilderTests.java index 4263497..a263829 100644 --- a/src/test/java/org/springframework/classify/BinaryExceptionClassifierBuilderTests.java +++ b/src/test/java/org/springframework/classify/BinaryExceptionClassifierBuilderTests.java @@ -21,10 +21,13 @@ import java.io.IOException; import java.io.StreamCorruptedException; import java.util.concurrent.TimeoutException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + import org.springframework.retry.support.RetryTemplate; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + /** * @author Aleksandr Shamukov */ @@ -37,11 +40,11 @@ public class BinaryExceptionClassifierBuilderTests { BinaryExceptionClassifier classifier = BinaryExceptionClassifier.builder().retryOn(IOException.class) .retryOn(TimeoutException.class).build(); - Assert.assertTrue(classifier.classify(new IOException())); + assertThat(classifier.classify(new IOException())).isTrue(); // should not retry due to traverseCauses=fasle - Assert.assertFalse(classifier.classify(new RuntimeException(new IOException()))); - Assert.assertTrue(classifier.classify(new StreamCorruptedException())); - Assert.assertFalse(classifier.classify(new OutOfMemoryError())); + assertThat(classifier.classify(new RuntimeException(new IOException()))).isFalse(); + assertThat(classifier.classify(new StreamCorruptedException())).isTrue(); + assertThat(classifier.classify(new OutOfMemoryError())).isFalse(); } @Test @@ -49,13 +52,13 @@ public class BinaryExceptionClassifierBuilderTests { BinaryExceptionClassifier classifier = BinaryExceptionClassifier.builder().retryOn(IOException.class) .retryOn(TimeoutException.class).traversingCauses().build(); - Assert.assertTrue(classifier.classify(new IOException())); + assertThat(classifier.classify(new IOException())).isTrue(); // should retry due to traverseCauses=true - Assert.assertTrue(classifier.classify(new RuntimeException(new IOException()))); - Assert.assertTrue(classifier.classify(new StreamCorruptedException())); + assertThat(classifier.classify(new RuntimeException(new IOException()))).isTrue(); + assertThat(classifier.classify(new StreamCorruptedException())).isTrue(); // should retry due to FileNotFoundException is a subclass of TimeoutException - Assert.assertTrue(classifier.classify(new FileNotFoundException())); - Assert.assertFalse(classifier.classify(new RuntimeException())); + assertThat(classifier.classify(new FileNotFoundException())).isTrue(); + assertThat(classifier.classify(new RuntimeException())).isFalse(); } @Test @@ -64,16 +67,17 @@ public class BinaryExceptionClassifierBuilderTests { .notRetryOn(InterruptedException.class).traversingCauses().build(); // should not retry due to OutOfMemoryError is a subclass of Error - Assert.assertFalse(classifier.classify(new OutOfMemoryError())); - Assert.assertFalse(classifier.classify(new InterruptedException())); - Assert.assertTrue(classifier.classify(new Throwable())); + assertThat(classifier.classify(new OutOfMemoryError())).isFalse(); + assertThat(classifier.classify(new InterruptedException())).isFalse(); + assertThat(classifier.classify(new Throwable())).isTrue(); // should retry due to traverseCauses=true - Assert.assertFalse(classifier.classify(new RuntimeException(new InterruptedException()))); + assertThat(classifier.classify(new RuntimeException(new InterruptedException()))).isFalse(); } - @Test(expected = IllegalArgumentException.class) + @Test public void testFailOnNotationMix() { - BinaryExceptionClassifier.builder().retryOn(IOException.class).notRetryOn(OutOfMemoryError.class); + assertThatIllegalArgumentException().isThrownBy(() -> BinaryExceptionClassifier.builder() + .retryOn(IOException.class).notRetryOn(OutOfMemoryError.class)); } } diff --git a/src/test/java/org/springframework/classify/BinaryExceptionClassifierTests.java b/src/test/java/org/springframework/classify/BinaryExceptionClassifierTests.java index 799370e..305aa37 100644 --- a/src/test/java/org/springframework/classify/BinaryExceptionClassifierTests.java +++ b/src/test/java/org/springframework/classify/BinaryExceptionClassifierTests.java @@ -16,48 +16,47 @@ package org.springframework.classify; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import java.util.Collection; 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.beans.DirectFieldAccessor; +import static org.assertj.core.api.Assertions.assertThat; + public class BinaryExceptionClassifierTests { BinaryExceptionClassifier classifier = new BinaryExceptionClassifier(false); @Test public void testClassifyNullIsDefault() { - assertFalse(classifier.classify(null)); + assertThat(classifier.classify(null)).isFalse(); } @Test public void testFalseIsDefault() { - assertFalse(classifier.getDefault()); + assertThat(classifier.getDefault()).isFalse(); } @Test public void testDefaultProvided() { classifier = new BinaryExceptionClassifier(true); - assertTrue(classifier.getDefault()); + assertThat(classifier.getDefault()).isTrue(); } @Test public void testClassifyRandomException() { - assertFalse(classifier.classify(new IllegalStateException("foo"))); + assertThat(classifier.classify(new IllegalStateException("foo"))).isFalse(); } @Test public void testClassifyExactMatch() { Collection> set = Collections .>singleton(IllegalStateException.class); - assertTrue(new BinaryExceptionClassifier(set).classify(new IllegalStateException("Foo"))); + assertThat(new BinaryExceptionClassifier(set).classify(new IllegalStateException("Foo"))).isTrue(); } @Test @@ -66,7 +65,7 @@ public class BinaryExceptionClassifierTests { .>singleton(IllegalStateException.class); BinaryExceptionClassifier binaryExceptionClassifier = new BinaryExceptionClassifier(set); binaryExceptionClassifier.setTraverseCauses(true); - assertTrue(binaryExceptionClassifier.classify(new RuntimeException(new IllegalStateException("Foo")))); + assertThat(binaryExceptionClassifier.classify(new RuntimeException(new IllegalStateException("Foo")))).isTrue(); } @Test @@ -75,7 +74,7 @@ public class BinaryExceptionClassifierTests { .>singleton(IllegalStateException.class); BinaryExceptionClassifier binaryExceptionClassifier = new BinaryExceptionClassifier(set); binaryExceptionClassifier.setTraverseCauses(true); - assertTrue(binaryExceptionClassifier.classify(new RuntimeException(new FooException("Foo")))); + assertThat(binaryExceptionClassifier.classify(new RuntimeException(new FooException("Foo")))).isTrue(); } @Test @@ -85,24 +84,25 @@ public class BinaryExceptionClassifierTests { map.put(BarException.class, false); BinaryExceptionClassifier binaryExceptionClassifier = new BinaryExceptionClassifier(map, true); binaryExceptionClassifier.setTraverseCauses(true); - assertTrue( - binaryExceptionClassifier.classify(new RuntimeException(new FooException("Foo", new BarException())))); - assertTrue(((Map) new DirectFieldAccessor(binaryExceptionClassifier).getPropertyValue("classified")) - .containsKey(FooException.class)); + assertThat( + binaryExceptionClassifier.classify(new RuntimeException(new FooException("Foo", new BarException())))) + .isTrue(); + assertThat(((Map) new DirectFieldAccessor(binaryExceptionClassifier).getPropertyValue("classified")) + .containsKey(FooException.class)).isTrue(); } @Test public void testTypesProvidedInConstructor() { classifier = new BinaryExceptionClassifier( Collections.>singleton(IllegalStateException.class)); - assertTrue(classifier.classify(new IllegalStateException("Foo"))); + assertThat(classifier.classify(new IllegalStateException("Foo"))).isTrue(); } @Test public void testTypesProvidedInConstructorWithNonDefault() { classifier = new BinaryExceptionClassifier( Collections.>singleton(IllegalStateException.class), false); - assertFalse(classifier.classify(new IllegalStateException("Foo"))); + assertThat(classifier.classify(new IllegalStateException("Foo"))).isFalse(); } @Test @@ -110,7 +110,8 @@ public class BinaryExceptionClassifierTests { classifier = new BinaryExceptionClassifier( Collections.>singleton(IllegalStateException.class), false); classifier.setTraverseCauses(true); - assertFalse(classifier.classify(new RuntimeException(new RuntimeException(new IllegalStateException("Foo"))))); + assertThat(classifier.classify(new RuntimeException(new RuntimeException(new IllegalStateException("Foo"))))) + .isFalse(); } @SuppressWarnings("serial") diff --git a/src/test/java/org/springframework/classify/ClassifierAdapterTests.java b/src/test/java/org/springframework/classify/ClassifierAdapterTests.java index d9f2306..87e9535 100644 --- a/src/test/java/org/springframework/classify/ClassifierAdapterTests.java +++ b/src/test/java/org/springframework/classify/ClassifierAdapterTests.java @@ -15,14 +15,17 @@ */ package org.springframework.classify; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.classify.annotation.Classifier; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * @author Dave Syer + * @author Gary Russell * */ public class ClassifierAdapterTests { @@ -42,12 +45,12 @@ public class ClassifierAdapterTests { throw new UnsupportedOperationException("Not allowed"); } }); - assertEquals(23, adapter.classify("23").intValue()); + assertThat(adapter.classify("23").intValue()).isEqualTo(23); } - @Test(expected = IllegalStateException.class) + @Test public void testClassifierAdapterObjectWithNoAnnotation() { - adapter = new ClassifierAdapter<>(new Object() { + assertThatIllegalStateException().isThrownBy(() -> new ClassifierAdapter<>(new Object() { @SuppressWarnings("unused") public Integer getValue(String key) { return Integer.parseInt(key); @@ -57,8 +60,7 @@ public class ClassifierAdapterTests { public Integer getAnother(String key) { throw new UnsupportedOperationException("Not allowed"); } - }); - assertEquals(23, adapter.classify("23").intValue()); + })); } @Test @@ -78,14 +80,14 @@ public class ClassifierAdapterTests { return "foo"; } }); - assertEquals(23, adapter.classify("23").intValue()); + assertThat(adapter.classify("23").intValue()).isEqualTo(23); } @SuppressWarnings({ "serial" }) @Test public void testClassifierAdapterClassifier() { adapter = new ClassifierAdapter<>(Integer::valueOf); - assertEquals(23, adapter.classify("23").intValue()); + assertThat(adapter.classify("23").intValue()).isEqualTo(23); } @Test @@ -96,10 +98,10 @@ public class ClassifierAdapterTests { return Integer.parseInt(key); } }); - assertEquals(23, adapter.classify("23").intValue()); + assertThat(adapter.classify("23").intValue()).isEqualTo(23); } - @Test(expected = IllegalArgumentException.class) + @Test public void testClassifyWithWrongType() { adapter.setDelegate(new Object() { @Classifier @@ -107,14 +109,13 @@ public class ClassifierAdapterTests { return key.toString(); } }); - assertEquals(23, adapter.classify("23").intValue()); + assertThatIllegalArgumentException().isThrownBy(() -> adapter.classify("23")); } - @SuppressWarnings("serial") @Test public void testClassifyWithClassifier() { adapter.setDelegate(Integer::valueOf); - assertEquals(23, adapter.classify("23").intValue()); + assertThat(adapter.classify("23").intValue()).isEqualTo(23); } } diff --git a/src/test/java/org/springframework/classify/ClassifierSupportTests.java b/src/test/java/org/springframework/classify/ClassifierSupportTests.java index 9a5fbff..e500d0c 100644 --- a/src/test/java/org/springframework/classify/ClassifierSupportTests.java +++ b/src/test/java/org/springframework/classify/ClassifierSupportTests.java @@ -16,22 +16,22 @@ package org.springframework.classify; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; public class ClassifierSupportTests { @Test public void testClassifyNullIsDefault() { ClassifierSupport classifier = new ClassifierSupport<>("foo"); - assertEquals(classifier.classify(null), "foo"); + assertThat(classifier.classify(null)).isEqualTo("foo"); } @Test public void testClassifyRandomException() { ClassifierSupport classifier = new ClassifierSupport<>("foo"); - assertEquals(classifier.classify(new IllegalStateException("Foo")), classifier.classify(null)); + assertThat(classifier.classify(new IllegalStateException("Foo"))).isEqualTo(classifier.classify(null)); } } diff --git a/src/test/java/org/springframework/classify/PatternMatchingClassifierTests.java b/src/test/java/org/springframework/classify/PatternMatchingClassifierTests.java index 83b44e0..b3e7fde 100644 --- a/src/test/java/org/springframework/classify/PatternMatchingClassifierTests.java +++ b/src/test/java/org/springframework/classify/PatternMatchingClassifierTests.java @@ -15,14 +15,13 @@ */ package org.springframework.classify; -import static org.junit.Assert.*; - import java.util.HashMap; import java.util.Map; -import org.junit.Before; -import org.junit.Test; -import org.springframework.classify.PatternMatchingClassifier; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -34,7 +33,7 @@ public class PatternMatchingClassifierTests { private Map map; - @Before + @BeforeEach public void createMap() { map = new HashMap<>(); map.put("foo", "bar"); @@ -44,15 +43,15 @@ public class PatternMatchingClassifierTests { @Test public void testSetPatternMap() { classifier.setPatternMap(map); - assertEquals("bar", classifier.classify("foo")); - assertEquals("spam", classifier.classify("bucket")); + assertThat(classifier.classify("foo")).isEqualTo("bar"); + assertThat(classifier.classify("bucket")).isEqualTo("spam"); } @Test public void testCreateFromMap() { classifier = new PatternMatchingClassifier<>(map); - assertEquals("bar", classifier.classify("foo")); - assertEquals("spam", classifier.classify("bucket")); + assertThat(classifier.classify("foo")).isEqualTo("bar"); + assertThat(classifier.classify("bucket")).isEqualTo("spam"); } -} \ No newline at end of file +} diff --git a/src/test/java/org/springframework/classify/SubclassClassifierTests.java b/src/test/java/org/springframework/classify/SubclassClassifierTests.java index ca1da63..0f97bdc 100644 --- a/src/test/java/org/springframework/classify/SubclassClassifierTests.java +++ b/src/test/java/org/springframework/classify/SubclassClassifierTests.java @@ -19,9 +19,9 @@ package org.springframework.classify; import java.util.Collections; import java.util.function.Supplier; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class SubclassClassifierTests { @@ -29,14 +29,14 @@ public class SubclassClassifierTests { public void testClassifyInterface() { SubclassClassifier classifier = new SubclassClassifier<>(); classifier.setTypeMap(Collections., String>singletonMap(Supplier.class, "foo")); - assertEquals("foo", classifier.classify(new Foo())); + assertThat(classifier.classify(new Foo())).isEqualTo("foo"); } @Test public void testClassifyInterfaceOfParent() { SubclassClassifier classifier = new SubclassClassifier<>(); classifier.setTypeMap(Collections., String>singletonMap(Supplier.class, "foo")); - assertEquals("foo", classifier.classify(new Bar())); + assertThat(classifier.classify(new Bar())).isEqualTo("foo"); } public class Bar extends Foo { diff --git a/src/test/java/org/springframework/classify/SubclassExceptionClassifierTests.java b/src/test/java/org/springframework/classify/SubclassExceptionClassifierTests.java index 4c3ae27..c7cd12d 100644 --- a/src/test/java/org/springframework/classify/SubclassExceptionClassifierTests.java +++ b/src/test/java/org/springframework/classify/SubclassExceptionClassifierTests.java @@ -23,10 +23,9 @@ import java.util.Collections; import java.util.HashMap; import java.util.NoSuchElementException; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; public class SubclassExceptionClassifierTests { @@ -34,44 +33,44 @@ public class SubclassExceptionClassifierTests { @Test public void testClassifyNullIsDefault() { - assertEquals(this.classifier.classify(null), this.classifier.getDefault()); + assertThat(this.classifier.getDefault()).isEqualTo(this.classifier.classify(null)); } @Test public void testClassifyNull() { - assertNull(this.classifier.classify(null)); + assertThat(this.classifier.classify(null)).isNull(); } @Test public void testClassifyNullNonDefault() { this.classifier = new SubclassClassifier<>("foo"); - assertEquals("foo", this.classifier.classify(null)); + assertThat(this.classifier.classify(null)).isEqualTo("foo"); } @Test public void testClassifyRandomException() { - assertNull(this.classifier.classify(new IllegalStateException("Foo"))); + assertThat(this.classifier.classify(new IllegalStateException("Foo"))).isNull(); } @Test public void testClassifyExactMatch() { this.classifier.setTypeMap( Collections., String>singletonMap(IllegalStateException.class, "foo")); - assertEquals("foo", this.classifier.classify(new IllegalStateException("Foo"))); + assertThat(this.classifier.classify(new IllegalStateException("Foo"))).isEqualTo("foo"); } @Test public void testClassifySubclassMatch() { this.classifier.setTypeMap( Collections., String>singletonMap(RuntimeException.class, "foo")); - assertEquals("foo", this.classifier.classify(new IllegalStateException("Foo"))); + assertThat(this.classifier.classify(new IllegalStateException("Foo"))).isEqualTo("foo"); } @Test public void testClassifySuperclassDoesNotMatch() { this.classifier.setTypeMap( Collections., String>singletonMap(IllegalStateException.class, "foo")); - assertEquals(this.classifier.getDefault(), this.classifier.classify(new RuntimeException("Foo"))); + assertThat(this.classifier.classify(new RuntimeException("Foo"))).isEqualTo(this.classifier.getDefault()); } @SuppressWarnings("serial") @@ -84,7 +83,7 @@ public class SubclassExceptionClassifierTests { put(RuntimeException.class, "spam"); } }); - assertEquals("spam", this.classifier.classify(new IllegalStateException("Foo"))); + assertThat(this.classifier.classify(new IllegalStateException("Foo"))).isEqualTo("spam"); } @SuppressWarnings("serial") @@ -102,7 +101,7 @@ public class SubclassExceptionClassifierTests { put(ConnectException.class, "2"); } }); - assertEquals("2", this.classifier.classify(new SubConnectException())); + assertThat(this.classifier.classify(new SubConnectException())).isEqualTo("2"); } public static class SubConnectException extends ConnectException { diff --git a/src/test/java/org/springframework/retry/AbstractExceptionTests.java b/src/test/java/org/springframework/retry/AbstractExceptionTests.java index f721d68..c97b27e 100644 --- a/src/test/java/org/springframework/retry/AbstractExceptionTests.java +++ b/src/test/java/org/springframework/retry/AbstractExceptionTests.java @@ -16,22 +16,22 @@ package org.springframework.retry; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; public abstract class AbstractExceptionTests { @Test public void testExceptionString() throws Exception { Exception exception = getException("foo"); - assertEquals("foo", exception.getMessage()); + assertThat(exception.getMessage()).isEqualTo("foo"); } @Test public void testExceptionStringThrowable() throws Exception { Exception exception = getException("foo", new IllegalStateException()); - assertEquals("foo", exception.getMessage().substring(0, 3)); + assertThat(exception.getMessage().substring(0, 3)).isEqualTo("foo"); } public abstract Exception getException(String msg); diff --git a/src/test/java/org/springframework/retry/AnyThrowTests.java b/src/test/java/org/springframework/retry/AnyThrowTests.java index af3e7b8..c0f364d 100644 --- a/src/test/java/org/springframework/retry/AnyThrowTests.java +++ b/src/test/java/org/springframework/retry/AnyThrowTests.java @@ -16,35 +16,32 @@ package org.springframework.retry; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Dave Syer + * @author Gary Russell * */ public class AnyThrowTests { - @Rule - public ExpectedException expected = ExpectedException.none(); - @Test public void testRuntimeException() { - expected.expect(RuntimeException.class); - AnyThrow.throwAny(new RuntimeException("planned")); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> AnyThrow.throwAny(new RuntimeException("planned"))); } @Test public void testUncheckedRuntimeException() { - expected.expect(RuntimeException.class); - AnyThrow.throwUnchecked(new RuntimeException("planned")); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> AnyThrow.throwUnchecked(new RuntimeException("planned"))); } @Test public void testCheckedException() { - expected.expect(Exception.class); - AnyThrow.throwAny(new Exception("planned")); + assertThatExceptionOfType(Exception.class).isThrownBy(() -> AnyThrow.throwAny(new Exception("planned"))); } private static class AnyThrow { diff --git a/src/test/java/org/springframework/retry/annotation/CircuitBreakerResetTimeoutTests.java b/src/test/java/org/springframework/retry/annotation/CircuitBreakerResetTimeoutTests.java index 37d8cba..50599b1 100644 --- a/src/test/java/org/springframework/retry/annotation/CircuitBreakerResetTimeoutTests.java +++ b/src/test/java/org/springframework/retry/annotation/CircuitBreakerResetTimeoutTests.java @@ -16,9 +16,8 @@ package org.springframework.retry.annotation; -import static org.junit.Assert.assertFalse; +import org.junit.jupiter.api.Test; -import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -26,6 +25,8 @@ import org.springframework.retry.RetryContext; import org.springframework.retry.policy.CircuitBreakerRetryPolicy; import org.springframework.retry.support.RetrySynchronizationManager; +import static org.assertj.core.api.Assertions.assertThat; + public class CircuitBreakerResetTimeoutTests { private final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( @@ -44,7 +45,7 @@ public class CircuitBreakerResetTimeoutTests { correctStep(timeOfLastFailure); correctStep(timeOfLastFailure); correctStep(timeOfLastFailure); - assertFalse((Boolean) serviceInTest.getContext().getAttribute(CircuitBreakerRetryPolicy.CIRCUIT_OPEN)); + assertThat((Boolean) serviceInTest.getContext().getAttribute(CircuitBreakerRetryPolicy.CIRCUIT_OPEN)).isFalse(); } private void incorrectStep() { diff --git a/src/test/java/org/springframework/retry/annotation/CircuitBreakerTests.java b/src/test/java/org/springframework/retry/annotation/CircuitBreakerTests.java index 6f07d55..7df7ba8 100644 --- a/src/test/java/org/springframework/retry/annotation/CircuitBreakerTests.java +++ b/src/test/java/org/springframework/retry/annotation/CircuitBreakerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2019 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. @@ -19,7 +19,7 @@ package org.springframework.retry.annotation; import java.util.Map; import org.aopalliance.intercept.MethodInterceptor; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.aop.Advisor; import org.springframework.aop.framework.Advised; @@ -32,10 +32,8 @@ import org.springframework.retry.RetryContext; import org.springframework.retry.policy.CircuitBreakerRetryPolicy; import org.springframework.retry.support.RetrySynchronizationManager; -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.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Dave Syer @@ -48,29 +46,29 @@ public class CircuitBreakerTests { public void vanilla() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class); Service service = context.getBean(Service.class); - assertTrue(AopUtils.isAopProxy(service)); + assertThat(AopUtils.isAopProxy(service)).isTrue(); try { service.service(); fail("Expected exception"); } catch (Exception e) { } - assertFalse((Boolean) service.getContext().getAttribute(CircuitBreakerRetryPolicy.CIRCUIT_OPEN)); + assertThat((Boolean) service.getContext().getAttribute(CircuitBreakerRetryPolicy.CIRCUIT_OPEN)).isFalse(); try { service.service(); fail("Expected exception"); } catch (Exception e) { } - assertFalse((Boolean) service.getContext().getAttribute(CircuitBreakerRetryPolicy.CIRCUIT_OPEN)); + assertThat((Boolean) service.getContext().getAttribute(CircuitBreakerRetryPolicy.CIRCUIT_OPEN)).isFalse(); try { service.service(); fail("Expected exception"); } catch (Exception e) { } - assertTrue((Boolean) service.getContext().getAttribute(CircuitBreakerRetryPolicy.CIRCUIT_OPEN)); - assertEquals(3, service.getCount()); + assertThat((Boolean) service.getContext().getAttribute(CircuitBreakerRetryPolicy.CIRCUIT_OPEN)).isTrue(); + assertThat(service.getCount()).isEqualTo(3); try { service.service(); fail("Expected exception"); @@ -78,22 +76,22 @@ public class CircuitBreakerTests { catch (Exception e) { } // Not called again once circuit is open - assertEquals(3, service.getCount()); + assertThat(service.getCount()).isEqualTo(3); service.expressionService(); - assertEquals(4, service.getCount()); + assertThat(service.getCount()).isEqualTo(4); Advised advised = (Advised) service; Advisor advisor = advised.getAdvisors()[0]; Map delegates = (Map) new DirectFieldAccessor(advisor).getPropertyValue("advice.delegates"); - assertTrue(delegates.size() == 1); + assertThat(delegates).hasSize(1); Map methodMap = (Map) delegates.values().iterator().next(); MethodInterceptor interceptor = (MethodInterceptor) methodMap .get(Service.class.getDeclaredMethod("expressionService")); DirectFieldAccessor accessor = new DirectFieldAccessor(interceptor); - assertEquals(8, accessor.getPropertyValue("retryOperations.retryPolicy.delegate.maxAttempts")); - assertEquals(19000L, accessor.getPropertyValue("retryOperations.retryPolicy.openTimeout")); - assertEquals(20000L, accessor.getPropertyValue("retryOperations.retryPolicy.resetTimeout")); - assertEquals("#root instanceof RuntimeExpression", - accessor.getPropertyValue("retryOperations.retryPolicy.delegate.expression.expression")); + assertThat(accessor.getPropertyValue("retryOperations.retryPolicy.delegate.maxAttempts")).isEqualTo(8); + assertThat(accessor.getPropertyValue("retryOperations.retryPolicy.openTimeout")).isEqualTo(19000L); + assertThat(accessor.getPropertyValue("retryOperations.retryPolicy.resetTimeout")).isEqualTo(20000L); + assertThat(accessor.getPropertyValue("retryOperations.retryPolicy.delegate.expression.expression")) + .isEqualTo("#root instanceof RuntimeExpression"); context.close(); } diff --git a/src/test/java/org/springframework/retry/annotation/EnableRetryTests.java b/src/test/java/org/springframework/retry/annotation/EnableRetryTests.java index c226c1b..992127c 100644 --- a/src/test/java/org/springframework/retry/annotation/EnableRetryTests.java +++ b/src/test/java/org/springframework/retry/annotation/EnableRetryTests.java @@ -21,8 +21,7 @@ import java.util.Map; import java.util.Properties; import org.aopalliance.intercept.MethodInterceptor; -import org.aopalliance.intercept.MethodInvocation; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.aop.framework.Advised; import org.springframework.aop.support.AopUtils; @@ -44,11 +43,9 @@ import org.springframework.retry.listener.RetryListenerSupport; import org.springframework.retry.policy.SimpleRetryPolicy; import org.springframework.retry.support.RetryTemplate; -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.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Dave Syer @@ -64,14 +61,14 @@ public class EnableRetryTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class); Service service = context.getBean(Service.class); Foo foo = context.getBean(Foo.class); - assertFalse(AopUtils.isAopProxy(foo)); - assertTrue(AopUtils.isAopProxy(service)); + assertThat(AopUtils.isAopProxy(foo)).isFalse(); + assertThat(AopUtils.isAopProxy(service)).isTrue(); service.service(); - assertEquals(3, service.getCount()); + assertThat(service.getCount()).isEqualTo(3); TestConfiguration config = context.getBean(TestConfiguration.class); - assertTrue(config.listener1); - assertTrue(config.listener2); - assertTrue(config.twoFirst); + assertThat(config.listener1).isTrue(); + assertThat(config.listener2).isTrue(); + assertThat(config.twoFirst).isTrue(); context.close(); } @@ -80,9 +77,9 @@ public class EnableRetryTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class); MultiService service = context.getBean(MultiService.class); service.service(); - assertEquals(3, service.getCount()); + assertThat(service.getCount()).isEqualTo(3); service.other(); - assertEquals(4, service.getCount()); + assertThat(service.getCount()).isEqualTo(4); context.close(); } @@ -91,10 +88,10 @@ public class EnableRetryTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( TestProxyConfiguration.class); Service service = context.getBean(Service.class); - assertTrue(AopUtils.isCglibProxy(service)); + assertThat(AopUtils.isCglibProxy(service)).isTrue(); RecoverableService recoverable = context.getBean(RecoverableService.class); recoverable.service(); - assertTrue(recoverable.isOtherAdviceCalled()); + assertThat(recoverable.isOtherAdviceCalled()).isTrue(); context.close(); } @@ -102,8 +99,8 @@ public class EnableRetryTests { public void marker() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class); Service service = context.getBean(Service.class); - assertTrue(AopUtils.isCglibProxy(service)); - assertTrue(service instanceof org.springframework.retry.interceptor.Retryable); + assertThat(AopUtils.isCglibProxy(service)).isTrue(); + assertThat(service instanceof org.springframework.retry.interceptor.Retryable).isTrue(); context.close(); } @@ -112,7 +109,7 @@ public class EnableRetryTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class); RecoverableService service = context.getBean(RecoverableService.class); service.service(); - assertEquals(3, service.getCount()); + assertThat(service.getCount()).isEqualTo(3); assertNotNull(service.getCause()); context.close(); } @@ -122,7 +119,7 @@ public class EnableRetryTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class); RetryableService service = context.getBean(RetryableService.class); service.service(); - assertEquals(3, service.getCount()); + assertThat(service.getCount()).isEqualTo(3); context.close(); } @@ -136,7 +133,7 @@ public class EnableRetryTests { } catch (IllegalStateException e) { } - assertEquals(1, service.getCount()); + assertThat(service.getCount()).isEqualTo(1); context.close(); } @@ -151,11 +148,11 @@ public class EnableRetryTests { } catch (IllegalStateException e) { } - assertEquals(1, service.getCount()); + assertThat(service.getCount()).isEqualTo(1); service.setExceptionToThrow(new IllegalArgumentException()); service.service(); - assertEquals(3, service.getCount()); + assertThat(service.getCount()).isEqualTo(3); context.close(); } @@ -168,10 +165,10 @@ public class EnableRetryTests { service.service(1); } catch (Exception e) { - assertEquals("Planned", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("Planned"); } } - assertEquals(3, service.getCount()); + assertThat(service.getCount()).isEqualTo(3); context.close(); } @@ -180,7 +177,7 @@ public class EnableRetryTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class); InterceptableService service = context.getBean(InterceptableService.class); service.service(); - assertEquals(5, service.getCount()); + assertThat(service.getCount()).isEqualTo(5); context.close(); } @@ -190,9 +187,9 @@ public class EnableRetryTests { TheInterface service = context.getBean(TheInterface.class); service.service1(); service.service2(); - assertEquals(4, service.getCount()); + assertThat(service.getCount()).isEqualTo(4); service.service3(); - assertTrue(service.isRecovered()); + assertThat(service.isRecovered()).isTrue(); context.close(); } @@ -201,7 +198,7 @@ public class EnableRetryTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class); NoRecoverInterface service = context.getBean(NoRecoverInterface.class); service.service(); - assertTrue(service.isRecovered()); + assertThat(service.isRecovered()).isTrue(); } @Test @@ -210,7 +207,7 @@ public class EnableRetryTests { NotAnnotatedInterface service = context.getBean(NotAnnotatedInterface.class); service.service1(); service.service2(); - assertEquals(5, service.getCount()); + assertThat(service.getCount()).isEqualTo(5); context.close(); } @@ -219,17 +216,17 @@ public class EnableRetryTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class); ExpressionService service = context.getBean(ExpressionService.class); service.service1(); - assertEquals(3, service.getCount()); + assertThat(service.getCount()).isEqualTo(3); try { service.service2(); fail("expected exception"); } catch (RuntimeException e) { - assertEquals("this cannot be retried", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("this cannot be retried"); } - assertEquals(4, service.getCount()); + assertThat(service.getCount()).isEqualTo(4); service.service3(); - assertEquals(9, service.getCount()); + assertThat(service.getCount()).isEqualTo(9); RetryConfiguration config = context.getBean(RetryConfiguration.class); AnnotationAwareRetryOperationsInterceptor advice = (AnnotationAwareRetryOperationsInterceptor) new DirectFieldAccessor( config).getPropertyValue("advice"); @@ -243,15 +240,15 @@ public class EnableRetryTests { DirectFieldAccessor templateAccessor = new DirectFieldAccessor(template); ExponentialBackOffPolicy backOff = (ExponentialBackOffPolicy) templateAccessor .getPropertyValue("backOffPolicy"); - assertEquals(1, backOff.getInitialInterval()); - assertEquals(5, backOff.getMaxInterval()); - assertEquals(1.1, backOff.getMultiplier(), 0.1); + assertThat(backOff.getInitialInterval()).isEqualTo(1); + assertThat(backOff.getMaxInterval()).isEqualTo(5); + assertThat(backOff.getMultiplier()).isEqualTo(1.1); SimpleRetryPolicy retryPolicy = (SimpleRetryPolicy) templateAccessor.getPropertyValue("retryPolicy"); - assertEquals(5, retryPolicy.getMaxAttempts()); + assertThat(retryPolicy.getMaxAttempts()).isEqualTo(5); service.service4(); - assertEquals(11, service.getCount()); + assertThat(service.getCount()).isEqualTo(11); service.service5(); - assertEquals(12, service.getCount()); + assertThat(service.getCount()).isEqualTo(12); context.close(); } diff --git a/src/test/java/org/springframework/retry/annotation/EnableRetryWithBackoffTests.java b/src/test/java/org/springframework/retry/annotation/EnableRetryWithBackoffTests.java index 88e8164..af854d7 100644 --- a/src/test/java/org/springframework/retry/annotation/EnableRetryWithBackoffTests.java +++ b/src/test/java/org/springframework/retry/annotation/EnableRetryWithBackoffTests.java @@ -16,20 +16,19 @@ package org.springframework.retry.annotation; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; - import java.util.ArrayList; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; + import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.retry.backoff.Sleeper; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Dave Syer * @@ -41,8 +40,8 @@ public class EnableRetryWithBackoffTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class); Service service = context.getBean(Service.class); service.service(); - assertEquals("[1000, 1000]", context.getBean(PeriodSleeper.class).getPeriods().toString()); - assertEquals(3, service.getCount()); + assertThat(context.getBean(PeriodSleeper.class).getPeriods().toString()).isEqualTo("[1000, 1000]"); + assertThat(service.getCount()).isEqualTo(3); context.close(); } @@ -52,8 +51,8 @@ public class EnableRetryWithBackoffTests { RandomService service = context.getBean(RandomService.class); service.service(); List periods = context.getBean(PeriodSleeper.class).getPeriods(); - assertTrue("Wrong periods: " + periods, periods.get(0) > 1000); - assertEquals(3, service.getCount()); + assertThat(periods.get(0) > 1000).describedAs("Wrong periods: %s" + periods.toString()).isTrue(); + assertThat(service.getCount()).isEqualTo(3); context.close(); } @@ -62,8 +61,8 @@ public class EnableRetryWithBackoffTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class); ExponentialService service = context.getBean(ExponentialService.class); service.service(); - assertEquals(3, service.getCount()); - assertEquals("[1000, 1100]", context.getBean(PeriodSleeper.class).getPeriods().toString()); + assertThat(service.getCount()).isEqualTo(3); + assertThat(context.getBean(PeriodSleeper.class).getPeriods().toString()).isEqualTo("[1000, 1100]"); context.close(); } @@ -72,11 +71,12 @@ public class EnableRetryWithBackoffTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class); ExponentialRandomService service = context.getBean(ExponentialRandomService.class); service.service(1); - assertEquals(3, service.getCount()); + assertThat(service.getCount()).isEqualTo(3); List periods = context.getBean(PeriodSleeper.class).getPeriods(); - assertNotEquals("[1000, 1100]", context.getBean(PeriodSleeper.class).getPeriods().toString()); - assertTrue("Wrong periods: " + periods, periods.get(0) > 1000); - assertTrue("Wrong periods: " + periods, periods.get(1) > 1100 && periods.get(1) < 1210); + assertThat(context.getBean(PeriodSleeper.class).getPeriods().toString()).isNotEqualTo("[1000, 1100]"); + assertThat(periods.get(0) > 1000).describedAs("Wrong periods: %s" + periods.toString()).isTrue(); + assertThat(periods.get(1) > 1100 && periods.get(1) < 1210).describedAs("Wrong periods: %s" + periods.toString()) + .isTrue(); context.close(); } @@ -85,11 +85,12 @@ public class EnableRetryWithBackoffTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class); ExponentialRandomExpressionService service = context.getBean(ExponentialRandomExpressionService.class); service.service(1); - assertEquals(3, service.getCount()); + assertThat(service.getCount()).isEqualTo(3); List periods = context.getBean(PeriodSleeper.class).getPeriods(); - assertNotEquals("[1000, 1100]", context.getBean(PeriodSleeper.class).getPeriods().toString()); - assertTrue("Wrong periods: " + periods, periods.get(0) > 1000); - assertTrue("Wrong periods: " + periods, periods.get(1) > 1100 && periods.get(1) < 1210); + assertThat(context.getBean(PeriodSleeper.class).getPeriods().toString()).isNotEqualTo("[1000, 1100]"); + assertThat(periods.get(0) > 1000).describedAs("Wrong periods: %s" + periods.toString()).isTrue(); + assertThat(periods.get(1) > 1100 && periods.get(1) < 1210).describedAs("Wrong periods: %s" + periods.toString()) + .isTrue(); context.close(); } diff --git a/src/test/java/org/springframework/retry/annotation/EnableRetryWithListenersTests.java b/src/test/java/org/springframework/retry/annotation/EnableRetryWithListenersTests.java index 0154b3c..3910d6e 100644 --- a/src/test/java/org/springframework/retry/annotation/EnableRetryWithListenersTests.java +++ b/src/test/java/org/springframework/retry/annotation/EnableRetryWithListenersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 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. @@ -16,9 +16,8 @@ package org.springframework.retry.annotation; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; -import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -27,8 +26,11 @@ import org.springframework.retry.RetryContext; import org.springframework.retry.RetryListener; import org.springframework.retry.listener.RetryListenerSupport; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Dave Syer + * @author Gary Russell * */ public class EnableRetryWithListenersTests { @@ -38,7 +40,7 @@ public class EnableRetryWithListenersTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class); Service service = context.getBean(Service.class); service.service(); - assertEquals(1, context.getBean(TestConfiguration.class).count); + assertThat(context.getBean(TestConfiguration.class).count).isEqualTo(1); context.close(); } @@ -48,8 +50,8 @@ public class EnableRetryWithListenersTests { TestConfigurationMultipleListeners.class); ServiceWithOverriddenListener service = context.getBean(ServiceWithOverriddenListener.class); service.service(); - assertEquals(1, context.getBean(TestConfigurationMultipleListeners.class).count1); - assertEquals(0, context.getBean(TestConfigurationMultipleListeners.class).count2); + assertThat(context.getBean(TestConfigurationMultipleListeners.class).count1).isEqualTo(1); + assertThat(context.getBean(TestConfigurationMultipleListeners.class).count2).isEqualTo(0); context.close(); } diff --git a/src/test/java/org/springframework/retry/annotation/PrototypeBeanTests.java b/src/test/java/org/springframework/retry/annotation/PrototypeBeanTests.java index 977e6e0..735b1a2 100644 --- a/src/test/java/org/springframework/retry/annotation/PrototypeBeanTests.java +++ b/src/test/java/org/springframework/retry/annotation/PrototypeBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 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,25 +16,23 @@ package org.springframework.retry.annotation; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; - -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +import static org.assertj.core.api.Assertions.assertThat; /** * @author Gary Russell * @since 1.2.2 * */ -@RunWith(SpringRunner.class) +@SpringJUnitConfig public class PrototypeBeanTests { @Autowired @@ -50,7 +48,7 @@ public class PrototypeBeanTests { public void testProtoBean() { this.bar1.foo("one"); this.bar2.foo("two"); - assertThat(this.foo.recovered, equalTo("two")); + assertThat(this.foo.recovered).isEqualTo("two"); } @Configuration diff --git a/src/test/java/org/springframework/retry/annotation/ProxyApplicationTests.java b/src/test/java/org/springframework/retry/annotation/ProxyApplicationTests.java index bdb9d99..f92f8cc 100644 --- a/src/test/java/org/springframework/retry/annotation/ProxyApplicationTests.java +++ b/src/test/java/org/springframework/retry/annotation/ProxyApplicationTests.java @@ -21,7 +21,7 @@ import java.net.URLClassLoader; import java.util.HashSet; import java.util.Set; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @@ -29,7 +29,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class ProxyApplicationTests { @@ -47,13 +47,13 @@ public class ProxyApplicationTests { int base = count(); runAndClose(); count = count(); - assertEquals("Class leak", base, count); + assertThat(count).describedAs("Class leak").isEqualTo(base); runAndClose(); count = count(); - assertEquals("Class leak", base, count); + assertThat(count).describedAs("Class leak").isEqualTo(base); runAndClose(); count = count(); - assertEquals("Class leak", base, count); + assertThat(count).describedAs("Class leak").isEqualTo(base); } @SuppressWarnings("resource") diff --git a/src/test/java/org/springframework/retry/annotation/RecoverAnnotationRecoveryHandlerTests.java b/src/test/java/org/springframework/retry/annotation/RecoverAnnotationRecoveryHandlerTests.java index ee4cf28..c43c7c4 100644 --- a/src/test/java/org/springframework/retry/annotation/RecoverAnnotationRecoveryHandlerTests.java +++ b/src/test/java/org/springframework/retry/annotation/RecoverAnnotationRecoveryHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 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. @@ -22,17 +22,14 @@ import java.util.Collections; import java.util.List; import java.util.Map; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import org.springframework.retry.ExhaustedRetryException; import org.springframework.util.CollectionUtils; import org.springframework.util.ReflectionUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Dave Syer @@ -43,21 +40,18 @@ import static org.junit.Assert.assertNotNull; */ public class RecoverAnnotationRecoveryHandlerTests { - @Rule - public ExpectedException expected = ExpectedException.none(); - @Test public void defaultRecoverMethod() { RecoverAnnotationRecoveryHandler handler = new RecoverAnnotationRecoveryHandler( new DefaultRecover(), ReflectionUtils.findMethod(DefaultRecover.class, "foo", String.class)); - assertEquals(1, handler.recover(new Object[] { "Dave" }, new RuntimeException("Planned"))); + assertThat(handler.recover(new Object[] { "Dave" }, new RuntimeException("Planned"))).isEqualTo(1); } @Test public void fewerArgs() { RecoverAnnotationRecoveryHandler handler = new RecoverAnnotationRecoveryHandler(new FewerArgs(), ReflectionUtils.findMethod(FewerArgs.class, "foo", String.class, int.class)); - assertEquals(1, handler.recover(new Object[] { "Dave" }, new RuntimeException("Planned"))); + assertThat(handler.recover(new Object[] { "Dave" }, new RuntimeException("Planned"))).isEqualTo(1); } @Test @@ -66,22 +60,22 @@ public class RecoverAnnotationRecoveryHandlerTests { RecoverAnnotationRecoveryHandler handler = new RecoverAnnotationRecoveryHandler(target, ReflectionUtils.findMethod(NoArgs.class, "foo")); handler.recover(new Object[0], new RuntimeException("Planned")); - assertEquals("Planned", target.getCause().getMessage()); + assertThat(target.getCause().getMessage()).isEqualTo("Planned"); } @Test public void noMatch() { RecoverAnnotationRecoveryHandler handler = new RecoverAnnotationRecoveryHandler( new SpecificException(), ReflectionUtils.findMethod(SpecificException.class, "foo", String.class)); - this.expected.expect(ExhaustedRetryException.class); - handler.recover(new Object[] { "Dave" }, new Error("Planned")); + assertThatExceptionOfType(ExhaustedRetryException.class) + .isThrownBy(() -> handler.recover(new Object[] { "Dave" }, new Error("Planned"))); } @Test public void specificRecoverMethod() { RecoverAnnotationRecoveryHandler handler = new RecoverAnnotationRecoveryHandler( new SpecificRecover(), ReflectionUtils.findMethod(SpecificRecover.class, "foo", String.class)); - assertEquals(2, handler.recover(new Object[] { "Dave" }, new RuntimeException("Planned"))); + assertThat(handler.recover(new Object[] { "Dave" }, new RuntimeException("Planned"))).isEqualTo(2); } @Test @@ -89,7 +83,7 @@ public class RecoverAnnotationRecoveryHandlerTests { Method foo = ReflectionUtils.findMethod(InAccessibleRecover.class, "foo", String.class); RecoverAnnotationRecoveryHandler handler = new RecoverAnnotationRecoveryHandler( new InAccessibleRecover(), foo); - assertEquals(1, handler.recover(new Object[] { "Dave" }, new RuntimeException("Planned"))); + assertThat(handler.recover(new Object[] { "Dave" }, new RuntimeException("Planned"))).isEqualTo(1); } @@ -98,8 +92,8 @@ public class RecoverAnnotationRecoveryHandlerTests { RecoverAnnotationRecoveryHandler fooHandler = new RecoverAnnotationRecoveryHandler( new InheritanceReturnTypeRecover(), ReflectionUtils.findMethod(InheritanceReturnTypeRecover.class, "foo", String.class)); - assertEquals(1, fooHandler.recover(new Object[] { "Aldo" }, new RuntimeException("Planned"))); - assertEquals(2, fooHandler.recover(new Object[] { "Aldo" }, new IllegalStateException("Planned"))); + assertThat(fooHandler.recover(new Object[] { "Aldo" }, new RuntimeException("Planned"))).isEqualTo(1); + assertThat(fooHandler.recover(new Object[] { "Aldo" }, new IllegalStateException("Planned"))).isEqualTo(2); } @@ -108,7 +102,7 @@ public class RecoverAnnotationRecoveryHandlerTests { RecoverAnnotationRecoveryHandler barHandler = new RecoverAnnotationRecoveryHandler( new InheritanceReturnTypeRecover(), ReflectionUtils.findMethod(InheritanceReturnTypeRecover.class, "bar", String.class)); - assertEquals(3, barHandler.recover(new Object[] { "Aldo" }, new RuntimeException("Planned"))); + assertThat(barHandler.recover(new Object[] { "Aldo" }, new RuntimeException("Planned"))).isEqualTo(3); } @@ -122,8 +116,8 @@ public class RecoverAnnotationRecoveryHandlerTests { @SuppressWarnings("unchecked") Map recoverResponseMap = (Map) handler.recover(new Object[] { "Aldo" }, new RuntimeException("Planned")); - assertFalse(CollectionUtils.isEmpty(recoverResponseMap)); - assertEquals("fooRecoverValue1", recoverResponseMap.get("foo")); + assertThat(CollectionUtils.isEmpty(recoverResponseMap)).isFalse(); + assertThat(recoverResponseMap.get("foo")).isEqualTo("fooRecoverValue1"); } @Test @@ -136,8 +130,8 @@ public class RecoverAnnotationRecoveryHandlerTests { @SuppressWarnings("unchecked") Map recoverResponseMap = (Map) handler.recover(new Object[] { "Aldo" }, new IllegalStateException("Planned")); - assertFalse(CollectionUtils.isEmpty(recoverResponseMap)); - assertEquals("fooRecoverValue2", recoverResponseMap.get("foo")); + assertThat(CollectionUtils.isEmpty(recoverResponseMap)).isFalse(); + assertThat(recoverResponseMap.get("foo")).isEqualTo("fooRecoverValue2"); } @Test @@ -150,9 +144,9 @@ public class RecoverAnnotationRecoveryHandlerTests { @SuppressWarnings("unchecked") Map recoverResponseMap = (Map) handler .recover(new Object[] { "Aldo" }, new RuntimeException("Planned")); - assertFalse(CollectionUtils.isEmpty(recoverResponseMap)); - assertNotNull(recoverResponseMap.get("bar")); - assertEquals("barRecoverValue", recoverResponseMap.get("bar").name); + assertThat(CollectionUtils.isEmpty(recoverResponseMap)).isFalse(); + assertThat(recoverResponseMap.get("bar")).isNotNull(); + assertThat(recoverResponseMap.get("bar").name).isEqualTo("barRecoverValue"); } @Test @@ -163,11 +157,11 @@ public class RecoverAnnotationRecoveryHandlerTests { @SuppressWarnings("unchecked") Map recoverResponseMapRe = (Map) fooHandler.recover(new Object[] { "Aldo" }, new RuntimeException("Planned")); - assertEquals(1, recoverResponseMapRe.get("foo").intValue()); + assertThat(recoverResponseMapRe.get("foo").intValue()).isEqualTo(1); @SuppressWarnings("unchecked") Map recoverResponseMapIse = (Map) fooHandler.recover(new Object[] { "Aldo" }, new IllegalStateException("Planned")); - assertEquals(2, recoverResponseMapIse.get("foo").intValue()); + assertThat(recoverResponseMapIse.get("foo").intValue()).isEqualTo(2); } /** @@ -182,7 +176,7 @@ public class RecoverAnnotationRecoveryHandlerTests { @SuppressWarnings("unchecked") Map recoverResponseMapRe = (Map) barHandler.recover(new Object[] { "Aldo" }, new RuntimeException("Planned")); - assertEquals(0.2, recoverResponseMapRe.get("bar")); + assertThat(recoverResponseMapRe.get("bar")).isEqualTo(0.2); } @Test @@ -193,11 +187,11 @@ public class RecoverAnnotationRecoveryHandlerTests { @SuppressWarnings("unchecked") Map>> recoverResponseMapRe = (Map>>) fooHandler .recover(new Object[] { "Aldo" }, new RuntimeException("Planned")); - assertEquals("fooRecoverReValue", recoverResponseMapRe.get("foo").get("foo").get(0)); + assertThat(recoverResponseMapRe.get("foo").get("foo").get(0)).isEqualTo("fooRecoverReValue"); @SuppressWarnings("unchecked") Map>> recoverResponseMapIe = (Map>>) fooHandler .recover(new Object[] { "Aldo" }, new IllegalStateException("Planned")); - assertEquals("fooRecoverIeValue", recoverResponseMapIe.get("foo").get("foo").get(0)); + assertThat(recoverResponseMapIe.get("foo").get("foo").get(0)).isEqualTo("fooRecoverIeValue"); } @Test @@ -208,7 +202,7 @@ public class RecoverAnnotationRecoveryHandlerTests { @SuppressWarnings("unchecked") Map>> recoverResponseMapRe = (Map>>) barHandler .recover(new Object[] { "Aldo" }, new RuntimeException("Planned")); - assertEquals("barRecoverNumberValue", recoverResponseMapRe.get("bar").get("bar").get(0.0)); + assertThat(recoverResponseMapRe.get("bar").get("bar").get(0.0)).isEqualTo("barRecoverNumberValue"); } @@ -217,7 +211,7 @@ public class RecoverAnnotationRecoveryHandlerTests { Method foo = ReflectionUtils.findMethod(MultipleQualifyingRecovers.class, "foo", String.class); RecoverAnnotationRecoveryHandler handler = new RecoverAnnotationRecoveryHandler( new MultipleQualifyingRecovers(), foo); - assertEquals(1, handler.recover(new Object[] { "Randell" }, new RuntimeException("Planned"))); + assertThat(handler.recover(new Object[] { "Randell" }, new RuntimeException("Planned"))).isEqualTo(1); } @@ -226,7 +220,7 @@ public class RecoverAnnotationRecoveryHandlerTests { Method foo = ReflectionUtils.findMethod(MultipleQualifyingRecovers.class, "foo", String.class); RecoverAnnotationRecoveryHandler handler = new RecoverAnnotationRecoveryHandler( new MultipleQualifyingRecovers(), foo); - assertEquals(1, handler.recover(new Object[] { null }, new RuntimeException("Planned"))); + assertThat(handler.recover(new Object[] { null }, new RuntimeException("Planned"))).isEqualTo(1); } @@ -235,7 +229,7 @@ public class RecoverAnnotationRecoveryHandlerTests { Method foo = ReflectionUtils.findMethod(MultipleQualifyingRecoversNoThrowable.class, "foo", String.class); RecoverAnnotationRecoveryHandler handler = new RecoverAnnotationRecoveryHandler( new MultipleQualifyingRecoversNoThrowable(), foo); - assertEquals(1, handler.recover(new Object[] { null }, new RuntimeException("Planned"))); + assertThat(handler.recover(new Object[] { null }, new RuntimeException("Planned"))).isEqualTo(1); } @@ -244,7 +238,7 @@ public class RecoverAnnotationRecoveryHandlerTests { Method foo = ReflectionUtils.findMethod(MultipleQualifyingRecoversReOrdered.class, "foo", String.class); RecoverAnnotationRecoveryHandler handler = new RecoverAnnotationRecoveryHandler( new MultipleQualifyingRecoversReOrdered(), foo); - assertEquals(3, handler.recover(new Object[] { "Randell" }, new RuntimeException("Planned"))); + assertThat(handler.recover(new Object[] { "Randell" }, new RuntimeException("Planned"))).isEqualTo(3); } @@ -253,8 +247,9 @@ public class RecoverAnnotationRecoveryHandlerTests { Method foo = ReflectionUtils.findMethod(MultipleQualifyingRecoversExtendsThrowable.class, "foo", String.class); RecoverAnnotationRecoveryHandler handler = new RecoverAnnotationRecoveryHandler( new MultipleQualifyingRecoversExtendsThrowable(), foo); - assertEquals(2, handler.recover(new Object[] { "Kevin" }, new IllegalArgumentException("Planned"))); - assertEquals(3, handler.recover(new Object[] { "Kevin" }, new UnsupportedOperationException("Planned"))); + assertThat(handler.recover(new Object[] { "Kevin" }, new IllegalArgumentException("Planned"))).isEqualTo(2); + assertThat(handler.recover(new Object[] { "Kevin" }, new UnsupportedOperationException("Planned"))) + .isEqualTo(3); } @@ -263,8 +258,8 @@ public class RecoverAnnotationRecoveryHandlerTests { Method foo = ReflectionUtils.findMethod(InheritanceOnArgumentClass.class, "foo", List.class); RecoverAnnotationRecoveryHandler handler = new RecoverAnnotationRecoveryHandler( new InheritanceOnArgumentClass(), foo); - assertEquals(1, - handler.recover(new Object[] { new ArrayList() }, new IllegalArgumentException("Planned"))); + assertThat(handler.recover(new Object[] { new ArrayList() }, new IllegalArgumentException("Planned"))) + .isEqualTo(1); } @Test @@ -272,7 +267,7 @@ public class RecoverAnnotationRecoveryHandlerTests { Method foo = ReflectionUtils.findMethod(RecoverByRetryableName.class, "foo", String.class); RecoverAnnotationRecoveryHandler handler = new RecoverAnnotationRecoveryHandler( new RecoverByRetryableName(), foo); - assertEquals(2, handler.recover(new Object[] { "Kevin" }, new RuntimeException("Planned"))); + assertThat(handler.recover(new Object[] { "Kevin" }, new RuntimeException("Planned"))).isEqualTo(2); } @Test @@ -280,7 +275,7 @@ public class RecoverAnnotationRecoveryHandlerTests { Method foo = ReflectionUtils.findMethod(RecoverByRetryableNameWithPrimitiveArgs.class, "foo", int.class); RecoverAnnotationRecoveryHandler handler = new RecoverAnnotationRecoveryHandler( new RecoverByRetryableNameWithPrimitiveArgs(), foo); - assertEquals(2, handler.recover(new Object[] { 2 }, new RuntimeException("Planned"))); + assertThat(handler.recover(new Object[] { 2 }, new RuntimeException("Planned"))).isEqualTo(2); } private static class InAccessibleRecover { diff --git a/src/test/java/org/springframework/retry/backoff/BackOffPolicyBuilderTests.java b/src/test/java/org/springframework/retry/backoff/BackOffPolicyBuilderTests.java index d4344d8..0a17e69 100644 --- a/src/test/java/org/springframework/retry/backoff/BackOffPolicyBuilderTests.java +++ b/src/test/java/org/springframework/retry/backoff/BackOffPolicyBuilderTests.java @@ -16,16 +16,16 @@ package org.springframework.retry.backoff; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.beans.DirectFieldAccessor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** * @author Tomaz Fernandes + * @author Gary Russell * @since 1.3.3 */ public class BackOffPolicyBuilderTests { @@ -33,29 +33,29 @@ public class BackOffPolicyBuilderTests { @Test public void shouldCreateDefaultBackOffPolicy() { BackOffPolicy backOffPolicy = BackOffPolicyBuilder.newDefaultPolicy(); - assertTrue(FixedBackOffPolicy.class.isAssignableFrom(backOffPolicy.getClass())); + assertThat(FixedBackOffPolicy.class.isAssignableFrom(backOffPolicy.getClass())).isTrue(); FixedBackOffPolicy policy = (FixedBackOffPolicy) backOffPolicy; - assertEquals(1000, policy.getBackOffPeriod()); + assertThat(policy.getBackOffPeriod()).isEqualTo(1000); } @Test public void shouldCreateDefaultBackOffPolicyViaNewBuilder() { Sleeper mockSleeper = mock(Sleeper.class); BackOffPolicy backOffPolicy = BackOffPolicyBuilder.newBuilder().sleeper(mockSleeper).build(); - assertTrue(FixedBackOffPolicy.class.isAssignableFrom(backOffPolicy.getClass())); + assertThat(FixedBackOffPolicy.class.isAssignableFrom(backOffPolicy.getClass())).isTrue(); FixedBackOffPolicy policy = (FixedBackOffPolicy) backOffPolicy; - assertEquals(1000, policy.getBackOffPeriod()); - assertEquals(mockSleeper, new DirectFieldAccessor(policy).getPropertyValue("sleeper")); + assertThat(policy.getBackOffPeriod()).isEqualTo(1000); + assertThat(new DirectFieldAccessor(policy).getPropertyValue("sleeper")).isEqualTo(mockSleeper); } @Test public void shouldCreateFixedBackOffPolicy() { Sleeper mockSleeper = mock(Sleeper.class); BackOffPolicy backOffPolicy = BackOffPolicyBuilder.newBuilder().delay(3500).sleeper(mockSleeper).build(); - assertTrue(FixedBackOffPolicy.class.isAssignableFrom(backOffPolicy.getClass())); + assertThat(FixedBackOffPolicy.class.isAssignableFrom(backOffPolicy.getClass())).isTrue(); FixedBackOffPolicy policy = (FixedBackOffPolicy) backOffPolicy; - assertEquals(3500, policy.getBackOffPeriod()); - assertEquals(mockSleeper, new DirectFieldAccessor(policy).getPropertyValue("sleeper")); + assertThat(policy.getBackOffPeriod()).isEqualTo(3500); + assertThat(new DirectFieldAccessor(policy).getPropertyValue("sleeper")).isEqualTo(mockSleeper); } @Test @@ -63,11 +63,11 @@ public class BackOffPolicyBuilderTests { Sleeper mockSleeper = mock(Sleeper.class); BackOffPolicy backOffPolicy = BackOffPolicyBuilder.newBuilder().delay(1).maxDelay(5000).sleeper(mockSleeper) .build(); - assertTrue(UniformRandomBackOffPolicy.class.isAssignableFrom(backOffPolicy.getClass())); + assertThat(UniformRandomBackOffPolicy.class.isAssignableFrom(backOffPolicy.getClass())).isTrue(); UniformRandomBackOffPolicy policy = (UniformRandomBackOffPolicy) backOffPolicy; - assertEquals(1, policy.getMinBackOffPeriod()); - assertEquals(5000, policy.getMaxBackOffPeriod()); - assertEquals(mockSleeper, new DirectFieldAccessor(policy).getPropertyValue("sleeper")); + assertThat(policy.getMinBackOffPeriod()).isEqualTo(1); + assertThat(policy.getMaxBackOffPeriod()).isEqualTo(5000); + assertThat(new DirectFieldAccessor(policy).getPropertyValue("sleeper")).isEqualTo(mockSleeper); } @Test @@ -75,12 +75,12 @@ public class BackOffPolicyBuilderTests { Sleeper mockSleeper = mock(Sleeper.class); BackOffPolicy backOffPolicy = BackOffPolicyBuilder.newBuilder().delay(100).maxDelay(1000).multiplier(2) .random(false).sleeper(mockSleeper).build(); - assertTrue(ExponentialBackOffPolicy.class.isAssignableFrom(backOffPolicy.getClass())); + assertThat(ExponentialBackOffPolicy.class.isAssignableFrom(backOffPolicy.getClass())).isTrue(); ExponentialBackOffPolicy policy = (ExponentialBackOffPolicy) backOffPolicy; - assertEquals(100, policy.getInitialInterval()); - assertEquals(1000, policy.getMaxInterval()); - assertEquals(2, policy.getMultiplier(), 0); - assertEquals(mockSleeper, new DirectFieldAccessor(policy).getPropertyValue("sleeper")); + assertThat(policy.getInitialInterval()).isEqualTo(100); + assertThat(policy.getMaxInterval()).isEqualTo(1000); + assertThat(policy.getMultiplier()).isEqualTo(2); + assertThat(new DirectFieldAccessor(policy).getPropertyValue("sleeper")).isEqualTo(mockSleeper); } @Test @@ -88,12 +88,12 @@ public class BackOffPolicyBuilderTests { Sleeper mockSleeper = mock(Sleeper.class); BackOffPolicy backOffPolicy = BackOffPolicyBuilder.newBuilder().delay(10000).maxDelay(100000).multiplier(10) .random(true).sleeper(mockSleeper).build(); - assertTrue(ExponentialRandomBackOffPolicy.class.isAssignableFrom(backOffPolicy.getClass())); + assertThat(ExponentialRandomBackOffPolicy.class.isAssignableFrom(backOffPolicy.getClass())).isTrue(); ExponentialRandomBackOffPolicy policy = (ExponentialRandomBackOffPolicy) backOffPolicy; - assertEquals(10000, policy.getInitialInterval()); - assertEquals(100000, policy.getMaxInterval()); - assertEquals(10, policy.getMultiplier(), 0); - assertEquals(mockSleeper, new DirectFieldAccessor(policy).getPropertyValue("sleeper")); + assertThat(policy.getInitialInterval()).isEqualTo(10000); + assertThat(policy.getMaxInterval()).isEqualTo(100000); + assertThat(policy.getMultiplier()).isEqualTo(10); + assertThat(new DirectFieldAccessor(policy).getPropertyValue("sleeper")).isEqualTo(mockSleeper); } } diff --git a/src/test/java/org/springframework/retry/backoff/BackOffPolicySerializationTests.java b/src/test/java/org/springframework/retry/backoff/BackOffPolicySerializationTests.java index c2d7560..d7440d6 100644 --- a/src/test/java/org/springframework/retry/backoff/BackOffPolicySerializationTests.java +++ b/src/test/java/org/springframework/retry/backoff/BackOffPolicySerializationTests.java @@ -20,13 +20,12 @@ import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.regex.Pattern; +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.MethodSource; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.config.BeanDefinition; @@ -37,21 +36,19 @@ import org.springframework.retry.context.RetryContextSupport; import org.springframework.util.ClassUtils; import org.springframework.util.SerializationUtils; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Dave Syer + * @author Gary Russell * */ -@RunWith(Parameterized.class) public class BackOffPolicySerializationTests { private static final Log logger = LogFactory.getLog(BackOffPolicySerializationTests.class); - private final BackOffPolicy policy; - - @Parameters(name = "{index}: {0}") - public static List policies() { + @SuppressWarnings("deprecation") + public static Stream policies() { List result = new ArrayList<>(); ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true); scanner.addIncludeFilter(new AssignableTypeFilter(BackOffPolicy.class)); @@ -68,15 +65,13 @@ public class BackOffPolicySerializationTests { logger.warn("Cannot create instance of " + beanDefinition.getBeanClassName()); } } - return result; + return result.stream(); } - public BackOffPolicySerializationTests(BackOffPolicy policy) { - this.policy = policy; - } - - @Test - public void testSerializationCycleForContext() { + @ParameterizedTest + @MethodSource("policies") + @SuppressWarnings("deprecation") + public void testSerializationCycleForContext(BackOffPolicy policy) { BackOffContext context = policy.start(new RetryContextSupport(null)); if (context != null) { assertTrue(SerializationUtils.deserialize(SerializationUtils.serialize(context)) instanceof BackOffContext); diff --git a/src/test/java/org/springframework/retry/backoff/ExponentialBackOffPolicyTests.java b/src/test/java/org/springframework/retry/backoff/ExponentialBackOffPolicyTests.java index dca7ac8..ab63a4f 100644 --- a/src/test/java/org/springframework/retry/backoff/ExponentialBackOffPolicyTests.java +++ b/src/test/java/org/springframework/retry/backoff/ExponentialBackOffPolicyTests.java @@ -16,14 +16,14 @@ package org.springframework.retry.backoff; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop * @author Dave Syer + * @author Gary Russell */ public class ExponentialBackOffPolicyTests { @@ -33,28 +33,28 @@ public class ExponentialBackOffPolicyTests { public void testSetMaxInterval() { ExponentialBackOffPolicy strategy = new ExponentialBackOffPolicy(); strategy.setMaxInterval(1000); - assertTrue(strategy.toString().contains("maxInterval=1000")); + assertThat(strategy.toString()).contains("maxInterval=1000"); strategy.setMaxInterval(0); // The minimum value for the max interval is 1 - assertTrue(strategy.toString().contains("maxInterval=1")); + assertThat(strategy.toString()).contains("maxInterval=1"); } @Test public void testSetInitialInterval() { ExponentialBackOffPolicy strategy = new ExponentialBackOffPolicy(); strategy.setInitialInterval(10000); - assertTrue(strategy.toString().contains("initialInterval=10000,")); + assertThat(strategy.toString()).contains("initialInterval=10000,"); strategy.setInitialInterval(0); - assertTrue(strategy.toString().contains("initialInterval=1,")); + assertThat(strategy.toString()).contains("initialInterval=1,"); } @Test public void testSetMultiplier() { ExponentialBackOffPolicy strategy = new ExponentialBackOffPolicy(); strategy.setMultiplier(3.); - assertTrue(strategy.toString().contains("multiplier=3.")); + assertThat(strategy.toString()).contains("multiplier=3."); strategy.setMultiplier(.5); - assertTrue(strategy.toString().contains("multiplier=1.")); + assertThat(strategy.toString()).contains("multiplier=1."); } @Test @@ -63,7 +63,7 @@ public class ExponentialBackOffPolicyTests { strategy.setSleeper(sleeper); BackOffContext context = strategy.start(null); strategy.backOff(context); - assertEquals(ExponentialBackOffPolicy.DEFAULT_INITIAL_INTERVAL, sleeper.getLastBackOff()); + assertThat(sleeper.getLastBackOff()).isEqualTo(ExponentialBackOffPolicy.DEFAULT_INITIAL_INTERVAL); } @Test @@ -73,7 +73,7 @@ public class ExponentialBackOffPolicyTests { strategy.setSleeper(sleeper); BackOffContext context = strategy.start(null); strategy.backOff(context); - assertEquals(50, sleeper.getLastBackOff()); + assertThat(sleeper.getLastBackOff()).isEqualTo(50); } @Test @@ -87,7 +87,7 @@ public class ExponentialBackOffPolicyTests { BackOffContext context = strategy.start(null); for (int x = 0; x < 5; x++) { strategy.backOff(context); - assertEquals(seed, sleeper.getLastBackOff()); + assertThat(sleeper.getLastBackOff()).isEqualTo(seed); seed *= multiplier; } } diff --git a/src/test/java/org/springframework/retry/backoff/ExponentialRandomBackOffPolicyTests.java b/src/test/java/org/springframework/retry/backoff/ExponentialRandomBackOffPolicyTests.java index 1218c45..214575e 100644 --- a/src/test/java/org/springframework/retry/backoff/ExponentialRandomBackOffPolicyTests.java +++ b/src/test/java/org/springframework/retry/backoff/ExponentialRandomBackOffPolicyTests.java @@ -16,20 +16,21 @@ package org.springframework.retry.backoff; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; + import org.springframework.retry.policy.SimpleRetryPolicy; import org.springframework.retry.support.RetrySimulation; import org.springframework.retry.support.RetrySimulator; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Dave Syer * @author Jon Travis * @author Chase Diem + * @author Gary Russell * */ public class ExponentialRandomBackOffPolicyTests { @@ -59,13 +60,15 @@ public class ExponentialRandomBackOffPolicyTests { List sleeps = simulation.getLongestTotalSleepSequence().getSleeps(); System.out.println("Single trial of " + backOffPolicy + ": sleeps=" + sleeps); - assertEquals(MAX_RETRIES - 1, sleeps.size()); + assertThat(sleeps).hasSize(MAX_RETRIES - 1); long initialInterval = backOffPolicy.getInitialInterval(); for (int i = 0; i < sleeps.size(); i++) { long expectedMaxValue = 2 * (long) (initialInterval + initialInterval * Math.max(1, Math.pow(backOffPolicy.getMultiplier(), i))); - assertTrue("Found a sleep [" + sleeps.get(i) + "] which exceeds our max expected value of " - + expectedMaxValue + " at interval " + i, sleeps.get(i) < expectedMaxValue); + assertThat(sleeps.get(i)) + .describedAs("Found a sleep [%d] which exceeds our max expected value of %d at interval %d", + sleeps.get(i), expectedMaxValue, i) + .isLessThan(expectedMaxValue); } } @@ -80,13 +83,15 @@ public class ExponentialRandomBackOffPolicyTests { List sleeps = simulation.getLongestTotalSleepSequence().getSleeps(); System.out.println("Single trial of " + backOffPolicy + ": sleeps=" + sleeps); - assertEquals(MAX_RETRIES - 1, sleeps.size()); + assertThat(sleeps).hasSize(MAX_RETRIES - 1); long initialInterval = backOffPolicy.getInitialInterval(); for (int i = 0; i < sleeps.size(); i++) { long expectedMaxValue = 2 * (long) (initialInterval + initialInterval * Math.max(1, Math.pow(backOffPolicy.getMultiplier(), i))); - assertTrue("Found a sleep [" + sleeps.get(i) + "] which exceeds our max interval value of " - + expectedMaxValue + " at interval " + i, sleeps.get(i) <= maxInterval); + assertThat(sleeps.get(i)) + .describedAs("Found a sleep [%d] which exceeds our max expected value of %d at interval %d", + sleeps.get(i), expectedMaxValue, i) + .isLessThanOrEqualTo(expectedMaxValue); } } diff --git a/src/test/java/org/springframework/retry/backoff/FixedBackOffPolicyTests.java b/src/test/java/org/springframework/retry/backoff/FixedBackOffPolicyTests.java index 87b9cb2..5ca7091 100644 --- a/src/test/java/org/springframework/retry/backoff/FixedBackOffPolicyTests.java +++ b/src/test/java/org/springframework/retry/backoff/FixedBackOffPolicyTests.java @@ -16,13 +16,14 @@ package org.springframework.retry.backoff; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop * @author Dave Syer + * @author Gary Russell * @since 2.1 */ public class FixedBackOffPolicyTests { @@ -36,8 +37,8 @@ public class FixedBackOffPolicyTests { strategy.setSleeper(sleeper); strategy.backOff(null); // We should see a zero backoff if we try to set it negative - assertEquals(1, sleeper.getBackOffs().length); - assertEquals(1, sleeper.getLastBackOff()); + assertThat(sleeper.getBackOffs().length).isEqualTo(1); + assertThat(sleeper.getLastBackOff()).isEqualTo(1); } @Test @@ -47,8 +48,8 @@ public class FixedBackOffPolicyTests { strategy.setBackOffPeriod(backOffPeriod); strategy.setSleeper(sleeper); strategy.backOff(null); - assertEquals(1, sleeper.getBackOffs().length); - assertEquals(backOffPeriod, sleeper.getLastBackOff()); + assertThat(sleeper.getBackOffs().length).isEqualTo(1); + assertThat(sleeper.getLastBackOff()).isEqualTo(backOffPeriod); } @Test @@ -59,9 +60,9 @@ public class FixedBackOffPolicyTests { strategy.setSleeper(sleeper); for (int x = 0; x < 10; x++) { strategy.backOff(null); - assertEquals(backOffPeriod, sleeper.getLastBackOff()); + assertThat(sleeper.getLastBackOff()).isEqualTo(backOffPeriod); } - assertEquals(10, sleeper.getBackOffs().length); + assertThat(sleeper.getBackOffs().length).isEqualTo(10); } } diff --git a/src/test/java/org/springframework/retry/backoff/ThreadWaitSleeperTests.java b/src/test/java/org/springframework/retry/backoff/ThreadWaitSleeperTests.java index 0d8c494..7d47449 100644 --- a/src/test/java/org/springframework/retry/backoff/ThreadWaitSleeperTests.java +++ b/src/test/java/org/springframework/retry/backoff/ThreadWaitSleeperTests.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,13 +16,14 @@ package org.springframework.retry.backoff; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer * @author Artem Bilan + * @author Gary Russell */ public class ThreadWaitSleeperTests { @@ -39,8 +40,8 @@ public class ThreadWaitSleeperTests { private void assertEqualsApprox(long desired, long actual, long variance) { long lower = desired - variance; long upper = desired + 2 * variance; - assertTrue("Expected value to be between '" + lower + "' and '" + upper + "' but was '" + actual + "'", - lower <= actual); + assertThat(lower).describedAs("Expected value to be between '%d' and '%d' but was '%d'", lower, upper, actual) + .isLessThanOrEqualTo(actual); } } diff --git a/src/test/java/org/springframework/retry/backoff/UniformRandomBackOffPolicyTests.java b/src/test/java/org/springframework/retry/backoff/UniformRandomBackOffPolicyTests.java index d3922bb..1dd3095 100644 --- a/src/test/java/org/springframework/retry/backoff/UniformRandomBackOffPolicyTests.java +++ b/src/test/java/org/springframework/retry/backoff/UniformRandomBackOffPolicyTests.java @@ -16,12 +16,13 @@ package org.springframework.retry.backoff; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Tomaz Fernandes + * @author Gary Russell * @since 1.3.2 */ public class UniformRandomBackOffPolicyTests { @@ -35,8 +36,8 @@ public class UniformRandomBackOffPolicyTests { backOffPolicy.setMaxBackOffPeriod(maxBackOff); UniformRandomBackOffPolicy withSleeper = backOffPolicy.withSleeper(new DummySleeper()); - assertEquals(minBackOff, withSleeper.getMinBackOffPeriod()); - assertEquals(maxBackOff, withSleeper.getMaxBackOffPeriod()); + assertThat(withSleeper.getMinBackOffPeriod()).isEqualTo(minBackOff); + assertThat(withSleeper.getMaxBackOffPeriod()).isEqualTo(maxBackOff); } } diff --git a/src/test/java/org/springframework/retry/interceptor/RetryInterceptorBuilderTests.java b/src/test/java/org/springframework/retry/interceptor/RetryInterceptorBuilderTests.java index 572dfc4..5b98ea7 100644 --- a/src/test/java/org/springframework/retry/interceptor/RetryInterceptorBuilderTests.java +++ b/src/test/java/org/springframework/retry/interceptor/RetryInterceptorBuilderTests.java @@ -15,15 +15,13 @@ */ package org.springframework.retry.interceptor; -import static org.junit.Assert.*; - import java.util.Collections; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.aopalliance.intercept.MethodInterceptor; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.aop.Pointcut; import org.springframework.aop.framework.ProxyFactory; @@ -34,6 +32,9 @@ import org.springframework.retry.policy.SimpleRetryPolicy; import org.springframework.retry.support.RetryTemplate; import org.springframework.retry.util.test.TestUtils; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertSame; + /** * @author Gary Russell * @author Artem Bilan @@ -45,7 +46,7 @@ public class RetryInterceptorBuilderTests { @Test public void testBasic() { StatefulRetryOperationsInterceptor interceptor = RetryInterceptorBuilder.stateful().build(); - assertEquals(3, TestUtils.getPropertyValue(interceptor, "retryOperations.retryPolicy.maxAttempts")); + assertThat(TestUtils.getPropertyValue(interceptor, "retryOperations.retryPolicy.maxAttempts")).isEqualTo(3); } @Test @@ -53,14 +54,14 @@ public class RetryInterceptorBuilderTests { RetryOperations retryOperations = new RetryTemplate(); StatefulRetryOperationsInterceptor interceptor = RetryInterceptorBuilder.stateful() .retryOperations(retryOperations).build(); - assertEquals(3, TestUtils.getPropertyValue(interceptor, "retryOperations.retryPolicy.maxAttempts")); + assertThat(TestUtils.getPropertyValue(interceptor, "retryOperations.retryPolicy.maxAttempts")).isEqualTo(3); assertSame(retryOperations, TestUtils.getPropertyValue(interceptor, "retryOperations")); } @Test public void testWithMoreAttempts() { StatefulRetryOperationsInterceptor interceptor = RetryInterceptorBuilder.stateful().maxAttempts(5).build(); - assertEquals(5, TestUtils.getPropertyValue(interceptor, "retryOperations.retryPolicy.maxAttempts")); + assertThat(TestUtils.getPropertyValue(interceptor, "retryOperations.retryPolicy.maxAttempts")).isEqualTo(5); } @Test @@ -68,10 +69,11 @@ public class RetryInterceptorBuilderTests { StatefulRetryOperationsInterceptor interceptor = RetryInterceptorBuilder.stateful().maxAttempts(5) .backOffOptions(1, 2, 10).build(); - assertEquals(5, TestUtils.getPropertyValue(interceptor, "retryOperations.retryPolicy.maxAttempts")); - assertEquals(1L, TestUtils.getPropertyValue(interceptor, "retryOperations.backOffPolicy.initialInterval")); - assertEquals(2.0, TestUtils.getPropertyValue(interceptor, "retryOperations.backOffPolicy.multiplier")); - assertEquals(10L, TestUtils.getPropertyValue(interceptor, "retryOperations.backOffPolicy.maxInterval")); + assertThat(TestUtils.getPropertyValue(interceptor, "retryOperations.retryPolicy.maxAttempts")).isEqualTo(5); + assertThat(TestUtils.getPropertyValue(interceptor, "retryOperations.backOffPolicy.initialInterval")) + .isEqualTo(1L); + assertThat(TestUtils.getPropertyValue(interceptor, "retryOperations.backOffPolicy.multiplier")).isEqualTo(2.0); + assertThat(TestUtils.getPropertyValue(interceptor, "retryOperations.backOffPolicy.maxInterval")).isEqualTo(10L); } @Test @@ -79,8 +81,9 @@ public class RetryInterceptorBuilderTests { StatefulRetryOperationsInterceptor interceptor = RetryInterceptorBuilder.stateful().maxAttempts(5) .backOffPolicy(new FixedBackOffPolicy()).build(); - assertEquals(5, TestUtils.getPropertyValue(interceptor, "retryOperations.retryPolicy.maxAttempts")); - assertEquals(1000L, TestUtils.getPropertyValue(interceptor, "retryOperations.backOffPolicy.backOffPeriod")); + assertThat(TestUtils.getPropertyValue(interceptor, "retryOperations.retryPolicy.maxAttempts")).isEqualTo(5); + assertThat(TestUtils.getPropertyValue(interceptor, "retryOperations.backOffPolicy.backOffPeriod")) + .isEqualTo(1000L); } @Test @@ -92,8 +95,9 @@ public class RetryInterceptorBuilderTests { return false; }).backOffPolicy(new FixedBackOffPolicy()).build(); - assertEquals(5, TestUtils.getPropertyValue(interceptor, "retryOperations.retryPolicy.maxAttempts")); - assertEquals(1000L, TestUtils.getPropertyValue(interceptor, "retryOperations.backOffPolicy.backOffPeriod")); + assertThat(TestUtils.getPropertyValue(interceptor, "retryOperations.retryPolicy.maxAttempts")).isEqualTo(5); + assertThat(TestUtils.getPropertyValue(interceptor, "retryOperations.backOffPolicy.backOffPeriod")) + .isEqualTo(1000L); final AtomicInteger count = new AtomicInteger(); Foo delegate = createDelegate(interceptor, count); Object message = ""; @@ -101,10 +105,10 @@ public class RetryInterceptorBuilderTests { delegate.onMessage("", message); } catch (RuntimeException e) { - assertEquals("foo", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("foo"); } - assertEquals(1, count.get()); - assertTrue(latch.await(0, TimeUnit.SECONDS)); + assertThat(count.get()).isEqualTo(1); + assertThat(latch.await(0, TimeUnit.SECONDS)).isTrue(); } @Test @@ -113,7 +117,7 @@ public class RetryInterceptorBuilderTests { .retryPolicy(new SimpleRetryPolicy(15, Collections., Boolean>singletonMap(Exception.class, true), true)) .build(); - assertEquals(15, TestUtils.getPropertyValue(interceptor, "retryOperations.retryPolicy.maxAttempts")); + assertThat(TestUtils.getPropertyValue(interceptor, "retryOperations.retryPolicy.maxAttempts")).isEqualTo(15); } @Test @@ -124,7 +128,7 @@ public class RetryInterceptorBuilderTests { return "foo"; }).build(); - assertEquals(3, TestUtils.getPropertyValue(interceptor, "retryOperations.retryPolicy.maxAttempts")); + assertThat(TestUtils.getPropertyValue(interceptor, "retryOperations.retryPolicy.maxAttempts")).isEqualTo(3); final AtomicInteger count = new AtomicInteger(); Foo delegate = createDelegate(interceptor, count); Object message = ""; @@ -132,10 +136,10 @@ public class RetryInterceptorBuilderTests { delegate.onMessage("", message); } catch (RuntimeException e) { - assertEquals("foo", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("foo"); } - assertEquals(1, count.get()); - assertTrue(latch.await(0, TimeUnit.SECONDS)); + assertThat(count.get()).isEqualTo(1); + assertThat(latch.await(0, TimeUnit.SECONDS)).isTrue(); } private Foo createDelegate(MethodInterceptor interceptor, final AtomicInteger count) { diff --git a/src/test/java/org/springframework/retry/interceptor/RetryOperationsInterceptorTests.java b/src/test/java/org/springframework/retry/interceptor/RetryOperationsInterceptorTests.java index e9bc569..2cc9825 100644 --- a/src/test/java/org/springframework/retry/interceptor/RetryOperationsInterceptorTests.java +++ b/src/test/java/org/springframework/retry/interceptor/RetryOperationsInterceptorTests.java @@ -26,8 +26,8 @@ import java.util.concurrent.atomic.AtomicBoolean; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; -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.Advised; import org.springframework.aop.framework.ProxyFactory; @@ -44,13 +44,8 @@ import org.springframework.transaction.support.TransactionSynchronizationAdapter import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.util.ClassUtils; -import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.fail; public class RetryOperationsInterceptorTests { @@ -66,7 +61,7 @@ public class RetryOperationsInterceptorTests { private RetryContext context; - @Before + @BeforeEach public void setUp() { this.interceptor = new RetryOperationsInterceptor(); RetryTemplate retryTemplate = new RetryTemplate(); @@ -93,7 +88,7 @@ public class RetryOperationsInterceptorTests { @Override public boolean open(RetryContext context, RetryCallback callback) { - assertFalse(calledFirst.get()); + assertThat(calledFirst.get()).isFalse(); return true; } @@ -109,7 +104,7 @@ public class RetryOperationsInterceptorTests { public void testDefaultInterceptorSunnyDay() throws Exception { ((Advised) this.service).addAdvice(this.interceptor); this.service.service(); - assertEquals(2, count); + assertThat(count).isEqualTo(2); } @Test @@ -117,8 +112,8 @@ public class RetryOperationsInterceptorTests { this.interceptor.setLabel("FOO"); ((Advised) this.service).addAdvice(this.interceptor); this.service.service(); - assertEquals(2, count); - assertEquals("FOO", this.context.getAttribute(RetryContext.NAME)); + assertThat(count).isEqualTo(2); + assertThat(this.context.getAttribute(RetryContext.NAME)).isEqualTo("FOO"); } @Test @@ -157,13 +152,13 @@ public class RetryOperationsInterceptorTests { ((Advised) this.service).addAdvice(this.interceptor); this.service.service(); - assertEquals(2, count); - assertEquals(3, monitoringTags.entrySet().size()); - assertThat(monitoringTags.get(labelTagName), equalTo(label)); - assertThat(monitoringTags.get(classTagName), - equalTo(RetryOperationsInterceptorTests.Service.class.getSimpleName())); - assertThat(monitoringTags.get(methodTagName), equalTo("service")); - assertTrue(argumentsAsExpected.get()); + assertThat(count).isEqualTo(2); + assertThat(monitoringTags.entrySet()).hasSize(3); + assertThat(monitoringTags.get(labelTagName)).isEqualTo(label); + assertThat(monitoringTags.get(classTagName)) + .isEqualTo(RetryOperationsInterceptorTests.Service.class.getSimpleName()); + assertThat(monitoringTags.get(methodTagName)).isEqualTo("service"); + assertThat(argumentsAsExpected.get()).isTrue(); } @Test @@ -174,7 +169,7 @@ public class RetryOperationsInterceptorTests { this.interceptor.setRecoverer((args, cause) -> null); ((Advised) this.service).addAdvice(this.interceptor); this.service.service(); - assertEquals(1, count); + assertThat(count).isEqualTo(1); } @Test @@ -189,8 +184,8 @@ public class RetryOperationsInterceptorTests { template.setRetryPolicy(new SimpleRetryPolicy(2)); this.interceptor.setRetryOperations(template); this.service.service(); - assertEquals(2, count); - assertEquals(2, list.size()); + assertThat(count).isEqualTo(2); + assertThat(list).hasSize(2); } @Test @@ -204,9 +199,9 @@ public class RetryOperationsInterceptorTests { fail("Expected Exception."); } catch (Exception e) { - assertTrue(e.getMessage().startsWith("Not enough calls")); + assertThat(e.getMessage()).startsWith("Not enough calls"); } - assertEquals(1, count); + assertThat(count).isEqualTo(1); } @Test @@ -214,13 +209,12 @@ public class RetryOperationsInterceptorTests { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( ClassUtils.addResourcePathToPackagePath(getClass(), "retry-transaction-test.xml")); Object object = context.getBean("bean"); - assertNotNull(object); - assertTrue(object instanceof Service); + assertThat(object).isInstanceOf(Service.class); Service bean = (Service) object; bean.doTansactional(); - assertEquals(2, count); + assertThat(count).isEqualTo(2); // Expect 2 separate transactions... - assertEquals(2, transactionCount); + assertThat(transactionCount).isEqualTo(2); context.close(); } @@ -257,8 +251,7 @@ public class RetryOperationsInterceptorTests { fail("IllegalStateException expected"); } catch (IllegalStateException e) { - assertTrue("Exception message should contain MethodInvocation: " + e.getMessage(), - e.getMessage().contains("MethodInvocation")); + assertThat(e.getMessage()).contains("MethodInvocation"); } } diff --git a/src/test/java/org/springframework/retry/interceptor/StatefulRetryOperationsInterceptorTests.java b/src/test/java/org/springframework/retry/interceptor/StatefulRetryOperationsInterceptorTests.java index 91a002a..6bf741c 100644 --- a/src/test/java/org/springframework/retry/interceptor/StatefulRetryOperationsInterceptorTests.java +++ b/src/test/java/org/springframework/retry/interceptor/StatefulRetryOperationsInterceptorTests.java @@ -15,16 +15,6 @@ */ package org.springframework.retry.interceptor; -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.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -32,15 +22,14 @@ import java.util.List; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.springframework.aop.framework.Advised; import org.springframework.aop.framework.ProxyFactory; import org.springframework.aop.target.SingletonTargetSource; import org.springframework.retry.ExhaustedRetryException; -import org.springframework.retry.RecoveryCallback; import org.springframework.retry.RetryCallback; import org.springframework.retry.RetryContext; import org.springframework.retry.RetryOperations; @@ -51,6 +40,15 @@ import org.springframework.retry.policy.SimpleRetryPolicy; import org.springframework.retry.support.DefaultRetryState; import org.springframework.retry.support.RetryTemplate; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + /** * @author Dave Syer * @author Gary Russell @@ -70,7 +68,7 @@ public class StatefulRetryOperationsInterceptorTests { private static int count; - @Before + @BeforeEach public void setUp() { interceptor = new StatefulRetryOperationsInterceptor(); retryTemplate.registerListener(new RetryListenerSupport() { @@ -89,45 +87,26 @@ public class StatefulRetryOperationsInterceptorTests { @Test public void testDefaultInterceptorSunnyDay() { ((Advised) service).addAdvice(interceptor); - try { - service.service("foo"); - fail("Expected Exception."); - } - catch (Exception e) { - String message = e.getMessage(); - assertTrue("Wrong message: " + message, message.startsWith("Not enough calls")); - } - assertEquals(1, count); + assertThatExceptionOfType(Exception.class).isThrownBy(() -> service.service("foo")) + .withMessageStartingWith("Not enough calls"); } @Test public void testDefaultInterceptorWithLabel() { interceptor.setLabel("FOO"); ((Advised) service).addAdvice(interceptor); - try { - service.service("foo"); - fail("Expected Exception."); - } - catch (Exception e) { - String message = e.getMessage(); - assertTrue("Wrong message: " + message, message.startsWith("Not enough calls")); - } - assertEquals(1, count); - assertEquals("FOO", context.getAttribute(RetryContext.NAME)); + assertThatExceptionOfType(Exception.class).isThrownBy(() -> service.service("foo")) + .withMessageStartingWith("Not enough calls"); + assertThat(count).isEqualTo(1); + assertThat(context.getAttribute(RetryContext.NAME)).isEqualTo("FOO"); } @Test public void testDefaultTransformerInterceptorSunnyDay() { ((Advised) transformer).addAdvice(interceptor); - try { - transformer.transform("foo"); - fail("Expected Exception."); - } - catch (Exception e) { - String message = e.getMessage(); - assertTrue("Wrong message: " + message, message.startsWith("Not enough calls")); - } - assertEquals(1, count); + assertThatExceptionOfType(Exception.class).isThrownBy(() -> transformer.transform("foo")) + .withMessageStartingWith("Not enough calls"); + assertThat(count).isEqualTo(1); } @Test @@ -135,15 +114,9 @@ public class StatefulRetryOperationsInterceptorTests { retryTemplate.setRetryPolicy(new AlwaysRetryPolicy()); interceptor.setRetryOperations(retryTemplate); ((Advised) service).addAdvice(interceptor); - try { - service.service("foo"); - fail("Expected Exception."); - } - catch (Exception e) { - String message = e.getMessage(); - assertTrue("Wrong message: " + message, message.startsWith("Not enough calls")); - } - assertEquals(1, count); + assertThatExceptionOfType(Exception.class).isThrownBy(() -> service.service("foo")) + .withMessageStartingWith("Not enough calls"); + assertThat(count).isEqualTo(1); } @Test @@ -156,18 +129,12 @@ public class StatefulRetryOperationsInterceptorTests { }); interceptor.setRetryOperations(retryTemplate); retryTemplate.setRetryPolicy(new SimpleRetryPolicy(2)); - try { - service.service("foo"); - fail("Expected Exception."); - } - catch (Exception e) { - String message = e.getMessage(); - assertTrue("Wrong message: " + message, message.startsWith("Not enough calls")); - } - assertEquals(1, count); + assertThatExceptionOfType(Exception.class).isThrownBy(() -> service.service("foo")) + .withMessageStartingWith("Not enough calls"); + assertThat(count).isEqualTo(1); service.service("foo"); - assertEquals(2, count); - assertEquals(2, list.size()); + assertThat(count).isEqualTo(2); + assertThat(list).hasSize(2); } @Test @@ -175,18 +142,12 @@ public class StatefulRetryOperationsInterceptorTests { ((Advised) transformer).addAdvice(interceptor); interceptor.setRetryOperations(retryTemplate); retryTemplate.setRetryPolicy(new SimpleRetryPolicy(2)); - try { - transformer.transform("foo"); - fail("Expected Exception."); - } - catch (Exception e) { - String message = e.getMessage(); - assertTrue("Wrong message: " + message, message.startsWith("Not enough calls")); - } - assertEquals(1, count); + assertThatExceptionOfType(Exception.class).isThrownBy(() -> transformer.transform("foo")) + .withMessageStartingWith("Not enough calls"); + assertThat(count).isEqualTo(1); Collection result = transformer.transform("foo"); - assertEquals(2, count); - assertEquals(1, result.size()); + assertThat(count).isEqualTo(2); + assertThat(result).hasSize(1); } @Test @@ -194,25 +155,12 @@ public class StatefulRetryOperationsInterceptorTests { ((Advised) service).addAdvice(interceptor); interceptor.setRetryOperations(retryTemplate); retryTemplate.setRetryPolicy(new NeverRetryPolicy()); - try { - service.service("foo"); - fail("Expected Exception."); - } - catch (Exception e) { - String message = e.getMessage(); - assertTrue("Wrong message: " + message, message.startsWith("Not enough calls")); - } - assertEquals(1, count); - try { - service.service("foo"); - fail("Expected ExhaustedRetryException"); - } - catch (ExhaustedRetryException e) { - // expected - String message = e.getMessage(); - assertTrue("Wrong message: " + message, message.startsWith("Retry exhausted")); - } - assertEquals(1, count); + assertThatExceptionOfType(Exception.class).isThrownBy(() -> service.service("foo")) + .withMessageStartingWith("Not enough calls"); + assertThat(count).isEqualTo(1); + assertThatExceptionOfType(ExhaustedRetryException.class).isThrownBy(() -> service.service("foo")) + .withMessageStartingWith("Retry exhausted"); + assertThat(count).isEqualTo(1); } @Test @@ -220,21 +168,15 @@ public class StatefulRetryOperationsInterceptorTests { ((Advised) service).addAdvice(interceptor); interceptor.setRetryOperations(retryTemplate); retryTemplate.setRetryPolicy(new NeverRetryPolicy()); - try { - service.service("foo"); - fail("Expected Exception."); - } - catch (Exception e) { - String message = e.getMessage(); - assertTrue("Wrong message: " + message, message.startsWith("Not enough calls")); - } - assertEquals(1, count); + assertThatExceptionOfType(Exception.class).isThrownBy(() -> service.service("foo")) + .withMessageStartingWith("Not enough calls"); + assertThat(count).isEqualTo(1); interceptor.setRecoverer((data, cause) -> { count++; return null; }); service.service("foo"); - assertEquals(2, count); + assertThat(count).isEqualTo(2); } @SuppressWarnings("unchecked") @@ -265,7 +207,7 @@ public class StatefulRetryOperationsInterceptorTests { this.interceptor.invoke(invocation); ArgumentCaptor captor = ArgumentCaptor.forClass(DefaultRetryState.class); verify(template).execute(any(RetryCallback.class), eq(null), captor.capture()); - assertEquals("bar", captor.getValue().getKey()); + assertThat(captor.getValue().getKey()).isEqualTo("bar"); } @Test @@ -273,22 +215,16 @@ public class StatefulRetryOperationsInterceptorTests { ((Advised) transformer).addAdvice(interceptor); interceptor.setRetryOperations(retryTemplate); retryTemplate.setRetryPolicy(new NeverRetryPolicy()); - try { - transformer.transform("foo"); - fail("Expected Exception."); - } - catch (Exception e) { - String message = e.getMessage(); - assertTrue("Wrong message: " + message, message.startsWith("Not enough calls")); - } - assertEquals(1, count); + assertThatExceptionOfType(Exception.class).isThrownBy(() -> transformer.transform("foo")) + .withMessageStartingWith("Not enough calls"); + assertThat(count).isEqualTo(1); interceptor.setRecoverer((data, cause) -> { count++; return Collections.singleton((String) data[0]); }); Collection result = transformer.transform("foo"); - assertEquals(2, count); - assertEquals(1, result.size()); + assertThat(count).isEqualTo(2); + assertThat(result.size()).isEqualTo(1); } public static interface Service { diff --git a/src/test/java/org/springframework/retry/listener/MethodInvocationRetryListenerSupportTests.java b/src/test/java/org/springframework/retry/listener/MethodInvocationRetryListenerSupportTests.java index 18e49aa..21e1168 100644 --- a/src/test/java/org/springframework/retry/listener/MethodInvocationRetryListenerSupportTests.java +++ b/src/test/java/org/springframework/retry/listener/MethodInvocationRetryListenerSupportTests.java @@ -18,15 +18,15 @@ package org.springframework.retry.listener; import java.util.concurrent.atomic.AtomicInteger; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.retry.RetryCallback; import org.springframework.retry.RetryContext; import org.springframework.retry.interceptor.MethodInvocationRetryCallback; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatNoException; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.mock; public class MethodInvocationRetryListenerSupportTests { @@ -34,12 +34,7 @@ public class MethodInvocationRetryListenerSupportTests { @Test public void testClose() { MethodInvocationRetryListenerSupport support = new MethodInvocationRetryListenerSupport(); - try { - support.close(null, null, null); - } - catch (Exception e) { - fail("Unexpected exception"); - } + assertThatNoException().isThrownBy(() -> support.close(null, null, null)); } @Test @@ -55,7 +50,7 @@ public class MethodInvocationRetryListenerSupportTests { RetryContext context = mock(RetryContext.class); support.close(context, mockMethodInvocationRetryCallback(), null); - assertEquals(1, callsOnDoCloseMethod.get()); + assertThat(callsOnDoCloseMethod.get()).isEqualTo(1); } @Test @@ -72,7 +67,7 @@ public class MethodInvocationRetryListenerSupportTests { RetryCallback callback = mock(RetryCallback.class); support.close(context, callback, null); - assertEquals(0, callsOnDoCloseMethod.get()); + assertThat(callsOnDoCloseMethod.get()).isEqualTo(0); } @Test @@ -99,13 +94,13 @@ public class MethodInvocationRetryListenerSupportTests { RetryContext context = mock(RetryContext.class); support.onError(context, mockMethodInvocationRetryCallback(), null); - assertEquals(1, callsOnDoOnErrorMethod.get()); + assertThat(callsOnDoOnErrorMethod.get()).isEqualTo(1); } @Test public void testOpen() { MethodInvocationRetryListenerSupport support = new MethodInvocationRetryListenerSupport(); - assertTrue(support.open(null, null)); + assertThat(support.open(null, null)).isTrue(); } @Test @@ -121,8 +116,8 @@ public class MethodInvocationRetryListenerSupportTests { }; RetryContext context = mock(RetryContext.class); - assertTrue(support.open(context, mockMethodInvocationRetryCallback())); - assertEquals(1, callsOnDoOpenMethod.get()); + assertThat(support.open(context, mockMethodInvocationRetryCallback())).isTrue(); + assertThat(callsOnDoOpenMethod.get()).isEqualTo(1); } private MethodInvocationRetryCallback mockMethodInvocationRetryCallback() { diff --git a/src/test/java/org/springframework/retry/listener/RetryListenerSupportTests.java b/src/test/java/org/springframework/retry/listener/RetryListenerSupportTests.java index ce03f7e..b583563 100644 --- a/src/test/java/org/springframework/retry/listener/RetryListenerSupportTests.java +++ b/src/test/java/org/springframework/retry/listener/RetryListenerSupportTests.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,39 +16,29 @@ package org.springframework.retry.listener; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatNoException; public class RetryListenerSupportTests { @Test public void testClose() { RetryListenerSupport support = new RetryListenerSupport(); - try { - support.close(null, null, null); - } - catch (Exception e) { - fail("Unexpected exception"); - } + assertThatNoException().isThrownBy(() -> support.close(null, null, null)); } @Test public void testOnError() { RetryListenerSupport support = new RetryListenerSupport(); - try { - support.onError(null, null, null); - } - catch (Exception e) { - fail("Unexpected exception"); - } + assertThatNoException().isThrownBy(() -> support.onError(null, null, null)); } @Test public void testOpen() { RetryListenerSupport support = new RetryListenerSupport(); - assertTrue(support.open(null, null)); + assertThat(support.open(null, null)).isTrue(); } } diff --git a/src/test/java/org/springframework/retry/listener/RetryListenerTests.java b/src/test/java/org/springframework/retry/listener/RetryListenerTests.java index 09bd174..3446e8b 100644 --- a/src/test/java/org/springframework/retry/listener/RetryListenerTests.java +++ b/src/test/java/org/springframework/retry/listener/RetryListenerTests.java @@ -16,14 +16,11 @@ package org.springframework.retry.listener; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; - import java.util.ArrayList; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; + import org.springframework.retry.RetryCallback; import org.springframework.retry.RetryContext; import org.springframework.retry.RetryListener; @@ -31,6 +28,11 @@ import org.springframework.retry.TerminatedRetryException; import org.springframework.retry.policy.NeverRetryPolicy; import org.springframework.retry.support.RetryTemplate; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; + public class RetryListenerTests { RetryTemplate template = new RetryTemplate(); @@ -55,9 +57,9 @@ public class RetryListenerTests { } } }); template.execute(context -> null); - assertEquals(2, count); - assertEquals(2, list.size()); - assertEquals("1:1", list.get(0)); + assertThat(count).isEqualTo(2); + assertThat(list).hasSize(2); + assertThat(list.get(0)).isEqualTo("1:1"); } @Test @@ -78,9 +80,9 @@ public class RetryListenerTests { catch (TerminatedRetryException e) { // expected } - assertEquals(0, count); - assertEquals(1, list.size()); - assertEquals("1", list.get(0)); + assertThat(count).isEqualTo(0); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isEqualTo("1"); } @Test @@ -99,10 +101,10 @@ public class RetryListenerTests { } } }); template.execute(context -> null); - assertEquals(2, count); - assertEquals(2, list.size()); + assertThat(count).isEqualTo(2); + assertThat(list).hasSize(2); // interceptors are called in reverse order on close... - assertEquals("2:1", list.get(0)); + assertThat(list.get(0)).isEqualTo("2:1"); } @Test @@ -119,21 +121,15 @@ public class RetryListenerTests { list.add("2"); } } }); - try { - template.execute(context -> { - count++; - throw new IllegalStateException("foo"); - }); - fail("Expected IllegalStateException"); - } - catch (IllegalStateException e) { - assertEquals("foo", e.getMessage()); - } + assertThatIllegalStateException().isThrownBy(() -> template.execute(context -> { + count++; + throw new IllegalStateException("foo"); + })).withMessage("foo"); // never retry so callback is executed once - assertEquals(1, count); - assertEquals(2, list.size()); + assertThat(count).isEqualTo(1); + assertThat(list).hasSize(2); // interceptors are called in reverse order on error... - assertEquals("2", list.get(0)); + assertThat(list.get(0)).isEqualTo("2"); } @@ -152,11 +148,11 @@ public class RetryListenerTests { throw new RuntimeException("Retry!"); return null; }); - assertEquals(2, count); + assertThat(count).isEqualTo(2); // The close interceptor was only called once: - assertEquals(1, list.size()); + assertThat(list).hasSize(1); // We succeeded on the second try: - assertEquals("2", list.get(0)); + assertThat(list.get(0)).isEqualTo("2"); } } diff --git a/src/test/java/org/springframework/retry/policy/AlwaysRetryPolicyTests.java b/src/test/java/org/springframework/retry/policy/AlwaysRetryPolicyTests.java index e9f3255..eef9213 100644 --- a/src/test/java/org/springframework/retry/policy/AlwaysRetryPolicyTests.java +++ b/src/test/java/org/springframework/retry/policy/AlwaysRetryPolicyTests.java @@ -16,39 +16,36 @@ package org.springframework.retry.policy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; -import org.junit.Test; import org.springframework.retry.RetryContext; +import static org.assertj.core.api.Assertions.assertThat; + public class AlwaysRetryPolicyTests { @Test public void testSimpleOperations() { AlwaysRetryPolicy policy = new AlwaysRetryPolicy(); RetryContext context = policy.open(null); - assertNotNull(context); - assertTrue(policy.canRetry(context)); + assertThat(context).isNotNull(); + assertThat(policy.canRetry(context)).isTrue(); policy.registerThrowable(context, null); - assertTrue(policy.canRetry(context)); + assertThat(policy.canRetry(context)).isTrue(); policy.close(context); - assertTrue(policy.canRetry(context)); + assertThat(policy.canRetry(context)).isTrue(); } @Test public void testRetryCount() { AlwaysRetryPolicy policy = new AlwaysRetryPolicy(); RetryContext context = policy.open(null); - assertNotNull(context); + assertThat(context).isNotNull(); policy.registerThrowable(context, null); - assertEquals(0, context.getRetryCount()); + assertThat(context.getRetryCount()).isEqualTo(0); policy.registerThrowable(context, new RuntimeException("foo")); - assertEquals(1, context.getRetryCount()); - assertEquals("foo", context.getLastThrowable().getMessage()); + assertThat(context.getRetryCount()).isEqualTo(1); + assertThat(context.getLastThrowable().getMessage()).isEqualTo("foo"); } @Test @@ -56,8 +53,8 @@ public class AlwaysRetryPolicyTests { AlwaysRetryPolicy policy = new AlwaysRetryPolicy(); RetryContext context = policy.open(null); RetryContext child = policy.open(context); - assertNotSame(child, context); - assertSame(context, child.getParent()); + assertThat(context).isNotSameAs(child); + assertThat(child.getParent()).isSameAs(context); } } diff --git a/src/test/java/org/springframework/retry/policy/CircuitBreakerRetryTemplateTests.java b/src/test/java/org/springframework/retry/policy/CircuitBreakerRetryTemplateTests.java index 4aac8ae..f7bcfe3 100644 --- a/src/test/java/org/springframework/retry/policy/CircuitBreakerRetryTemplateTests.java +++ b/src/test/java/org/springframework/retry/policy/CircuitBreakerRetryTemplateTests.java @@ -16,12 +16,9 @@ package org.springframework.retry.policy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.junit.Before; -import org.junit.Test; import org.springframework.classify.BinaryExceptionClassifier; import org.springframework.retry.RecoveryCallback; import org.springframework.retry.RetryCallback; @@ -30,6 +27,9 @@ import org.springframework.retry.policy.CircuitBreakerRetryPolicy.CircuitBreaker import org.springframework.retry.support.DefaultRetryState; import org.springframework.retry.support.RetryTemplate; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + /** * @author Dave Syer * @@ -48,7 +48,7 @@ public class CircuitBreakerRetryTemplateTests { private DefaultRetryState state; - @Before + @BeforeEach public void init() { this.callback = new MockRetryCallback(); this.recovery = context -> RECOVERED; @@ -62,33 +62,26 @@ public class CircuitBreakerRetryTemplateTests { public void testCircuitOpenWhenNotRetryable() throws Throwable { this.retryTemplate.setRetryPolicy(new CircuitBreakerRetryPolicy(new NeverRetryPolicy())); Object result = this.retryTemplate.execute(this.callback, this.recovery, this.state); - assertEquals(1, this.callback.getAttempts()); - assertEquals(RECOVERED, result); + assertThat(this.callback.getAttempts()).isEqualTo(1); + assertThat(result).isEqualTo(RECOVERED); result = this.retryTemplate.execute(this.callback, this.recovery, this.state); // circuit is now open so no more attempts - assertEquals(1, this.callback.getAttempts()); - assertEquals(RECOVERED, result); + assertThat(this.callback.getAttempts()).isEqualTo(1); + assertThat(result).isEqualTo(RECOVERED); } @Test public void testCircuitOpenWithNoRecovery() { this.retryTemplate.setRetryPolicy(new CircuitBreakerRetryPolicy(new NeverRetryPolicy())); this.retryTemplate.setThrowLastExceptionOnExhausted(true); - try { - this.retryTemplate.execute(this.callback, this.state); - } - catch (Exception e) { - assertEquals(this.callback.exceptionToThrow, e); - assertEquals(1, this.callback.getAttempts()); - } - try { - this.retryTemplate.execute(this.callback, this.state); - } - catch (Exception e) { - assertEquals(this.callback.exceptionToThrow, e); - // circuit is now open so no more attempts - assertEquals(1, this.callback.getAttempts()); - } + assertThatExceptionOfType(Exception.class) + .isThrownBy(() -> this.retryTemplate.execute(this.callback, this.state)) + .isEqualTo(this.callback.exceptionToThrow); + assertThat(this.callback.getAttempts()).isEqualTo(1); + assertThatExceptionOfType(Exception.class) + .isThrownBy(() -> this.retryTemplate.execute(this.callback, this.state)) + .isEqualTo(this.callback.exceptionToThrow); + assertThat(this.callback.getAttempts()).isEqualTo(1); } @Test @@ -96,15 +89,15 @@ public class CircuitBreakerRetryTemplateTests { this.retryTemplate.setRetryPolicy(new CircuitBreakerRetryPolicy(new SimpleRetryPolicy())); this.callback.setAttemptsBeforeSuccess(10); Object result = this.retryTemplate.execute(this.callback, this.recovery, this.state); - assertEquals(1, this.callback.getAttempts()); - assertEquals(RECOVERED, result); - assertFalse(this.callback.status.isOpen()); + assertThat(this.callback.getAttempts()).isEqualTo(1); + assertThat(result).isEqualTo(RECOVERED); + assertThat(this.callback.status.isOpen()).isFalse(); result = this.retryTemplate.execute(this.callback, this.recovery, this.state); result = this.retryTemplate.execute(this.callback, this.recovery, this.state); // circuit is now open so no more attempts - assertEquals(3, this.callback.getAttempts()); - assertEquals(RECOVERED, result); - assertTrue(this.callback.status.isOpen()); + assertThat(this.callback.getAttempts()).isEqualTo(3); + assertThat(result).isEqualTo(RECOVERED); + assertThat(this.callback.status.isOpen()).isTrue(); } @Test @@ -114,15 +107,15 @@ public class CircuitBreakerRetryTemplateTests { retryPolicy.setOpenTimeout(100); this.callback.setAttemptsBeforeSuccess(10); Object result = this.retryTemplate.execute(this.callback, this.recovery, this.state); - assertEquals(1, this.callback.getAttempts()); - assertEquals(RECOVERED, result); - assertFalse(this.callback.status.isOpen()); + assertThat(this.callback.getAttempts()).isEqualTo(1); + assertThat(result).isEqualTo(RECOVERED); + assertThat(this.callback.status.isOpen()).isFalse(); Thread.sleep(200L); result = this.retryTemplate.execute(this.callback, this.recovery, this.state); // circuit is reset after sleep window - assertEquals(2, this.callback.getAttempts()); - assertEquals(RECOVERED, result); - assertFalse(this.callback.status.isOpen()); + assertThat(this.callback.getAttempts()).isEqualTo(2); + assertThat(result).isEqualTo(RECOVERED); + assertThat(this.callback.status.isOpen()).isFalse(); } @Test @@ -131,15 +124,15 @@ public class CircuitBreakerRetryTemplateTests { this.retryTemplate.setRetryPolicy(retryPolicy); retryPolicy.setResetTimeout(100); Object result = this.retryTemplate.execute(this.callback, this.recovery, this.state); - assertEquals(1, this.callback.getAttempts()); - assertEquals(RECOVERED, result); - assertTrue(this.callback.status.isOpen()); + assertThat(this.callback.getAttempts()).isEqualTo(1); + assertThat(result).isEqualTo(RECOVERED); + assertThat(this.callback.status.isOpen()).isTrue(); // Sleep longer than the timeout Thread.sleep(200L); - assertFalse(this.callback.status.isOpen()); + assertThat(this.callback.status.isOpen()).isFalse(); result = this.retryTemplate.execute(this.callback, this.recovery, this.state); // circuit closed again now - assertEquals(RESULT, result); + assertThat(result).isEqualTo(RESULT); } @Test @@ -148,9 +141,9 @@ public class CircuitBreakerRetryTemplateTests { this.retryTemplate.setRetryPolicy(new CircuitBreakerRetryPolicy(mockNeverRetryPolicy)); this.callback.setAttemptsBeforeSuccess(10); Object result = this.retryTemplate.execute(this.callback, this.recovery, this.state); - assertEquals(RECOVERED, result); + assertThat(result).isEqualTo(RECOVERED); result = this.retryTemplate.execute(this.callback, this.recovery, this.state); - assertEquals(RECOVERED, result); + assertThat(result).isEqualTo(RECOVERED); } protected static class MockRetryCallback implements RetryCallback { diff --git a/src/test/java/org/springframework/retry/policy/CompositeRetryPolicyTests.java b/src/test/java/org/springframework/retry/policy/CompositeRetryPolicyTests.java index ec894d8..ed60bd1 100644 --- a/src/test/java/org/springframework/retry/policy/CompositeRetryPolicyTests.java +++ b/src/test/java/org/springframework/retry/policy/CompositeRetryPolicyTests.java @@ -16,29 +16,25 @@ package org.springframework.retry.policy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.util.ArrayList; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; + import org.springframework.retry.RetryContext; import org.springframework.retry.RetryPolicy; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + public class CompositeRetryPolicyTests { @Test public void testEmptyPolicies() { CompositeRetryPolicy policy = new CompositeRetryPolicy(); RetryContext context = policy.open(null); - assertNotNull(context); - assertTrue(policy.canRetry(context)); + assertThat(context).isNotNull(); + assertThat(policy.canRetry(context)).isTrue(); } @Test @@ -46,8 +42,8 @@ public class CompositeRetryPolicyTests { CompositeRetryPolicy policy = new CompositeRetryPolicy(); policy.setPolicies(new RetryPolicy[] { new MockRetryPolicySupport(), new MockRetryPolicySupport() }); RetryContext context = policy.open(null); - assertNotNull(context); - assertTrue(policy.canRetry(context)); + assertThat(context).isNotNull(); + assertThat(policy.canRetry(context)).isTrue(); } @SuppressWarnings("serial") @@ -60,8 +56,8 @@ public class CompositeRetryPolicyTests { } } }); RetryContext context = policy.open(null); - assertNotNull(context); - assertFalse(policy.canRetry(context)); + assertThat(context).isNotNull(); + assertThat(policy.canRetry(context)).isFalse(); } @SuppressWarnings("serial") @@ -80,10 +76,10 @@ public class CompositeRetryPolicyTests { } } }); RetryContext context = policy.open(null); - assertNotNull(context); - assertTrue(policy.canRetry(context)); + assertThat(context).isNotNull(); + assertThat(policy.canRetry(context)).isTrue(); policy.registerThrowable(context, null); - assertFalse("Should be still able to retry", policy.canRetry(context)); + assertThat(policy.canRetry(context)).describedAs("Should be still able to retry").isFalse(); } @SuppressWarnings("serial") @@ -101,9 +97,9 @@ public class CompositeRetryPolicyTests { } } }); RetryContext context = policy.open(null); - assertNotNull(context); + assertThat(context).isNotNull(); policy.close(context); - assertEquals(2, list.size()); + assertThat(list).hasSize(2); } @SuppressWarnings("serial") @@ -122,15 +118,9 @@ public class CompositeRetryPolicyTests { } } }); RetryContext context = policy.open(null); - assertNotNull(context); - try { - policy.close(context); - fail("Expected RuntimeException"); - } - catch (RuntimeException e) { - assertEquals("Pah!", e.getMessage()); - } - assertEquals(2, list.size()); + assertThat(context).isNotNull(); + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> policy.close(context)).withMessage("Pah!"); + assertThat(list).hasSize(2); } @Test @@ -138,12 +128,12 @@ public class CompositeRetryPolicyTests { CompositeRetryPolicy policy = new CompositeRetryPolicy(); policy.setPolicies(new RetryPolicy[] { new MockRetryPolicySupport(), new MockRetryPolicySupport() }); RetryContext context = policy.open(null); - assertNotNull(context); + assertThat(context).isNotNull(); policy.registerThrowable(context, null); - assertEquals(0, context.getRetryCount()); + assertThat(context.getRetryCount()).isEqualTo(0); policy.registerThrowable(context, new RuntimeException("foo")); - assertEquals(1, context.getRetryCount()); - assertEquals("foo", context.getLastThrowable().getMessage()); + assertThat(context.getRetryCount()).isEqualTo(1); + assertThat(context.getLastThrowable().getMessage()).isEqualTo("foo"); } @Test @@ -151,8 +141,8 @@ public class CompositeRetryPolicyTests { CompositeRetryPolicy policy = new CompositeRetryPolicy(); RetryContext context = policy.open(null); RetryContext child = policy.open(context); - assertNotSame(child, context); - assertSame(context, child.getParent()); + assertThat(context).isNotSameAs(child); + assertThat(child.getParent()).isSameAs(context); } @SuppressWarnings("serial") @@ -166,8 +156,8 @@ public class CompositeRetryPolicyTests { } }, new MockRetryPolicySupport() }); RetryContext context = policy.open(null); - assertNotNull(context); - assertTrue(policy.canRetry(context)); + assertThat(context).isNotNull(); + assertThat(policy.canRetry(context)).isTrue(); } } diff --git a/src/test/java/org/springframework/retry/policy/ExceptionClassifierRetryPolicyTests.java b/src/test/java/org/springframework/retry/policy/ExceptionClassifierRetryPolicyTests.java index ce70edc..d14b506 100644 --- a/src/test/java/org/springframework/retry/policy/ExceptionClassifierRetryPolicyTests.java +++ b/src/test/java/org/springframework/retry/policy/ExceptionClassifierRetryPolicyTests.java @@ -16,21 +16,18 @@ package org.springframework.retry.policy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - import java.util.Collections; import java.util.HashMap; -import org.junit.Test; -import org.springframework.classify.Classifier; +import org.junit.jupiter.api.Test; + import org.springframework.retry.RetryContext; import org.springframework.retry.RetryPolicy; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class ExceptionClassifierRetryPolicyTests { private final ExceptionClassifierRetryPolicy policy = new ExceptionClassifierRetryPolicy(); @@ -38,7 +35,7 @@ public class ExceptionClassifierRetryPolicyTests { @Test public void testDefaultPolicies() { RetryContext context = policy.open(null); - assertNotNull(context); + assertThat(context).isNotNull(); } @Test @@ -46,7 +43,7 @@ public class ExceptionClassifierRetryPolicyTests { policy.setPolicyMap(Collections., RetryPolicy>singletonMap(Exception.class, new MockRetryPolicySupport())); RetryContext context = policy.open(null); - assertNotNull(context); + assertThat(context).isNotNull(); assertTrue(policy.canRetry(context)); } @@ -54,7 +51,7 @@ public class ExceptionClassifierRetryPolicyTests { public void testNullPolicies() { policy.setPolicyMap(new HashMap<>()); RetryContext context = policy.open(null); - assertNotNull(context); + assertThat(context).isNotNull(); } @Test @@ -63,7 +60,7 @@ public class ExceptionClassifierRetryPolicyTests { new NeverRetryPolicy())); RetryContext context = policy.open(null); - assertNotNull(context); + assertThat(context).isNotNull(); assertTrue(policy.canRetry(context)); } @@ -73,7 +70,7 @@ public class ExceptionClassifierRetryPolicyTests { public void testClassifierOperates() { RetryContext context = policy.open(null); - assertNotNull(context); + assertThat(context).isNotNull(); assertTrue(policy.canRetry(context)); policy.registerThrowable(context, new IllegalArgumentException()); @@ -115,24 +112,24 @@ public class ExceptionClassifierRetryPolicyTests { // The mapped (child) policy hasn't been used yet, so if we close now // we don't incur the possible expense of creating the child context. policy.close(context); - assertEquals(0, count); // not classified yet + assertThat(count).isEqualTo(0); // not classified yet // This forces a child context to be created and the child policy is // then closed policy.registerThrowable(context, new IllegalStateException()); policy.close(context); - assertEquals(1, count); // now classified + assertThat(count).isEqualTo(1); // now classified } @Test public void testRetryCount() { ExceptionClassifierRetryPolicy policy = new ExceptionClassifierRetryPolicy(); RetryContext context = policy.open(null); - assertNotNull(context); + assertThat(context).isNotNull(); policy.registerThrowable(context, null); - assertEquals(0, context.getRetryCount()); + assertThat(context.getRetryCount()).isEqualTo(0); policy.registerThrowable(context, new RuntimeException("foo")); - assertEquals(1, context.getRetryCount()); - assertEquals("foo", context.getLastThrowable().getMessage()); + assertThat(context.getRetryCount()).isEqualTo(1); + assertThat(context.getLastThrowable().getMessage()).isEqualTo("foo"); } @Test @@ -140,8 +137,8 @@ public class ExceptionClassifierRetryPolicyTests { ExceptionClassifierRetryPolicy policy = new ExceptionClassifierRetryPolicy(); RetryContext context = policy.open(null); RetryContext child = policy.open(context); - assertNotSame(child, context); - assertSame(context, child.getParent()); + assertThat(context).isNotSameAs(child); + assertThat(child.getParent()).isSameAs(context); } } diff --git a/src/test/java/org/springframework/retry/policy/FatalExceptionRetryPolicyTests.java b/src/test/java/org/springframework/retry/policy/FatalExceptionRetryPolicyTests.java index 51d366f..895b47c 100644 --- a/src/test/java/org/springframework/retry/policy/FatalExceptionRetryPolicyTests.java +++ b/src/test/java/org/springframework/retry/policy/FatalExceptionRetryPolicyTests.java @@ -16,19 +16,22 @@ package org.springframework.retry.policy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - import java.util.HashMap; import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.jupiter.api.Test; -import org.junit.Test; import org.springframework.retry.RecoveryCallback; import org.springframework.retry.RetryCallback; import org.springframework.retry.RetryContext; import org.springframework.retry.support.DefaultRetryState; import org.springframework.retry.support.RetryTemplate; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatNoException; + public class FatalExceptionRetryPolicyTests { @Test @@ -48,17 +51,11 @@ public class FatalExceptionRetryPolicyTests { retryTemplate.setRetryPolicy(policy); RecoveryCallback recoveryCallback = context -> "bar"; - Object result = null; - try { - result = retryTemplate.execute(callback, recoveryCallback); - } - catch (IllegalArgumentException e) { - // We should swallow the exception when recovery is possible - fail("Did not expect IllegalArgumentException"); - } + AtomicReference result = new AtomicReference<>(); + assertThatNoException().isThrownBy(() -> result.set(retryTemplate.execute(callback, recoveryCallback))); // Callback is called once: the recovery path should also be called - assertEquals(1, callback.attempts); - assertEquals("bar", result); + assertThat(callback.attempts).isEqualTo(1); + assertThat(result.get()).isEqualTo("bar"); } @Test @@ -78,18 +75,12 @@ public class FatalExceptionRetryPolicyTests { RecoveryCallback recoveryCallback = context -> "bar"; Object result = null; - try { - retryTemplate.execute(callback, recoveryCallback, new DefaultRetryState("foo")); - fail("Expected IllegalArgumentException"); - } - catch (IllegalArgumentException e) { - // If stateful we have to always rethrow. Clients who want special - // cases have to implement them in the callback - } + assertThatIllegalArgumentException() + .isThrownBy(() -> retryTemplate.execute(callback, recoveryCallback, new DefaultRetryState("foo"))); result = retryTemplate.execute(callback, recoveryCallback, new DefaultRetryState("foo")); // Callback is called once: the recovery path should also be called - assertEquals(1, callback.attempts); - assertEquals("bar", result); + assertThat(callback.attempts).isEqualTo(1); + assertThat(result).isEqualTo("bar"); } private static class MockRetryCallback implements RetryCallback { diff --git a/src/test/java/org/springframework/retry/policy/MapRetryContextCacheTests.java b/src/test/java/org/springframework/retry/policy/MapRetryContextCacheTests.java index 8f9272b..70ba712 100644 --- a/src/test/java/org/springframework/retry/policy/MapRetryContextCacheTests.java +++ b/src/test/java/org/springframework/retry/policy/MapRetryContextCacheTests.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,13 +16,13 @@ package org.springframework.retry.policy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; -import org.junit.Test; import org.springframework.retry.context.RetryContextSupport; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + public class MapRetryContextCacheTests { MapRetryContextCache cache = new MapRetryContextCache(); @@ -31,25 +31,26 @@ public class MapRetryContextCacheTests { public void testPut() { RetryContextSupport context = new RetryContextSupport(null); cache.put("foo", context); - assertEquals(context, cache.get("foo")); + assertThat(cache.get("foo")).isEqualTo(context); } - @Test(expected = RetryCacheCapacityExceededException.class) + @Test public void testPutOverLimit() { RetryContextSupport context = new RetryContextSupport(null); cache.setCapacity(1); cache.put("foo", context); - cache.put("foo", context); + assertThatExceptionOfType(RetryCacheCapacityExceededException.class) + .isThrownBy(() -> cache.put("foo", context)); } @Test public void testRemove() { - assertFalse(cache.containsKey("foo")); + assertThat(cache.containsKey("foo")).isFalse(); RetryContextSupport context = new RetryContextSupport(null); cache.put("foo", context); - assertTrue(cache.containsKey("foo")); + assertThat(cache.containsKey("foo")).isTrue(); cache.remove("foo"); - assertFalse(cache.containsKey("foo")); + assertThat(cache.containsKey("foo")).isFalse(); } } diff --git a/src/test/java/org/springframework/retry/policy/NeverRetryPolicyTests.java b/src/test/java/org/springframework/retry/policy/NeverRetryPolicyTests.java index d5c1590..9cb4421 100644 --- a/src/test/java/org/springframework/retry/policy/NeverRetryPolicyTests.java +++ b/src/test/java/org/springframework/retry/policy/NeverRetryPolicyTests.java @@ -16,42 +16,38 @@ package org.springframework.retry.policy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; -import org.junit.Test; import org.springframework.retry.RetryContext; +import static org.assertj.core.api.Assertions.assertThat; + public class NeverRetryPolicyTests { @Test public void testSimpleOperations() { NeverRetryPolicy policy = new NeverRetryPolicy(); RetryContext context = policy.open(null); - assertNotNull(context); + assertThat(context).isNotNull(); // We can retry until the first exception is registered... - assertTrue(policy.canRetry(context)); - assertTrue(policy.canRetry(context)); + assertThat(policy.canRetry(context)).isTrue(); + assertThat(policy.canRetry(context)).isTrue(); policy.registerThrowable(context, null); - assertFalse(policy.canRetry(context)); + assertThat(policy.canRetry(context)).isFalse(); policy.close(context); - assertFalse(policy.canRetry(context)); + assertThat(policy.canRetry(context)).isFalse(); } @Test public void testRetryCount() { NeverRetryPolicy policy = new NeverRetryPolicy(); RetryContext context = policy.open(null); - assertNotNull(context); + assertThat(context).isNotNull(); policy.registerThrowable(context, null); - assertEquals(0, context.getRetryCount()); + assertThat(context.getRetryCount()).isEqualTo(0); policy.registerThrowable(context, new RuntimeException("foo")); - assertEquals(1, context.getRetryCount()); - assertEquals("foo", context.getLastThrowable().getMessage()); + assertThat(context.getRetryCount()).isEqualTo(1); + assertThat(context.getLastThrowable().getMessage()).isEqualTo("foo"); } @Test @@ -59,8 +55,8 @@ public class NeverRetryPolicyTests { NeverRetryPolicy policy = new NeverRetryPolicy(); RetryContext context = policy.open(null); RetryContext child = policy.open(context); - assertNotSame(child, context); - assertSame(context, child.getParent()); + assertThat(context).isNotSameAs(child); + assertThat(child.getParent()).isSameAs(context); } } diff --git a/src/test/java/org/springframework/retry/policy/RetryContextSerializationTests.java b/src/test/java/org/springframework/retry/policy/RetryContextSerializationTests.java index a5aa255..ddf5d58 100644 --- a/src/test/java/org/springframework/retry/policy/RetryContextSerializationTests.java +++ b/src/test/java/org/springframework/retry/policy/RetryContextSerializationTests.java @@ -23,10 +23,8 @@ import java.util.regex.Pattern; 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.MethodSource; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.config.BeanDefinition; @@ -39,21 +37,18 @@ import org.springframework.retry.RetryPolicy; import org.springframework.util.ClassUtils; import org.springframework.util.SerializationUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer + * @author Gary Russell * */ -@RunWith(Parameterized.class) public class RetryContextSerializationTests { private static final Log logger = LogFactory.getLog(RetryContextSerializationTests.class); - private final RetryPolicy policy; - - @Parameters(name = "{index}: {0}") + @SuppressWarnings("deprecation") public static List policies() { List result = new ArrayList<>(); ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true); @@ -76,23 +71,25 @@ public class RetryContextSerializationTests { return result; } - public RetryContextSerializationTests(RetryPolicy policy) { - this.policy = policy; - } - - @Test - public void testSerializationCycleForContext() { + @SuppressWarnings("deprecation") + @ParameterizedTest + @MethodSource("policies") + public void testSerializationCycleForContext(RetryPolicy policy) { RetryContext context = policy.open(null); - assertEquals(0, context.getRetryCount()); + assertThat(context.getRetryCount()).isEqualTo(0); policy.registerThrowable(context, new RuntimeException()); - assertEquals(1, context.getRetryCount()); - assertEquals(1, - ((RetryContext) SerializationUtils.deserialize(SerializationUtils.serialize(context))).getRetryCount()); + assertThat(context.getRetryCount()).isEqualTo(1); + assertThat( + ((RetryContext) SerializationUtils.deserialize(SerializationUtils.serialize(context))).getRetryCount()) + .isEqualTo(1); } - @Test - public void testSerializationCycleForPolicy() { - assertTrue(SerializationUtils.deserialize(SerializationUtils.serialize(policy)) instanceof RetryPolicy); + @ParameterizedTest + @MethodSource("policies") + @SuppressWarnings("deprecation") + public void testSerializationCycleForPolicy(RetryPolicy policy) { + assertThat(SerializationUtils.deserialize(SerializationUtils.serialize(policy)) instanceof RetryPolicy) + .isTrue(); } } diff --git a/src/test/java/org/springframework/retry/policy/SimpleRetryPolicyTests.java b/src/test/java/org/springframework/retry/policy/SimpleRetryPolicyTests.java index e59b4de..c1592a1 100644 --- a/src/test/java/org/springframework/retry/policy/SimpleRetryPolicyTests.java +++ b/src/test/java/org/springframework/retry/policy/SimpleRetryPolicyTests.java @@ -16,28 +16,23 @@ package org.springframework.retry.policy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - 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.retry.RetryContext; +import static org.assertj.core.api.Assertions.assertThat; + public class SimpleRetryPolicyTests { @Test public void testCanRetryIfNoException() { SimpleRetryPolicy policy = new SimpleRetryPolicy(); RetryContext context = policy.open(null); - assertTrue(policy.canRetry(context)); + assertThat(policy.canRetry(context)).isTrue(); } @Test @@ -50,7 +45,7 @@ public class SimpleRetryPolicyTests { // ...so we can't retry this one... policy.registerThrowable(context, new IllegalStateException()); - assertFalse(policy.canRetry(context)); + assertThat(policy.canRetry(context)).isFalse(); } @Test @@ -64,21 +59,21 @@ public class SimpleRetryPolicyTests { // ...so we can't retry this one... policy.registerThrowable(context, new IllegalStateException()); - assertFalse(policy.canRetry(context)); + assertThat(policy.canRetry(context)).isFalse(); // ...and we can retry this one... policy.registerThrowable(context, new IllegalArgumentException()); - assertTrue(policy.canRetry(context)); + assertThat(policy.canRetry(context)).isTrue(); } @Test public void testRetryLimitInitialState() { SimpleRetryPolicy policy = new SimpleRetryPolicy(); RetryContext context = policy.open(null); - assertTrue(policy.canRetry(context)); + assertThat(policy.canRetry(context)).isTrue(); policy.setMaxAttempts(0); context = policy.open(null); - assertFalse(policy.canRetry(context)); + assertThat(policy.canRetry(context)).isFalse(); } @Test @@ -86,23 +81,23 @@ public class SimpleRetryPolicyTests { SimpleRetryPolicy policy = new SimpleRetryPolicy(); RetryContext context = policy.open(null); policy.setMaxAttempts(2); - assertTrue(policy.canRetry(context)); + assertThat(policy.canRetry(context)).isTrue(); policy.registerThrowable(context, new Exception()); - assertTrue(policy.canRetry(context)); + assertThat(policy.canRetry(context)).isTrue(); policy.registerThrowable(context, new Exception()); - assertFalse(policy.canRetry(context)); + assertThat(policy.canRetry(context)).isFalse(); } @Test public void testRetryCount() { SimpleRetryPolicy policy = new SimpleRetryPolicy(); RetryContext context = policy.open(null); - assertNotNull(context); + assertThat(context).isNotNull(); policy.registerThrowable(context, null); - assertEquals(0, context.getRetryCount()); + assertThat(context.getRetryCount()).isEqualTo(0); policy.registerThrowable(context, new RuntimeException("foo")); - assertEquals(1, context.getRetryCount()); - assertEquals("foo", context.getLastThrowable().getMessage()); + assertThat(context.getRetryCount()).isEqualTo(1); + assertThat(context.getLastThrowable().getMessage()).isEqualTo("foo"); } @Test @@ -112,9 +107,9 @@ public class SimpleRetryPolicyTests { map.put(RuntimeException.class, true); SimpleRetryPolicy policy = new SimpleRetryPolicy(3, map); RetryContext context = policy.open(null); - assertNotNull(context); + assertThat(context).isNotNull(); policy.registerThrowable(context, new RuntimeException("foo")); - assertTrue(policy.canRetry(context)); + assertThat(policy.canRetry(context)).isTrue(); } @Test @@ -123,9 +118,9 @@ public class SimpleRetryPolicyTests { map.put(RuntimeException.class, true); SimpleRetryPolicy policy = new SimpleRetryPolicy(3, map, true); RetryContext context = policy.open(null); - assertNotNull(context); + assertThat(context).isNotNull(); policy.registerThrowable(context, new Exception(new RuntimeException("foo"))); - assertTrue(policy.canRetry(context)); + assertThat(policy.canRetry(context)).isTrue(); } @Test @@ -133,8 +128,8 @@ public class SimpleRetryPolicyTests { SimpleRetryPolicy policy = new SimpleRetryPolicy(); RetryContext context = policy.open(null); RetryContext child = policy.open(context); - assertNotSame(child, context); - assertSame(context, child.getParent()); + assertThat(context).isNotSameAs(child); + assertThat(child.getParent()).isSameAs(context); } } diff --git a/src/test/java/org/springframework/retry/policy/SoftReferenceMapRetryContextCacheTests.java b/src/test/java/org/springframework/retry/policy/SoftReferenceMapRetryContextCacheTests.java index 242622f..1dfb073 100644 --- a/src/test/java/org/springframework/retry/policy/SoftReferenceMapRetryContextCacheTests.java +++ b/src/test/java/org/springframework/retry/policy/SoftReferenceMapRetryContextCacheTests.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,13 +16,13 @@ package org.springframework.retry.policy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; -import org.junit.Test; import org.springframework.retry.context.RetryContextSupport; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + public class SoftReferenceMapRetryContextCacheTests { SoftReferenceMapRetryContextCache cache = new SoftReferenceMapRetryContextCache(); @@ -31,25 +31,26 @@ public class SoftReferenceMapRetryContextCacheTests { public void testPut() { RetryContextSupport context = new RetryContextSupport(null); cache.put("foo", context); - assertEquals(context, cache.get("foo")); + assertThat(cache.get("foo")).isEqualTo(context); } - @Test(expected = RetryCacheCapacityExceededException.class) + @Test public void testPutOverLimit() { RetryContextSupport context = new RetryContextSupport(null); cache.setCapacity(1); cache.put("foo", context); - cache.put("foo", context); + assertThatExceptionOfType(RetryCacheCapacityExceededException.class) + .isThrownBy(() -> cache.put("foo", context)); } @Test public void testRemove() { - assertFalse(cache.containsKey("foo")); + assertThat(cache.containsKey("foo")).isFalse(); RetryContextSupport context = new RetryContextSupport(null); cache.put("foo", context); - assertTrue(cache.containsKey("foo")); + assertThat(cache.containsKey("foo")).isTrue(); cache.remove("foo"); - assertFalse(cache.containsKey("foo")); + assertThat(cache.containsKey("foo")).isFalse(); } } diff --git a/src/test/java/org/springframework/retry/policy/StatefulRetryIntegrationTests.java b/src/test/java/org/springframework/retry/policy/StatefulRetryIntegrationTests.java index e17fe9f..2a8a83f 100644 --- a/src/test/java/org/springframework/retry/policy/StatefulRetryIntegrationTests.java +++ b/src/test/java/org/springframework/retry/policy/StatefulRetryIntegrationTests.java @@ -15,19 +15,11 @@ */ package org.springframework.retry.policy; -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 java.util.ArrayList; import java.util.List; -import org.junit.Test; -import org.springframework.retry.ExhaustedRetryException; -import org.springframework.retry.RecoveryCallback; +import org.junit.jupiter.api.Test; + import org.springframework.retry.RetryCallback; import org.springframework.retry.RetryContext; import org.springframework.retry.RetryState; @@ -35,6 +27,9 @@ import org.springframework.retry.backoff.ExponentialBackOffPolicy; import org.springframework.retry.support.DefaultRetryState; import org.springframework.retry.support.RetryTemplate; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + /** * @author Dave Syer * @author Gary Russell @@ -53,34 +48,21 @@ public class StatefulRetryIntegrationTests { retryTemplate.setRetryContextCache(cache); retryTemplate.setRetryPolicy(new SimpleRetryPolicy(1)); - assertFalse(cache.containsKey("foo")); + assertThat(cache.containsKey("foo")).isFalse(); - try { - retryTemplate.execute(callback, retryState); - // The first failed attempt we expect to retry... - fail("Expected RuntimeException"); - } - catch (RuntimeException e) { - assertEquals(null, e.getMessage()); - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> retryTemplate.execute(callback, retryState)) + .withMessage(null); - assertTrue(cache.containsKey("foo")); + assertThat(cache.containsKey("foo")).isTrue(); - try { - retryTemplate.execute(callback, retryState); - // We don't get a second attempt... - fail("Expected ExhaustedRetryException"); - } - catch (ExhaustedRetryException e) { - // This is now the "exhausted" message: - assertNotNull(e.getMessage()); - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> retryTemplate.execute(callback, retryState)) + .withMessageContaining("exhausted"); - assertFalse(cache.containsKey("foo")); + assertThat(cache.containsKey("foo")).isFalse(); // Callback is called once: the recovery path should be called in // handleRetryExhausted (so not in this test)... - assertEquals(1, callback.attempts); + assertThat(callback.attempts).isEqualTo(1); } @Test @@ -94,27 +76,21 @@ public class StatefulRetryIntegrationTests { retryTemplate.setRetryContextCache(cache); retryTemplate.setRetryPolicy(new SimpleRetryPolicy(2)); - assertFalse(cache.containsKey("foo")); + assertThat(cache.containsKey("foo")).isFalse(); Object result = "start_foo"; - try { - result = retryTemplate.execute(callback, retryState); - // The first failed attempt we expect to retry... - fail("Expected RuntimeException"); - } - catch (RuntimeException e) { - assertNull(e.getMessage()); - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> retryTemplate.execute(callback, retryState)) + .withMessage(null); - assertTrue(cache.containsKey("foo")); + assertThat(cache.containsKey("foo")).isTrue(); result = retryTemplate.execute(callback, retryState); - assertFalse(cache.containsKey("foo")); + assertThat(cache.containsKey("foo")).isFalse(); - assertEquals(2, callback.attempts); - assertEquals(1, callback.context.getRetryCount()); - assertEquals("bar", result); + assertThat(callback.attempts).isEqualTo(2); + assertThat(callback.context.getRetryCount()).isEqualTo(1); + assertThat(result).isEqualTo("bar"); } @Test @@ -128,27 +104,21 @@ public class StatefulRetryIntegrationTests { retryTemplate.setRetryContextCache(cache); retryTemplate.setRetryPolicy(new SimpleRetryPolicy(2)); - assertFalse(cache.containsKey("foo")); + assertThat(cache.containsKey("foo")).isFalse(); Object result = "start_foo"; - try { - result = retryTemplate.execute(callback, retryState); - // The first failed attempt we expect to retry... - fail("Expected RuntimeException"); - } - catch (RuntimeException e) { - assertNull(e.getMessage()); - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> retryTemplate.execute(callback, retryState)) + .withMessage(null); - assertTrue(cache.containsKey("foo")); + assertThat(cache.containsKey("foo")).isTrue(); result = retryTemplate.execute(callback, retryState); - assertFalse(cache.containsKey("foo")); + assertThat(cache.containsKey("foo")).isFalse(); - assertEquals(2, callback.attempts); - assertEquals(1, callback.context.getRetryCount()); - assertEquals("bar", result); + assertThat(callback.attempts).isEqualTo(2); + assertThat(callback.context.getRetryCount()).isEqualTo(1); + assertThat(result).isEqualTo("bar"); } @Test @@ -168,12 +138,12 @@ public class StatefulRetryIntegrationTests { }, context -> null, retryState); } catch (Exception e) { - assertTrue(e.getMessage().equals("Fail")); + assertThat(e.getMessage().equals("Fail")).isTrue(); } } - assertEquals(3, times.size()); - assertTrue(times.get(1) - times.get(0) >= 100); - assertTrue(times.get(2) - times.get(1) >= 150); + assertThat(times).hasSize(3); + assertThat(times.get(1) - times.get(0) >= 100).isTrue(); + assertThat(times.get(2) - times.get(1) >= 150).isTrue(); } @Test @@ -187,21 +157,15 @@ public class StatefulRetryIntegrationTests { retryTemplate.setRetryContextCache(cache); retryTemplate.setRetryPolicy(new SimpleRetryPolicy(1)); - try { - retryTemplate.execute(callback, retryState); - // The first failed attempt... - fail("Expected RuntimeException"); - } - catch (RuntimeException e) { - assertEquals(null, e.getMessage()); - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> retryTemplate.execute(callback, retryState)) + .withMessage(null); retryTemplate.execute(callback, retryState); // The second attempt is successful by design... // Callback is called twice because its state is null: the recovery path should // not be called... - assertEquals(2, callback.attempts); + assertThat(callback.attempts).isEqualTo(2); } /** diff --git a/src/test/java/org/springframework/retry/policy/TimeoutRetryPolicyTests.java b/src/test/java/org/springframework/retry/policy/TimeoutRetryPolicyTests.java index 81a4505..40e08f1 100644 --- a/src/test/java/org/springframework/retry/policy/TimeoutRetryPolicyTests.java +++ b/src/test/java/org/springframework/retry/policy/TimeoutRetryPolicyTests.java @@ -16,16 +16,12 @@ package org.springframework.retry.policy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; -import org.junit.Test; import org.springframework.retry.RetryContext; +import static org.assertj.core.api.Assertions.assertThat; + public class TimeoutRetryPolicyTests { @Test @@ -34,9 +30,9 @@ public class TimeoutRetryPolicyTests { policy.setTimeout(100); RetryContext context = policy.open(null); policy.registerThrowable(context, new Exception()); - assertTrue(policy.canRetry(context)); + assertThat(policy.canRetry(context)).isTrue(); Thread.sleep(200); - assertFalse(policy.canRetry(context)); + assertThat(policy.canRetry(context)).isFalse(); policy.close(context); } @@ -44,12 +40,12 @@ public class TimeoutRetryPolicyTests { public void testRetryCount() { TimeoutRetryPolicy policy = new TimeoutRetryPolicy(); RetryContext context = policy.open(null); - assertNotNull(context); + assertThat(context).isNotNull(); policy.registerThrowable(context, null); - assertEquals(0, context.getRetryCount()); + assertThat(context.getRetryCount()).isEqualTo(0); policy.registerThrowable(context, new RuntimeException("foo")); - assertEquals(1, context.getRetryCount()); - assertEquals("foo", context.getLastThrowable().getMessage()); + assertThat(context.getRetryCount()).isEqualTo(1); + assertThat(context.getLastThrowable().getMessage()).isEqualTo("foo"); } @Test @@ -57,8 +53,8 @@ public class TimeoutRetryPolicyTests { TimeoutRetryPolicy policy = new TimeoutRetryPolicy(); RetryContext context = policy.open(null); RetryContext child = policy.open(context); - assertNotSame(child, context); - assertSame(context, child.getParent()); + assertThat(context).isNotSameAs(child); + assertThat(child.getParent()).isSameAs(context); } } diff --git a/src/test/java/org/springframework/retry/stats/CircuitBreakerInterceptorStatisticsTests.java b/src/test/java/org/springframework/retry/stats/CircuitBreakerInterceptorStatisticsTests.java index 9da7eee..c7c5f66 100644 --- a/src/test/java/org/springframework/retry/stats/CircuitBreakerInterceptorStatisticsTests.java +++ b/src/test/java/org/springframework/retry/stats/CircuitBreakerInterceptorStatisticsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 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. @@ -16,11 +16,10 @@ package org.springframework.retry.stats; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -31,6 +30,8 @@ import org.springframework.retry.annotation.EnableRetry; import org.springframework.retry.annotation.Recover; import org.springframework.retry.support.RetrySynchronizationManager; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Dave Syer * @@ -47,7 +48,7 @@ public class CircuitBreakerInterceptorStatisticsTests { private AnnotationConfigApplicationContext context; - @Before + @BeforeEach public void init() { context = new AnnotationConfigApplicationContext(TestConfiguration.class); this.callback = context.getBean(Service.class); @@ -55,7 +56,7 @@ public class CircuitBreakerInterceptorStatisticsTests { this.callback.setAttemptsBeforeSuccess(1); } - @After + @AfterEach public void close() { if (context != null) { context.close(); @@ -67,12 +68,13 @@ public class CircuitBreakerInterceptorStatisticsTests { Object result = callback.service("one"); RetryStatistics stats = repository.findOne("test"); // System.err.println(stats); - assertEquals(1, stats.getStartedCount()); - assertEquals(RECOVERED, result); + assertThat(stats.getStartedCount()).isEqualTo(1); + assertThat(result).isEqualTo(RECOVERED); result = callback.service("two"); - assertEquals(RECOVERED, result); - assertEquals("There should be two recoveries", 2, stats.getRecoveryCount()); - assertEquals("There should only be one error because the circuit is now open", 1, stats.getErrorCount()); + assertThat(result).isEqualTo(RECOVERED); + assertThat(stats.getRecoveryCount()).describedAs("There should be two recoveries").isEqualTo(2); + assertThat(stats.getErrorCount()).describedAs("There should only be one error because the circuit is now open") + .isEqualTo(1); } @Configuration diff --git a/src/test/java/org/springframework/retry/stats/CircuitBreakerStatisticsTests.java b/src/test/java/org/springframework/retry/stats/CircuitBreakerStatisticsTests.java index 1e82410..fc9a21f 100644 --- a/src/test/java/org/springframework/retry/stats/CircuitBreakerStatisticsTests.java +++ b/src/test/java/org/springframework/retry/stats/CircuitBreakerStatisticsTests.java @@ -16,8 +16,8 @@ package org.springframework.retry.stats; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.classify.BinaryExceptionClassifier; import org.springframework.retry.ExhaustedRetryException; @@ -33,11 +33,12 @@ import org.springframework.retry.support.DefaultRetryState; import org.springframework.retry.support.RetryTemplate; import org.springframework.test.util.ReflectionTestUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Dave Syer + * @author Gary Russell * */ public class CircuitBreakerStatisticsTests { @@ -60,7 +61,7 @@ public class CircuitBreakerStatisticsTests { private RetryContextCache cache; - @Before + @BeforeEach public void init() { this.callback = new MockRetryCallback(); this.recovery = context -> RECOVERED; @@ -78,15 +79,16 @@ public class CircuitBreakerStatisticsTests { this.retryTemplate.setRetryPolicy(new CircuitBreakerRetryPolicy(new NeverRetryPolicy())); Object result = this.retryTemplate.execute(this.callback, this.recovery, this.state); MutableRetryStatistics stats = (MutableRetryStatistics) repository.findOne("test"); - assertEquals(1, stats.getStartedCount()); - assertEquals(RECOVERED, result); + assertThat(stats.getStartedCount()).isEqualTo(1); + assertThat(result).isEqualTo(RECOVERED); result = this.retryTemplate.execute(this.callback, this.recovery, this.state); - assertEquals(RECOVERED, result); - assertEquals("There should be two recoveries", 2, stats.getRecoveryCount()); - assertEquals("There should only be one error because the circuit is now open", 1, stats.getErrorCount()); - assertEquals(true, stats.getAttribute(CircuitBreakerRetryPolicy.CIRCUIT_OPEN)); + assertThat(result).isEqualTo(RECOVERED); + assertThat(stats.getRecoveryCount()).describedAs("There should be two recoveries", null).isEqualTo(2); + assertThat(stats.getErrorCount()) + .describedAs("There should only be one error because the circuit is now open", null).isEqualTo(1); + assertThat(stats.getAttribute(CircuitBreakerRetryPolicy.CIRCUIT_OPEN)).isEqualTo(Boolean.TRUE); // Both recoveries are through a short circuit because we used NeverRetryPolicy - assertEquals(2, stats.getAttribute(CircuitBreakerRetryPolicy.CIRCUIT_SHORT_COUNT)); + assertThat(stats.getAttribute(CircuitBreakerRetryPolicy.CIRCUIT_SHORT_COUNT)).isEqualTo(2); resetAndAssert(this.cache, stats); } @@ -96,17 +98,12 @@ public class CircuitBreakerStatisticsTests { this.recovery = context -> { throw new ExhaustedRetryException("Planned exhausted"); }; - try { - this.retryTemplate.execute(this.callback, this.recovery, this.state); - fail("Expected ExhaustedRetryException"); - } - catch (ExhaustedRetryException e) { - // Fine - } + assertThatExceptionOfType(ExhaustedRetryException.class) + .isThrownBy(() -> this.retryTemplate.execute(this.callback, this.recovery, this.state)); MutableRetryStatistics stats = (MutableRetryStatistics) repository.findOne("test"); - assertEquals(1, stats.getStartedCount()); - assertEquals(1, stats.getAbortCount()); - assertEquals(0, stats.getRecoveryCount()); + assertThat(stats.getStartedCount()).isEqualTo(1); + assertThat(stats.getAbortCount()).isEqualTo(1); + assertThat(stats.getRecoveryCount()).isEqualTo(0); } @Test @@ -124,16 +121,17 @@ public class CircuitBreakerStatisticsTests { catch (Exception e) { } MutableRetryStatistics stats = (MutableRetryStatistics) repository.findOne("test"); - assertEquals("There should be two aborts", 2, stats.getAbortCount()); - assertEquals("There should only be one error because the circuit is now open", 1, stats.getErrorCount()); - assertEquals(true, stats.getAttribute(CircuitBreakerRetryPolicy.CIRCUIT_OPEN)); + assertThat(stats.getAbortCount()).describedAs("There should be two aborts").isEqualTo(2); + assertThat(stats.getErrorCount()) + .describedAs("There should only be one error because the circuit is now open", null).isEqualTo(1); + assertThat(stats.getAttribute(CircuitBreakerRetryPolicy.CIRCUIT_OPEN)).isEqualTo(true); resetAndAssert(this.cache, stats); } private void resetAndAssert(RetryContextCache cache, MutableRetryStatistics stats) { reset(cache.get("retry")); listener.close(cache.get("retry"), callback, null); - assertEquals(0, stats.getAttribute(CircuitBreakerRetryPolicy.CIRCUIT_SHORT_COUNT)); + assertThat(stats.getAttribute(CircuitBreakerRetryPolicy.CIRCUIT_SHORT_COUNT)).isEqualTo(0); } private void reset(RetryContext retryContext) { diff --git a/src/test/java/org/springframework/retry/stats/ExponentialAverageRetryStatisticsTests.java b/src/test/java/org/springframework/retry/stats/ExponentialAverageRetryStatisticsTests.java index ab311af..93658d0 100644 --- a/src/test/java/org/springframework/retry/stats/ExponentialAverageRetryStatisticsTests.java +++ b/src/test/java/org/springframework/retry/stats/ExponentialAverageRetryStatisticsTests.java @@ -16,17 +16,17 @@ package org.springframework.retry.stats; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - import java.util.Arrays; -import org.junit.Test; +import org.junit.jupiter.api.Test; + import org.springframework.test.util.ReflectionTestUtils; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Dave Syer + * @author Gary Russell * */ public class ExponentialAverageRetryStatisticsTests { @@ -36,66 +36,64 @@ public class ExponentialAverageRetryStatisticsTests { @Test public void pointless() { stats.setName("spam"); - assertEquals("spam", stats.getName()); - assertNotNull(stats.toString()); + assertThat(stats.getName()).isEqualTo("spam"); } @Test public void attributes() { stats.setAttribute("foo", "bar"); - ; - assertEquals("bar", stats.getAttribute("foo")); - assertTrue(Arrays.asList(stats.attributeNames()).contains("foo")); + assertThat(stats.getAttribute("foo")).isEqualTo("bar"); + assertThat(Arrays.asList(stats.attributeNames()).contains("foo")).isTrue(); } @Test public void abortCount() { stats.incrementAbortCount(); - assertEquals(1, stats.getAbortCount()); + assertThat(stats.getAbortCount()).isEqualTo(1); // rounds up to 1 - assertEquals(1, stats.getRollingAbortCount()); + assertThat(stats.getRollingAbortCount()).isEqualTo(1); } @Test public void errorCount() { stats.incrementErrorCount(); - assertEquals(1, stats.getErrorCount()); + assertThat(stats.getErrorCount()).isEqualTo(1); // rounds up to 1 - assertEquals(1, stats.getRollingErrorCount()); + assertThat(stats.getRollingErrorCount()).isEqualTo(1); } @Test public void startedCount() { stats.incrementStartedCount(); - assertEquals(1, stats.getStartedCount()); + assertThat(stats.getStartedCount()).isEqualTo(1); // rounds up to 1 - assertEquals(1, stats.getRollingStartedCount()); + assertThat(stats.getRollingStartedCount()).isEqualTo(1); } @Test public void completeCount() { stats.incrementCompleteCount(); - assertEquals(1, stats.getCompleteCount()); + assertThat(stats.getCompleteCount()).isEqualTo(1); // rounds up to 1 - assertEquals(1, stats.getRollingCompleteCount()); + assertThat(stats.getRollingCompleteCount()).isEqualTo(1); } @Test public void recoveryCount() { stats.incrementRecoveryCount(); - assertEquals(1, stats.getRecoveryCount()); + assertThat(stats.getRecoveryCount()).isEqualTo(1); // rounds up to 1 - assertEquals(1, stats.getRollingRecoveryCount()); + assertThat(stats.getRollingRecoveryCount()).isEqualTo(1); } @Test public void oldValuesDecay() { stats.incrementAbortCount(); - assertEquals(1, stats.getAbortCount()); + assertThat(stats.getAbortCount()).isEqualTo(1); // Wind back time to epoch 0 ReflectionTestUtils.setField(ReflectionTestUtils.getField(stats, "abort"), "lastTime", 0); // rounds down to 1 - assertEquals(0, stats.getRollingAbortCount()); + assertThat(stats.getRollingAbortCount()).isEqualTo(0); } } diff --git a/src/test/java/org/springframework/retry/stats/StatisticsListenerTests.java b/src/test/java/org/springframework/retry/stats/StatisticsListenerTests.java index 2670d68..4bfe005 100644 --- a/src/test/java/org/springframework/retry/stats/StatisticsListenerTests.java +++ b/src/test/java/org/springframework/retry/stats/StatisticsListenerTests.java @@ -16,11 +16,8 @@ package org.springframework.retry.stats; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import org.junit.jupiter.api.Test; -import org.junit.Test; -import org.springframework.retry.RecoveryCallback; import org.springframework.retry.RetryCallback; import org.springframework.retry.RetryContext; import org.springframework.retry.RetryState; @@ -30,6 +27,8 @@ import org.springframework.retry.policy.SimpleRetryPolicy; import org.springframework.retry.support.DefaultRetryState; import org.springframework.retry.support.RetryTemplate; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Dave Syer * @@ -49,13 +48,13 @@ public class StatisticsListenerTests { callback.setAttemptsBeforeSuccess(x); retryTemplate.setRetryPolicy(new SimpleRetryPolicy(x)); retryTemplate.execute(callback); - assertEquals(x, callback.attempts); + assertThat(callback.attempts).isEqualTo(x); RetryStatistics stats = repository.findOne("test"); // System.err.println(stats); - assertNotNull(stats); - assertEquals(x, stats.getCompleteCount()); - assertEquals((x + 1) * x / 2, stats.getStartedCount()); - assertEquals(stats.getStartedCount(), stats.getErrorCount() + x); + assertThat(stats).isNotNull(); + assertThat(stats.getCompleteCount()).isEqualTo(x); + assertThat(stats.getStartedCount()).isEqualTo((x + 1) * x / 2); + assertThat(stats.getErrorCount() + x).isEqualTo(stats.getStartedCount()); } } @@ -76,13 +75,13 @@ public class StatisticsListenerTests { // don't care } } - assertEquals(x, callback.attempts); + assertThat(callback.attempts).isEqualTo(x); RetryStatistics stats = repository.findOne("test"); // System.err.println(stats); - assertNotNull(stats); - assertEquals(x, stats.getCompleteCount()); - assertEquals((x + 1) * x / 2, stats.getStartedCount()); - assertEquals(stats.getStartedCount(), stats.getErrorCount() + x); + assertThat(stats).isNotNull(); + assertThat(stats.getCompleteCount()).isEqualTo(x); + assertThat(stats.getStartedCount()).isEqualTo((x + 1) * x / 2); + assertThat(stats.getErrorCount() + x).isEqualTo(stats.getStartedCount()); } } @@ -100,12 +99,12 @@ public class StatisticsListenerTests { catch (Exception e) { // not interested } - assertEquals(x, callback.attempts); + assertThat(callback.attempts).isEqualTo(x); RetryStatistics stats = repository.findOne("test"); - assertNotNull(stats); - assertEquals(x, stats.getAbortCount()); - assertEquals((x + 1) * x / 2, stats.getStartedCount()); - assertEquals(stats.getStartedCount(), stats.getErrorCount()); + assertThat(stats).isNotNull(); + assertThat(stats.getAbortCount()).isEqualTo(x); + assertThat(stats.getStartedCount()).isEqualTo((x + 1) * x / 2); + assertThat(stats.getErrorCount()).isEqualTo(stats.getStartedCount()); } } @@ -126,13 +125,13 @@ public class StatisticsListenerTests { // don't care } } - assertEquals(x, callback.attempts); + assertThat(callback.attempts).isEqualTo(x); RetryStatistics stats = repository.findOne("test"); // System.err.println(stats); - assertNotNull(stats); - assertEquals(x, stats.getAbortCount()); - assertEquals((x + 1) * x / 2, stats.getStartedCount()); - assertEquals(stats.getStartedCount(), stats.getErrorCount()); + assertThat(stats).isNotNull(); + assertThat(stats.getAbortCount()).isEqualTo(x); + assertThat(stats.getStartedCount()).isEqualTo((x + 1) * x / 2); + assertThat(stats.getErrorCount()).isEqualTo(stats.getStartedCount()); } } @@ -145,13 +144,13 @@ public class StatisticsListenerTests { callback.setAttemptsBeforeSuccess(x + 1); retryTemplate.setRetryPolicy(new SimpleRetryPolicy(x)); retryTemplate.execute(callback, context -> null); - assertEquals(x, callback.attempts); + assertThat(callback.attempts).isEqualTo(x); RetryStatistics stats = repository.findOne("test"); // System.err.println(stats); - assertNotNull(stats); - assertEquals(x, stats.getRecoveryCount()); - assertEquals((x + 1) * x / 2, stats.getStartedCount()); - assertEquals(stats.getStartedCount(), stats.getErrorCount()); + assertThat(stats).isNotNull(); + assertThat(stats.getRecoveryCount()).isEqualTo(x); + assertThat(stats.getStartedCount()).isEqualTo((x + 1) * x / 2); + assertThat(stats.getErrorCount()).isEqualTo(stats.getStartedCount()); } } @@ -172,13 +171,13 @@ public class StatisticsListenerTests { // don't care } } - assertEquals(x, callback.attempts); + assertThat(callback.attempts).isEqualTo(x); RetryStatistics stats = repository.findOne("test"); // System.err.println(stats); - assertNotNull(stats); - assertEquals(x, stats.getRecoveryCount()); - assertEquals((x + 1) * x / 2, stats.getStartedCount()); - assertEquals(stats.getStartedCount(), stats.getErrorCount()); + assertThat(stats).isNotNull(); + assertThat(stats.getRecoveryCount()).isEqualTo(x); + assertThat(stats.getStartedCount()).isEqualTo((x + 1) * x / 2); + assertThat(stats.getErrorCount()).isEqualTo(stats.getStartedCount()); } } diff --git a/src/test/java/org/springframework/retry/support/DefaultRetryStateTests.java b/src/test/java/org/springframework/retry/support/DefaultRetryStateTests.java index d589a7f..7764657 100644 --- a/src/test/java/org/springframework/retry/support/DefaultRetryStateTests.java +++ b/src/test/java/org/springframework/retry/support/DefaultRetryStateTests.java @@ -15,15 +15,13 @@ */ package org.springframework.retry.support; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; -import org.junit.Test; -import org.springframework.classify.Classifier; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer + * @author Gary Russell * */ public class DefaultRetryStateTests { @@ -36,9 +34,9 @@ public class DefaultRetryStateTests { @Test public void testDefaultRetryStateObjectBooleanClassifierOfQsuperThrowableBoolean() { DefaultRetryState state = new DefaultRetryState("foo", true, classifiable -> false); - assertEquals("foo", state.getKey()); - assertTrue(state.isForceRefresh()); - assertFalse(state.rollbackFor(null)); + assertThat(state.getKey()).isEqualTo("foo"); + assertThat(state.isForceRefresh()).isTrue(); + assertThat(state.rollbackFor(null)).isFalse(); } /** @@ -49,9 +47,9 @@ public class DefaultRetryStateTests { @Test public void testDefaultRetryStateObjectClassifierOfQsuperThrowableBoolean() { DefaultRetryState state = new DefaultRetryState("foo", classifiable -> false); - assertEquals("foo", state.getKey()); - assertFalse(state.isForceRefresh()); - assertFalse(state.rollbackFor(null)); + assertThat(state.getKey()).isEqualTo("foo"); + assertThat(state.isForceRefresh()).isFalse(); + assertThat(state.rollbackFor(null)).isFalse(); } /** @@ -61,9 +59,9 @@ public class DefaultRetryStateTests { @Test public void testDefaultRetryStateObjectBoolean() { DefaultRetryState state = new DefaultRetryState("foo", true); - assertEquals("foo", state.getKey()); - assertTrue(state.isForceRefresh()); - assertTrue(state.rollbackFor(null)); + assertThat(state.getKey()).isEqualTo("foo"); + assertThat(state.isForceRefresh()).isTrue(); + assertThat(state.rollbackFor(null)).isTrue(); } /** @@ -73,9 +71,9 @@ public class DefaultRetryStateTests { @Test public void testDefaultRetryStateObject() { DefaultRetryState state = new DefaultRetryState("foo"); - assertEquals("foo", state.getKey()); - assertFalse(state.isForceRefresh()); - assertTrue(state.rollbackFor(null)); + assertThat(state.getKey()).isEqualTo("foo"); + assertThat(state.isForceRefresh()).isFalse(); + assertThat(state.rollbackFor(null)).isTrue(); } } diff --git a/src/test/java/org/springframework/retry/support/RetrySimulationTests.java b/src/test/java/org/springframework/retry/support/RetrySimulationTests.java index 179bb29..aab9f7a 100644 --- a/src/test/java/org/springframework/retry/support/RetrySimulationTests.java +++ b/src/test/java/org/springframework/retry/support/RetrySimulationTests.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,16 +16,17 @@ package org.springframework.retry.support; -import static java.util.Arrays.asList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import java.util.Arrays; + +import org.junit.jupiter.api.Test; -import org.junit.Test; import org.springframework.retry.backoff.ExponentialBackOffPolicy; import org.springframework.retry.backoff.ExponentialRandomBackOffPolicy; import org.springframework.retry.backoff.FixedBackOffPolicy; import org.springframework.retry.policy.SimpleRetryPolicy; +import static org.assertj.core.api.Assertions.assertThat; + public class RetrySimulationTests { @Test @@ -42,9 +43,11 @@ public class RetrySimulationTests { System.out.println("Longest sequence " + simulation.getLongestTotalSleepSequence()); System.out.println("Percentiles: " + simulation.getPercentiles()); - assertEquals(asList(400l, 400l, 400l, 400l), simulation.getLongestTotalSleepSequence().getSleeps()); - assertEquals(asList(400d, 400d, 400d, 400d, 400d, 400d, 400d, 400d, 400d), simulation.getPercentiles()); - assertEquals(400d, simulation.getPercentile(0.5), 0.1); + assertThat(simulation.getLongestTotalSleepSequence().getSleeps()) + .isEqualTo(Arrays.asList(400l, 400l, 400l, 400l)); + assertThat(simulation.getPercentiles()) + .isEqualTo(Arrays.asList(400d, 400d, 400d, 400d, 400d, 400d, 400d, 400d, 400d)); + assertThat(simulation.getPercentile(0.5)).isEqualTo(400d); } @Test @@ -63,9 +66,11 @@ public class RetrySimulationTests { System.out.println("Longest sequence " + simulation.getLongestTotalSleepSequence()); System.out.println("Percentiles: " + simulation.getPercentiles()); - assertEquals(asList(100l, 200l, 400l, 800l), simulation.getLongestTotalSleepSequence().getSleeps()); - assertEquals(asList(100d, 100d, 200d, 200d, 300d, 400d, 400d, 800d, 800d), simulation.getPercentiles()); - assertEquals(300d, simulation.getPercentile(0.5f), 0.1); + assertThat(simulation.getLongestTotalSleepSequence().getSleeps()) + .isEqualTo(Arrays.asList(100l, 200l, 400l, 800l)); + assertThat(simulation.getPercentiles()) + .isEqualTo(Arrays.asList(100d, 100d, 200d, 200d, 300d, 400d, 400d, 800d, 800d)); + assertThat(simulation.getPercentile(0.5f)).isEqualTo(300d); } @Test @@ -84,7 +89,7 @@ public class RetrySimulationTests { System.out.println("Longest sequence " + simulation.getLongestTotalSleepSequence()); System.out.println("Percentiles: " + simulation.getPercentiles()); - assertTrue(simulation.getPercentiles().size() > 4); + assertThat(simulation.getPercentiles().size()).isGreaterThan(4); } } diff --git a/src/test/java/org/springframework/retry/support/RetrySynchronizationManagerTests.java b/src/test/java/org/springframework/retry/support/RetrySynchronizationManagerTests.java index 1071205..12921f2 100644 --- a/src/test/java/org/springframework/retry/support/RetrySynchronizationManagerTests.java +++ b/src/test/java/org/springframework/retry/support/RetrySynchronizationManagerTests.java @@ -16,73 +16,70 @@ package org.springframework.retry.support; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.springframework.retry.RetryCallback; import org.springframework.retry.RetryContext; import org.springframework.retry.context.RetryContextSupport; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer + * @author Gary Russell */ public class RetrySynchronizationManagerTests { RetryTemplate template = new RetryTemplate(); - @Before + @BeforeEach public void setUp() { RetrySynchronizationManagerTests.clearAll(); RetryContext status = RetrySynchronizationManager.getContext(); - assertNull(status); + assertThat(status).isNull(); } @Test public void testStatusIsStoredByTemplate() { RetryContext status = RetrySynchronizationManager.getContext(); - assertNull(status); + assertThat(status).isNull(); this.template.execute(retryContext -> { RetryContext global = RetrySynchronizationManager.getContext(); - assertNotNull(retryContext); - assertEquals(global, retryContext); + assertThat(retryContext).isNotNull(); + assertThat(retryContext).isEqualTo(global); return null; }); status = RetrySynchronizationManager.getContext(); - assertNull(status); + assertThat(status).isNull(); } @Test public void testStatusRegistration() { RetryContext status = new RetryContextSupport(null); RetryContext value = RetrySynchronizationManager.register(status); - assertNull(value); + assertThat(value).isNull(); value = RetrySynchronizationManager.register(status); - assertEquals(status, value); + assertThat(value).isEqualTo(status); } @Test public void testClear() { RetryContext status = new RetryContextSupport(null); RetryContext value = RetrySynchronizationManager.register(status); - assertNull(value); + assertThat(value).isNull(); RetrySynchronizationManager.clear(); value = RetrySynchronizationManager.register(status); - assertNull(value); + assertThat(value).isNull(); } @Test public void testParent() { RetryContext parent = new RetryContextSupport(null); RetryContext child = new RetryContextSupport(parent); - assertSame(parent, child.getParent()); + assertThat(child.getParent()).isSameAs(parent); } /** diff --git a/src/test/java/org/springframework/retry/support/RetryTemplateBuilderTests.java b/src/test/java/org/springframework/retry/support/RetryTemplateBuilderTests.java index b91ae70..0973202 100644 --- a/src/test/java/org/springframework/retry/support/RetryTemplateBuilderTests.java +++ b/src/test/java/org/springframework/retry/support/RetryTemplateBuilderTests.java @@ -22,8 +22,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.classify.BinaryExceptionClassifier; import org.springframework.retry.RetryListener; @@ -40,6 +39,8 @@ import org.springframework.retry.policy.MaxAttemptsRetryPolicy; import org.springframework.retry.policy.TimeoutRetryPolicy; import org.springframework.retry.util.test.TestUtils; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; import static org.springframework.retry.util.test.TestUtils.getPropertyValue; @@ -51,6 +52,7 @@ import static org.springframework.retry.util.test.TestUtils.getPropertyValue; * * @author Aleksandr Shamukov * @author Kim In Hoi + * @author Gary Russell */ public class RetryTemplateBuilderTests { @@ -62,14 +64,14 @@ public class RetryTemplateBuilderTests { PolicyTuple policyTuple = PolicyTuple.extractWithAsserts(template); assertDefaultClassifier(policyTuple); - Assert.assertTrue(policyTuple.baseRetryPolicy instanceof MaxAttemptsRetryPolicy); + assertThat(policyTuple.baseRetryPolicy).isInstanceOf(MaxAttemptsRetryPolicy.class); assertDefaultClassifier(policyTuple); - Assert.assertFalse(getPropertyValue(template, "throwLastExceptionOnExhausted", Boolean.class)); - Assert.assertTrue(getPropertyValue(template, "retryContextCache") instanceof MapRetryContextCache); - Assert.assertEquals(0, getPropertyValue(template, "listeners", RetryListener[].class).length); + assertThat(getPropertyValue(template, "throwLastExceptionOnExhausted", Boolean.class)).isFalse(); + assertThat(getPropertyValue(template, "retryContextCache")).isInstanceOf(MapRetryContextCache.class); + assertThat(getPropertyValue(template, "listeners", RetryListener[].class).length).isEqualTo(0); - Assert.assertTrue(getPropertyValue(template, "backOffPolicy") instanceof NoBackOffPolicy); + assertThat(getPropertyValue(template, "backOffPolicy")).isInstanceOf(NoBackOffPolicy.class); } @Test @@ -85,27 +87,28 @@ public class RetryTemplateBuilderTests { PolicyTuple policyTuple = PolicyTuple.extractWithAsserts(template); BinaryExceptionClassifier classifier = policyTuple.exceptionClassifierRetryPolicy.getExceptionClassifier(); - Assert.assertTrue(classifier.classify(new FileNotFoundException())); - Assert.assertTrue(classifier.classify(new IllegalArgumentException())); - Assert.assertFalse(classifier.classify(new RuntimeException())); - Assert.assertFalse(classifier.classify(new OutOfMemoryError())); + assertThat(classifier.classify(new FileNotFoundException())).isTrue(); + assertThat(classifier.classify(new IllegalArgumentException())).isTrue(); + assertThat(classifier.classify(new RuntimeException())).isFalse(); + assertThat(classifier.classify(new OutOfMemoryError())).isFalse(); - Assert.assertTrue(policyTuple.baseRetryPolicy instanceof MaxAttemptsRetryPolicy); - Assert.assertEquals(10, ((MaxAttemptsRetryPolicy) policyTuple.baseRetryPolicy).getMaxAttempts()); + assertThat(policyTuple.baseRetryPolicy instanceof MaxAttemptsRetryPolicy).isTrue(); + assertThat(((MaxAttemptsRetryPolicy) policyTuple.baseRetryPolicy).getMaxAttempts()).isEqualTo(10); List listeners = Arrays.asList(getPropertyValue(template, "listeners", RetryListener[].class)); - Assert.assertEquals(2, listeners.size()); - Assert.assertTrue(listeners.contains(listener1)); - Assert.assertTrue(listeners.contains(listener2)); + assertThat(listeners).hasSize(2); + assertThat(listeners.contains(listener1)).isTrue(); + assertThat(listeners.contains(listener2)).isTrue(); - Assert.assertTrue(getPropertyValue(template, "backOffPolicy") instanceof ExponentialBackOffPolicy); + assertThat(getPropertyValue(template, "backOffPolicy")).isInstanceOf(ExponentialBackOffPolicy.class); } /* ---------------- Retry policy -------------- */ - @Test(expected = IllegalArgumentException.class) + @Test public void testFailOnRetryPoliciesConflict() { - RetryTemplate.builder().maxAttempts(3).withinMillis(1000).build(); + assertThatIllegalArgumentException() + .isThrownBy(() -> RetryTemplate.builder().maxAttempts(3).withinMillis(1000).build()); } @Test @@ -115,8 +118,8 @@ public class RetryTemplateBuilderTests { PolicyTuple policyTuple = PolicyTuple.extractWithAsserts(template); assertDefaultClassifier(policyTuple); - Assert.assertTrue(policyTuple.baseRetryPolicy instanceof TimeoutRetryPolicy); - Assert.assertEquals(10000, ((TimeoutRetryPolicy) policyTuple.baseRetryPolicy).getTimeout()); + assertThat(policyTuple.baseRetryPolicy).isInstanceOf(TimeoutRetryPolicy.class); + assertThat(((TimeoutRetryPolicy) policyTuple.baseRetryPolicy).getTimeout()).isEqualTo(10000); } @Test @@ -126,7 +129,7 @@ public class RetryTemplateBuilderTests { PolicyTuple policyTuple = PolicyTuple.extractWithAsserts(template); assertDefaultClassifier(policyTuple); - Assert.assertTrue(policyTuple.baseRetryPolicy instanceof AlwaysRetryPolicy); + assertThat(policyTuple.baseRetryPolicy).isInstanceOf(AlwaysRetryPolicy.class); } @Test @@ -138,78 +141,84 @@ public class RetryTemplateBuilderTests { PolicyTuple policyTuple = PolicyTuple.extractWithAsserts(template); assertDefaultClassifier(policyTuple); - Assert.assertEquals(customPolicy, policyTuple.baseRetryPolicy); + assertThat(policyTuple.baseRetryPolicy).isEqualTo(customPolicy); } private void assertDefaultClassifier(PolicyTuple policyTuple) { BinaryExceptionClassifier classifier = policyTuple.exceptionClassifierRetryPolicy.getExceptionClassifier(); - Assert.assertTrue(classifier.classify(new Exception())); - Assert.assertTrue(classifier.classify(new Exception(new Error()))); - Assert.assertFalse(classifier.classify(new Error())); - Assert.assertFalse(classifier.classify(new Error(new Exception()))); + assertThat(classifier.classify(new Exception())).isTrue(); + assertThat(classifier.classify(new Exception(new Error()))).isTrue(); + assertThat(classifier.classify(new Error())).isFalse(); + assertThat(classifier.classify(new Error(new Exception()))).isFalse(); } /* ---------------- Exception classification -------------- */ - @Test(expected = IllegalArgumentException.class) + @Test public void testFailOnEmptyExceptionClassifierRules() { - RetryTemplate.builder().traversingCauses().build(); + assertThatIllegalArgumentException().isThrownBy(() -> RetryTemplate.builder().traversingCauses().build()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testFailOnNotationMix() { - RetryTemplate.builder().retryOn(IOException.class).notRetryOn(OutOfMemoryError.class); + assertThatIllegalArgumentException().isThrownBy( + () -> RetryTemplate.builder().retryOn(IOException.class).notRetryOn(OutOfMemoryError.class)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testFailOnNotationsMix() { - RetryTemplate.builder().retryOn(Collections.>singletonList(IOException.class)) - .notRetryOn(Collections.>singletonList(OutOfMemoryError.class)); + assertThatIllegalArgumentException().isThrownBy(() -> RetryTemplate.builder() + .retryOn(Collections.>singletonList(IOException.class)) + .notRetryOn(Collections.>singletonList(OutOfMemoryError.class))); } /* ---------------- BackOff -------------- */ - @Test(expected = IllegalArgumentException.class) + @Test public void testFailOnBackOffPolicyNull() { - RetryTemplate.builder().customBackoff(null).build(); + assertThatIllegalArgumentException().isThrownBy(() -> RetryTemplate.builder().customBackoff(null).build()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testFailOnBackOffPolicyConflict() { - RetryTemplate.builder().noBackoff().fixedBackoff(1000).build(); + assertThatIllegalArgumentException() + .isThrownBy(() -> RetryTemplate.builder().noBackoff().fixedBackoff(1000).build()); } @Test public void testUniformRandomBackOff() { RetryTemplate template = RetryTemplate.builder().uniformRandomBackoff(10, 100).build(); - Assert.assertTrue(getPropertyValue(template, "backOffPolicy") instanceof UniformRandomBackOffPolicy); + assertThat(getPropertyValue(template, "backOffPolicy")).isInstanceOf(UniformRandomBackOffPolicy.class); } @Test public void testNoBackOff() { RetryTemplate template = RetryTemplate.builder().noBackoff().build(); - Assert.assertTrue(getPropertyValue(template, "backOffPolicy") instanceof NoBackOffPolicy); + assertThat(getPropertyValue(template, "backOffPolicy")).isInstanceOf(NoBackOffPolicy.class); } @Test public void testExpBackOffWithRandom() { RetryTemplate template = RetryTemplate.builder().exponentialBackoff(10, 2, 500, true).build(); - Assert.assertTrue(getPropertyValue(template, "backOffPolicy") instanceof ExponentialRandomBackOffPolicy); + assertThat(getPropertyValue(template, "backOffPolicy")).isInstanceOf(ExponentialRandomBackOffPolicy.class); } - @Test(expected = IllegalArgumentException.class) + @Test public void testValidateInitAndMax() { - RetryTemplate.builder().exponentialBackoff(100, 2, 100).build(); + assertThatIllegalArgumentException() + .isThrownBy(() -> RetryTemplate.builder().exponentialBackoff(100, 2, 100).build()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testValidateMeaninglessMultipier() { - RetryTemplate.builder().exponentialBackoff(100, 1, 200).build(); + assertThatIllegalArgumentException() + .isThrownBy(() -> RetryTemplate.builder().exponentialBackoff(100, 1, 200).build()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testValidateZeroInitInterval() { - RetryTemplate.builder().exponentialBackoff(0, 2, 200).build(); + assertThatIllegalArgumentException() + .isThrownBy(() -> RetryTemplate.builder().exponentialBackoff(0, 2, 200).build()); } /* ---------------- Utils -------------- */ @@ -225,7 +234,7 @@ public class RetryTemplateBuilderTests { CompositeRetryPolicy.class); PolicyTuple res = new PolicyTuple(); - Assert.assertFalse(getPropertyValue(compositeRetryPolicy, "optimistic", Boolean.class)); + assertThat(getPropertyValue(compositeRetryPolicy, "optimistic", Boolean.class)).isFalse(); for (final RetryPolicy policy : getPropertyValue(compositeRetryPolicy, "policies", RetryPolicy[].class)) { if (policy instanceof BinaryExceptionClassifierRetryPolicy) { @@ -235,11 +244,11 @@ public class RetryTemplateBuilderTests { res.baseRetryPolicy = policy; } } - Assert.assertNotNull(res.exceptionClassifierRetryPolicy); - Assert.assertNotNull(res.baseRetryPolicy); + assertThat(res.exceptionClassifierRetryPolicy).isNotNull(); + assertThat(res.baseRetryPolicy).isNotNull(); return res; } } -} \ No newline at end of file +} diff --git a/src/test/java/org/springframework/retry/support/RetryTemplateTests.java b/src/test/java/org/springframework/retry/support/RetryTemplateTests.java index 2040a0d..f204fbd 100644 --- a/src/test/java/org/springframework/retry/support/RetryTemplateTests.java +++ b/src/test/java/org/springframework/retry/support/RetryTemplateTests.java @@ -20,7 +20,7 @@ import java.util.Collections; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.classify.BinaryExceptionClassifier; import org.springframework.retry.RetryCallback; @@ -34,11 +34,8 @@ import org.springframework.retry.listener.RetryListenerSupport; import org.springframework.retry.policy.NeverRetryPolicy; import org.springframework.retry.policy.SimpleRetryPolicy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -63,7 +60,7 @@ public class RetryTemplateTests { RetryTemplate retryTemplate = new RetryTemplate(); retryTemplate.setRetryPolicy(new SimpleRetryPolicy(x)); retryTemplate.execute(callback); - assertEquals(x, callback.attempts); + assertThat(callback.attempts).isEqualTo(x); } } @@ -84,7 +81,7 @@ public class RetryTemplateTests { RetryTemplate retryTemplate = new RetryTemplate(); retryTemplate.setRetryPolicy(new SimpleRetryPolicy(x)); retryTemplate.execute(callback); - assertEquals(x, attempts.get()); + assertThat(attempts.get()).isEqualTo(x); } } @@ -96,8 +93,8 @@ public class RetryTemplateTests { retryTemplate.setRetryPolicy(new SimpleRetryPolicy(2)); final Object value = new Object(); Object result = retryTemplate.execute(callback, context -> value); - assertEquals(2, callback.attempts); - assertEquals(value, result); + assertThat(callback.attempts).isEqualTo(2); + assertThat(result).isEqualTo(value); } @Test @@ -106,7 +103,7 @@ public class RetryTemplateTests { RetryTemplate retryTemplate = new RetryTemplate(); retryTemplate.setRetryPolicy(new NeverRetryPolicy()); retryTemplate.execute(callback); - assertEquals(1, callback.attempts); + assertThat(callback.attempts).isEqualTo(1); } @Test @@ -123,8 +120,8 @@ public class RetryTemplateTests { fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { - assertNotNull(e); - assertEquals(retryAttempts, callback.attempts); + assertThat(e).isNotNull(); + assertThat(callback.attempts).isEqualTo(retryAttempts); return; } fail("Expected IllegalArgumentException"); @@ -140,7 +137,7 @@ public class RetryTemplateTests { RetryTemplate retryTemplate = new RetryTemplate(); retryTemplate.setRetryPolicy(new SimpleRetryPolicy(attempts)); retryTemplate.execute(callback); - assertEquals(attempts, callback.attempts); + assertThat(callback.attempts).isEqualTo(attempts); } @Test @@ -156,7 +153,7 @@ public class RetryTemplateTests { BinaryExceptionClassifier classifier = new BinaryExceptionClassifier( Collections.>singleton(IllegalArgumentException.class), false); retryTemplate.execute(callback, new DefaultRetryState("foo", classifier)); - assertEquals(attempts, callback.attempts); + assertThat(callback.attempts).isEqualTo(attempts); } @Test @@ -175,13 +172,13 @@ public class RetryTemplateTests { template.execute(callback); } catch (Exception e) { - assertNotNull(e); - assertEquals(1, callback.attempts); + assertThat(e).isNotNull(); + assertThat(callback.attempts).isEqualTo(1); } callback.setExceptionToThrow(new RuntimeException()); template.execute(callback); - assertEquals(attempts, callback.attempts); + assertThat(callback.attempts).isEqualTo(attempts); } @Test @@ -194,9 +191,9 @@ public class RetryTemplateTests { retryTemplate.setRetryPolicy(new SimpleRetryPolicy(10)); retryTemplate.setBackOffPolicy(backOff); retryTemplate.execute(callback); - assertEquals(x, callback.attempts); - assertEquals(1, backOff.startCalls); - assertEquals(x - 1, backOff.backOffCalls); + assertThat(callback.attempts).isEqualTo(x); + assertThat(backOff.startCalls).isEqualTo(1); + assertThat(backOff.backOffCalls).isEqualTo(x - 1); } } @@ -213,7 +210,7 @@ public class RetryTemplateTests { catch (IllegalStateException ex) { // Expected for internal retry policy (external would recover // gracefully) - assertEquals("Retry this operation", ex.getMessage()); + assertThat(ex.getMessage()).isEqualTo("Retry this operation"); } } @@ -231,7 +228,7 @@ public class RetryTemplateTests { catch (IllegalStateException ex) { // Expected for internal retry policy (external would recover // gracefully) - assertEquals("Retry this operation", ex.getMessage()); + assertThat(ex.getMessage()).isEqualTo("Retry this operation"); } } @@ -244,16 +241,18 @@ public class RetryTemplateTests { RetryTemplateTests.this.count++; Object result = inner.execute((RetryCallback) status1 -> { RetryTemplateTests.this.count++; - assertNotNull(RetryTemplateTests.this.context); - assertNotSame(status1, RetryTemplateTests.this.context); - assertSame(RetryTemplateTests.this.context, status1.getParent()); - assertSame("The context should be the child", status1, RetrySynchronizationManager.getContext()); + assertThat(RetryTemplateTests.this.context).isNotNull(); + assertThat(RetryTemplateTests.this.context).isNotSameAs(status1); + assertThat(status1.getParent()).isSameAs(RetryTemplateTests.this.context); + assertThat(RetrySynchronizationManager.getContext()).describedAs("The context should be the child") + .isSameAs(status1); return null; }); - assertSame("The context should be restored", status, RetrySynchronizationManager.getContext()); + assertThat(RetrySynchronizationManager.getContext()).describedAs("The context should be restored") + .isSameAs(status); return result; }); - assertEquals(2, this.count); + assertThat(this.count).isEqualTo(2); } @Test @@ -267,7 +266,7 @@ public class RetryTemplateTests { fail("Expected Error"); } catch (Error e) { - assertEquals("Realllly bad!", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("Realllly bad!"); } } @@ -288,7 +287,7 @@ public class RetryTemplateTests { fail("Expected Error"); } catch (TerminatedRetryException e) { - assertEquals("Planned", e.getCause().getMessage()); + assertThat(e.getCause().getMessage()).isEqualTo("Planned"); } } @@ -308,7 +307,7 @@ public class RetryTemplateTests { fail("Expected RuntimeException"); } catch (BackOffInterruptedException e) { - assertEquals("foo", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("foo"); } } @@ -343,7 +342,7 @@ public class RetryTemplateTests { fail(); } catch (Exception expected) { - assertEquals("maybe next time!", expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo("maybe next time!"); } verify(bop).start(any()); } @@ -369,7 +368,7 @@ public class RetryTemplateTests { callCount.incrementAndGet(); return first.getAndSet(false) ? "bad" : "good"; }); - assertEquals(2, callCount.get()); + assertThat(callCount.get()).isEqualTo(2); } private static class MockRetryCallback implements RetryCallback { diff --git a/src/test/java/org/springframework/retry/support/StatefulRecoveryRetryTests.java b/src/test/java/org/springframework/retry/support/StatefulRecoveryRetryTests.java index 1ac47a3..4458d44 100644 --- a/src/test/java/org/springframework/retry/support/StatefulRecoveryRetryTests.java +++ b/src/test/java/org/springframework/retry/support/StatefulRecoveryRetryTests.java @@ -20,7 +20,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.classify.BinaryExceptionClassifier; import org.springframework.dao.DataAccessException; @@ -35,11 +35,8 @@ import org.springframework.retry.policy.MapRetryContextCache; import org.springframework.retry.policy.NeverRetryPolicy; import org.springframework.retry.policy.SimpleRetryPolicy; -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.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class StatefulRecoveryRetryTests { @@ -52,9 +49,9 @@ public class StatefulRecoveryRetryTests { @Test public void testOpenSunnyDay() { RetryContext context = this.retryTemplate.open(new NeverRetryPolicy(), new DefaultRetryState("foo")); - assertNotNull(context); + assertThat(context).isNotNull(); // we haven't called the processor yet... - assertEquals(0, this.count); + assertThat(this.count).isEqualTo(0); } @Test @@ -62,9 +59,9 @@ public class StatefulRecoveryRetryTests { NeverRetryPolicy retryPolicy = new NeverRetryPolicy(); RetryState state = new DefaultRetryState("foo"); RetryContext context = this.retryTemplate.open(retryPolicy, state); - assertNotNull(context); + assertThat(context).isNotNull(); this.retryTemplate.registerThrowable(retryPolicy, state, context, new Exception()); - assertFalse(retryPolicy.canRetry(context)); + assertThat(retryPolicy.canRetry(context)).isFalse(); } @Test @@ -72,13 +69,13 @@ public class StatefulRecoveryRetryTests { NeverRetryPolicy retryPolicy = new NeverRetryPolicy(); RetryState state = new DefaultRetryState("foo"); RetryContext context = this.retryTemplate.open(retryPolicy, state); - assertNotNull(context); + assertThat(context).isNotNull(); this.retryTemplate.registerThrowable(retryPolicy, state, context, new Exception()); - assertFalse(retryPolicy.canRetry(context)); + assertThat(retryPolicy.canRetry(context)).isFalse(); this.retryTemplate.close(retryPolicy, context, state, true); // still can't retry, even if policy is closed // (not that this would happen in practice)... - assertFalse(retryPolicy.canRetry(context)); + assertThat(retryPolicy.canRetry(context)).isFalse(); } @Test @@ -95,18 +92,13 @@ public class StatefulRecoveryRetryTests { return input; }; Object result = null; - try { - result = this.retryTemplate.execute(callback, recoveryCallback, state); - fail("Expected exception on first try"); - } - catch (Exception e) { - // expected... - } + assertThatExceptionOfType(Exception.class) + .isThrownBy(() -> this.retryTemplate.execute(callback, recoveryCallback, state)); // On the second retry, the recovery path is taken... result = this.retryTemplate.execute(callback, recoveryCallback, state); - assertEquals(input, result); // default result is the item - assertEquals(1, this.count); - assertEquals(input, this.list.get(0)); + assertThat(result).isEqualTo(input); // default result is the item + assertThat(this.count).isEqualTo(1); + assertThat(this.list.get(0)).isEqualTo(input); } @Test @@ -116,7 +108,7 @@ public class StatefulRecoveryRetryTests { BinaryExceptionClassifier classifier = new BinaryExceptionClassifier( Collections.>singleton(DataAccessException.class)); // ...but not these: - assertFalse(classifier.classify(new RuntimeException())); + assertThat(classifier.classify(new RuntimeException())).isFalse(); final String input = "foo"; RetryState state = new DefaultRetryState(input, classifier); RetryCallback callback = context -> { @@ -130,9 +122,9 @@ public class StatefulRecoveryRetryTests { Object result = null; // On the second retry, the recovery path is taken... result = this.retryTemplate.execute(callback, recoveryCallback, state); - assertEquals(input, result); // default result is the item - assertEquals(1, this.count); - assertEquals(input, this.list.get(0)); + assertThat(result).isEqualTo(input); // default result is the item + assertThat(this.count).isEqualTo(1); + assertThat(this.list.get(0)).isEqualTo(input); } @Test @@ -146,25 +138,14 @@ public class StatefulRecoveryRetryTests { throw new RuntimeException("Barf!"); }; - try { - this.retryTemplate.execute(callback, state); - fail("Expected ExhaustedRetryException"); - } - catch (RuntimeException e) { - assertEquals("Barf!", e.getMessage()); - } - - try { - this.retryTemplate.execute(callback, state); - fail("Expected ExhaustedRetryException"); - } - catch (ExhaustedRetryException e) { - // expected - } + assertThatExceptionOfType(Exception.class).isThrownBy(() -> this.retryTemplate.execute(callback, state)) + .withMessage("Barf!"); + assertThatExceptionOfType(ExhaustedRetryException.class) + .isThrownBy(() -> this.retryTemplate.execute(callback, state)); RetryContext context = this.retryTemplate.open(retryPolicy, state); // True after exhausted - the history is reset... - assertTrue(retryPolicy.canRetry(context)); + assertThat(retryPolicy.canRetry(context)).isTrue(); } @Test @@ -183,29 +164,17 @@ public class StatefulRecoveryRetryTests { throw new RuntimeException("Barf!"); }; - try { - this.retryTemplate.execute(callback, state); - fail("Expected RuntimeException"); - } - catch (RuntimeException ex) { - String message = ex.getMessage(); - assertEquals("Barf!", message); - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.retryTemplate.execute(callback, state)) + .withMessage("Barf!"); // Only fails second attempt because the algorithm to detect // inconsistent has codes relies on the cache having been used for this // item already... - try { - this.retryTemplate.execute(callback, state); - fail("Expected RetryException"); - } - catch (RetryException ex) { - String message = ex.getMessage(); - assertTrue("Message doesn't contain 'inconsistent': " + message, message.contains("inconsistent")); - } + assertThatExceptionOfType(RetryException.class).isThrownBy(() -> this.retryTemplate.execute(callback, state)) + .withMessageContaining("inconsistent"); RetryContext context = this.retryTemplate.open(retryPolicy, state); // True after exhausted - the history is reset... - assertEquals(0, context.getRetryCount()); + assertThat(context.getRetryCount()).isEqualTo(0); } @@ -220,22 +189,13 @@ public class StatefulRecoveryRetryTests { throw new RuntimeException("Barf!"); }; - try { - this.retryTemplate.execute(callback, new DefaultRetryState("foo")); - fail("Expected RuntimeException"); - } - catch (RuntimeException e) { - assertEquals("Barf!", e.getMessage()); - } + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> this.retryTemplate.execute(callback, new DefaultRetryState("foo"))) + .withMessage("Barf!"); - try { - this.retryTemplate.execute(callback, new DefaultRetryState("bar")); - fail("Expected RetryException"); - } - catch (RetryException e) { - String message = e.getMessage(); - assertTrue("Message does not contain 'capacity': " + message, message.contains("capacity")); - } + assertThatExceptionOfType(RetryException.class) + .isThrownBy(() -> this.retryTemplate.execute(callback, new DefaultRetryState("bar"))) + .withMessageContaining("capacity"); } @Test @@ -253,18 +213,13 @@ public class StatefulRecoveryRetryTests { }; RecoveryCallback recoveryCallback = context -> null; - try { - this.retryTemplate.execute(callback, recoveryCallback, state); - fail("Expected RuntimeException"); - } - catch (RuntimeException e) { - assertEquals("Barf!", e.getMessage()); - } + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> this.retryTemplate.execute(callback, recoveryCallback, state)).withMessage("Barf!"); this.retryTemplate.execute(callback, recoveryCallback, state); RetryContext context = this.retryTemplate.open(retryPolicy, state); // True after exhausted - the history is reset... - assertEquals(0, context.getRetryCount()); + assertThat(context.getRetryCount()).isEqualTo(0); }