navig8tr
navig8tr

Reputation: 1844

Mocking return with any passed argument

While trying to mock MavenXpp3Reader the read() method remains null despite my attempts to mock the return. Here is my attempt

    String testVer = "1.0.0.TEST";
    MavenXpp3Reader mockReader = mock(MavenXpp3Reader.class);
    Model mockModel = mock(Model.class);
    when(mockModel.getVersion()).thenReturn(testVer);
    when(mockReader.read(new FileReader("pom.xml"))).thenReturn(mockModel);

    Model model = mockReader.read(new FileReader("pom.xml"));

model remains null. Basically, I want to return mockModel whenever MavenXpp3Reader.read() is called, no matter what arguments are passed.

Upvotes: 2

Views: 359

Answers (2)

chmilevfa
chmilevfa

Reputation: 363

Try to use any() from Mockito framework instead of (new FileReader("pom.xml"))

For example:

import static org.mockito.ArgumentMatchers.any;

...
when(mockReader.read(any(Reader.class)).thenReturn(mockModel);
...

Upvotes: 2

davidxxx
davidxxx

Reputation: 131316

Basically, I want to return mockModel whenever MavenXpp3Reader.read() is called, no matter what arguments are passed.

You could use Mockito.any() in the mock recording but it will not compile because MavenXpp3Reader.read() is overloaded.
You should so specify the class matching to a specific overload :

when(mockReader.read(Mockito.any(Reader.class))).thenReturn(mockModel);

But in most of case you want to avoid any matcher because that is not strict enough.


About your mock recording :

when(mockReader.read(new FileReader("pom.xml"))).thenReturn(mockModel);

will not be used here :

Model model = mockReader.read(new FileReader("pom.xml"));

because the way which you specify the FileReader argument (without a soft argument matcher) makes Mockito to rely on the equals() method of the classes to consider the match and new FileReader("pom.xml").equals(new FileReader("pom.xml")) returns false as FileReader doesn't override equals().
But it will work :

FileReader reader = new FileReader("pom.xml")
when(mockReader.read(reader)).thenReturn(mockModel);
Model model = mockReader.read(reader);

Upvotes: 3

Related Questions