2

I am writing unit tests for a class which has a latch to block the execute method. Class structure is something like this :

class Sample {

    private CountDownLatch latch;

    public void execute(String data) {
        latch = new CountDownLatch(1);
        // business logic
        latch.await();
    }

    public void onSuccess(String data) {
        if (latch != null) {
            latch.countDown();
        }
    }

}

To test the execute method i have added mock for all dependencies, but since the latch is initialized in the execute method, I am unable to mock that. So to write the unit tests for this, do I need to spawn a new thread in the test to call the countdown on latch or is there any other way to test this ?

eeedev
  • 149
  • 9
  • 5
    Your Sample class is hard to test because is highly coupled with CountDownLatch class. Instead, you should pass the `latch` by constructor. If you need, create a new instance each time you call `execute` method, you can: 1) pass a factory to the Sample constructor or 2) pass a CountDownLatch instance in execute method, with data String – Héctor Feb 14 '18 at 12:45

0 Answers0