Search code examples
javakotlinmockingmockitoros

Why does Mockito expects my verification method to be called with `Nothing`?


In my project I tried to setup a test in which should be verified that a method is called with a specific parameter. For this I am using Mockito and Kotlin.

In the test I am using a mock class. (publisher) This class is part of rosjava and contains a method publish;

public interface Publisher<T> extends TopicParticipant { //(java)
    void setLatchMode(boolean var1);

    boolean getLatchMode();

    T newMessage();

    void publish(T var1);

    boolean hasSubscribers();

    int getNumberOfSubscribers();

    void shutdown(long var1, TimeUnit var3);

    void shutdown();

    void addListener(PublisherListener<T> var1);
}

When I try to set my expectation like:

val publisherMock = mock(Publisher::class.java)

verify(publisherMock, atLeastOnce()).publish(message) // message is underlined with a red color

This does not compile and says that the parameter for publish should be of class Nothing!. Why is this?


Solution

  • That's because your Publisher class is generic. Creating mock with mock(Publisher::class.java) code creates Publisher<*> object (it means that type parameter is Nothing).

    To solve it you can't just place type parameter in mock creating code - Publisher<String>::class.java is not a valid code for Java or Kotlin.

    All you can do is unchecked cast:

    val publisherMock = mock(Publisher::class.java) as Publisher<String>
    

    If you need to disable warning from Android Studio just place @Suppress("UNCHECKED_CAST") line before that.