简体   繁体   English

Mockito 单元测试重试逻辑

[英]Mockito unit testing a retry logic

I have a piece of code that retries when it fails with ExceptionOne , and if it continues to fail, it will throw a ExceptionTwo .我有一段代码在ExceptionOne失败时重试,如果它继续失败,它将抛出一个ExceptionTwo I want to test this behavior, but am not sure how to.我想测试这种行为,但不知道怎么做。

public void someMethod(String x) {
    boolean retry;
    int try = 0;
    do {
        retry = false;
        try {
             someFunction(x);
        } catch (ExceptionOne e) {
            if (try < 5) {
                retry = true;
                attempt++;
            } else {
                throw new ExceptionTwo();
            }
        }
    } while (retry);
    
}

private void someFunction(String x) {
    doSomething(); //This can throw ExceptionOne
}

Suppose these functions are inside a SomeClass .假设这些函数在SomeClass中。 I mocked SomeClass and tried something like我嘲笑了SomeClass并尝试了类似的东西

doThrow(new ExceptionOne()).doNothing().when(mockObject).someMethod(any())

for consecutive calls, but this isn't quite what I am looking for since I believe this is really testing the someMethod, not someFunction or the retry functionality.连续调用,但这并不是我想要的,因为我相信这确实是在测试 someMethod,而不是someFunction或重试功能。

How do you test something like this?你如何测试这样的东西? That is, how do I verify that the behavior that when someFunction fails with ExceptionOne, it will retry until it succeeds or until it runs out of retries and throws an ExceptionTwo?也就是说,我如何验证当someFunction因 ExceptionOne 失败时,它将重试直到成功或重试次数用完并抛出 ExceptionTwo 的行为?

I ended up scrapping my current retry logic and using an external library to do the retry instead.我最终放弃了我当前的重试逻辑并使用外部库来进行重试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM