mercredi 22 juin 2016

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.

Aucun commentaire:

Enregistrer un commentaire