2

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.

navig8tr
  • 1,724
  • 8
  • 31
  • 69
  • [Can Mockito stub a method without regard to the argument?](https://stackoverflow.com/questions/5969630/can-mockito-stub-a-method-without-regard-to-the-argument) – Slaw Aug 20 '18 at 20:52

2 Answers2

3

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);
davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • I think question about a bit different thing: **I want to return mockModel whenever MavenXpp3Reader.read() is called, no matter what arguments are passed** – chmilevfa Aug 20 '18 at 20:54
2

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);
...
chmilevfa
  • 343
  • 3
  • 8