简体   繁体   中英

Unit test for Runnable

I have the following code:

public class TypesEngine
{
@VisibleForTesting
void types(@NonNull final FindTypes findTypes, @NonNull final List<String> types)
{
    final ExecutorService executorService = Executors.newFixedThreadPool(TYPES_NUMBER_OF_THREADS);

    for (final String type : types)
    {
        executorService.execute(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    findTypes.getRelatedInformation(type);
                }
                catch (final TypeNotFound e)
                {
                    log.info(String
                        .format(
                            "Caught TypeNotFound for type [%s].",
                            type));
                }
            }
        });
    }
    executorService.shutdown();
 }
}

I tried to the following unit test:

@Test
public void test_Types() throws Exception
{
    final List<String> types = Lists.newArrayList("type1","type2","type3");

    doAnswer(new Answer() {
        @Override
        public Object answer(final InvocationOnMock invocation) throws Throwable {
            throw new TypeNotFound();
        }
    }).when(findTypes).getRelatedInformation(anyString());

    typesEngine.types(findTypes, types);

    for(final String type : types)
    {
        verify(findTypes, times(1)).getRelatedInformation(type);
    }
}

But it always gives me the error that the verify method on is not being called. But if I add a system.out.println I can see that the different types are being called.

It would be great if anyone could tell me how to write the following unit test.

I'm using Mockito for my unit tests.

You're verifying that findTypes has been called immediately after the tasks have been submitted to the executor. The executor hasn't had the time to execute its tasks yet.

Since you have no way with that design to block until the tasks have completed, you need to sleep long enough before verifying. A more reliable way of doing it would be to pass your executor service as argument, and call awaitTermination() to block until the executor is done, rather than sleeping.

Also, you can use doThrow() rather than doAnswer()

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