mockito / mockito

Most popular Mocking framework for unit tests written in Java
http://mockito.org
MIT License
14.84k stars 2.55k forks source link

Ambiguous method call: Mockito.any(Class) vs. Matchers.any(Class) #1311

Closed alb-i986 closed 5 years ago

alb-i986 commented 6 years ago

A pretty common setup is to have JUnit + Hamcrest + Mockito altogether.

We also like to have static imports for Matchers, Assert and Mockito (or BDDMockito) classes, don't we?

import org.junit.Test;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;

public class MyDumbTest {

    private String mock = mock(String.class);

    @Test
    public void name() {
        given(mock.equalsIgnoreCase(any(String.class)))
                .willReturn(true);
        // ..
        assertThat("asd", containsString("asd"));
    }
}

Unfortunately this won't compile because of a naming collision between Mockito.any(Class) and org.hamcrest.Matchers.any(Class).

If we are lucky, we don't need to use both in our test class, so we can solve by adding an extra explicit import:

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;
import static org.mockito.BDDMockito.any;

Anyway, it would be nice to avoid the naming collision in the first place. So what about giving it a different name? I'd suggest anyObject(Class). Or anyObj(Class) (a little shorter).

BTW I see that the javadoc says it is an alias of isA(Class) but actually I see that their implementations are slightly different.

rodrigocprates commented 6 years ago

I get that using static imports make our code more readable, but if we think that every library shouldn't conflict on names we'd get on chaos. The problem comes when, for example, it changes to "anyObject(Class)" but another dev complains that it's conflicting the name with a lib that he is using, you know?

alb-i986 commented 6 years ago

True. But I think this is a special case, as hamcrest is referenced from the official documentation, e.g. http://static.javadoc.io/org.mockito/mockito-core/2.18.0/org/mockito/hamcrest/MockitoHamcrest.html

TimvdLippe commented 5 years ago

We don't plan to change this, as we deprecated support for Hamcrest. Moreover, this is an artifact of the *-import which is discouraged for these kind of clashes.