如何在SpringBootTest中模拟Spring的@Retryable属性,例如maxAttemps和delay。

huangapple go评论66阅读模式
英文:

How to mock Spring's @Retryable attributes such as maxAttemps and delay in SpringBootTest

问题

我有一个方法,我正在尝试测试

@Retryable(value = {SocketTimeoutException.class},
             backoff = @Backoff(delay = 10000),
             maxAttempts = 4)
public String getNewString(String oldString) throws IOException{
   ...
}

我已经创建了它的测试用例,如下所示:

@SpringBootTest
@RunWith(SpringRunner.class)
public class TestStrings {
  @Test(expected = SocketTimeoutException.class)
  public void testGetNewString() throws IOException {
     ...
  }

一切都很顺利,测试用例运行4次,间隔10秒。但我想要更改@Retryable的属性,特别是将maxAttempts从4更改为2,将delay从10秒更改为0.5秒,以便在运行测试用例时不需要等待很长时间,测试用例应该快速结束,同时也测试重试功能。

英文:

I have a method which I'm trying to test

@Retryable(value = {SocketTimeoutException.class},
             backoff = @Backoff(delay = 10000),
             maxAttempts = 4)
public String getNewString(String oldString) throws IOException{
   ...
}

I have created it's test case like so:

@SpringBootTest
@RunWith(SpringRunner.class)
public class TestStrings {
  @Test(expected = SocketTimeoutException.class)
  public void testGetNewString() throws IOException {
     ...
  }

Everything works great, the test case runs 4 times with a delay of 10sec. But I want to change the attributes of @Retryable, namely maxAttempts from 4 to 2 and delay from 10s to 0.5s for this specific test case.
I want to do this so that when running the test cases it should not wait for a long time and the test case should end quickly meanwhile also testing the retry functionality.

答案1

得分: 5

使用以下代码:

@Retryable(maxAttemptsExpression = "${max.attempts:4}", 
        backoff = @Backoff(delayExpression = "${delay:10000}"))

并在您的测试案例中设置属性。

英文:

Use

@Retryable(maxAttemptsExpression = "${max.attempts:4}", 
		backoff = @Backoff(delayExpression = "${delay:10000}"))

and set the properties in your test case.

huangapple
  • 本文由 发表于 2020年8月5日 20:00:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/63264737.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定