Search code examples
javajunitrunnable

Elegant solution for JUnit testing of run method in Thread implementation


I have a class that extends from Thread and want to JUnit test it. At this point I don't want to test for thread-safety, but to merely check whether the implementation logic works fine. My problem is that the run method iterates indefinitely, e.g.:

       public void run() {

        while (status.isRunning()) {

            // do stuff & sleep
        }
   }

For the purposes of my test, I only want to iterate over the logic in the run method once. The best I came up with to tackle this problem, is a Mockito mock object that uses a static counter and an anonymous implementation of Answer:

  private static int counter = 0;

  Status status = mock(Status.class);
        when(status.isRunning()).thenAnswer(new Answer<Boolean>() {
            public Boolean answer(InvocationOnMock invocation) throws Throwable {
                if (counter == 0) {
                    counter++;
                    return Boolean.TRUE;
                }
                return Boolean.FALSE;
            }
        });

I am not sure, whether this solution is the best there is. It seems a bit long-winded for a use case that common.

Can anybody think of a simpler, more elegant solution to the problem?


Solution

  • You don't need to do anything magical, just provide more than one "answer" in the "thenReturn" method, for example...

    when(status.isRunning()).thenReturn(true, false);