简体   繁体   中英

Is there any test framework or any other way to test async methods in Java?

I have a bunch of async functions in java that I want to test. I would like to have a functionality where the main thread waits until all the tests are done. The method signature of these functions looks like as follows

public class Callback {
    public void onSucess(Result result) {
        return result.getLastName(); 
    }
}

public class client{

    public static void getLastNameAsync(String firstname, Callback cb);

    public static void getLastNameAsync(String middlename, Callback cb);
    ...................................
    ...................................
    ...................................
    Imagine there are more functions like this 
}

I want to be be able to test the client class as follows

    public void TestClient(){
        Client client = new Client();
        client.getLastNameAsync("Brandon", new callback());
        client.getLastNameAsync("kyle", new callback());
        ....................
        ....................
        ....................

        Imagine I have to test more functions like this
    }

countDownLatch seems to be a solution however I need to know the number of method calls I am invoking and even if I do that seems to be a hacky solution because I need to instantiate as below

CountDownLatch latch = new CountDownLatch(#number of methods calls in my TestClient);
The trick again here is knowing #number of methods calls in my TestClient

open to any kind of advice or solution.

Static methods are not your friend. I would use instance classes, and then use an Executor as the means to control whether the execution is synchronous or asynchronous.

For your production code, inject a ThreadPoolExecutor in order for your logic to defer to another thread (or threads). But, in your test case, use a DirectExecutor to execute the logic in the same thread. See the javadoc for java.util.concurrent.Executor

This way, your test code will be far simpler. I'm sure you want to test the logic being called. If you need to test the multi-threadedness of it, you can then start to approach that as well. But if you don't have to, then keeping things simple will help in the test. And static methods don't help with that.

是的,这就是创建ConcurrentUnit的目的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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