Chiefwarpaint
Chiefwarpaint

Reputation: 673

Trouble With Mockito

I've started tinkering with Mockito today and have had quite the struggle and was hoping somebody could straighten me out.

Basically all I want to do is be able to verify that the 3 methods in my getName() method are called.

For some reason though in my test, whenever I hit this line:

Mockito.verify(mock).getPathObj();

I end up getting this error: "Wanted but not invoked: mock.getPathObj();"

Here is the class I wanna test

public class JavaFileInput {

private Path path;

public JavaFileInput(){
    super();
    this.path = null;
}

public Path getPathObj() {
    return this.path;
}

@Override
public String getName() {
    Path path = getPathObj(); //<--I realize I could just use my path member var here.  Added for troubleshooting.
    return path.getFileName().toString();
}
}

Here is my testing class

public class TestJavaFileInput {

@Mock(name = "path") private Path path;
@InjectMocks private JavaFileInput mock = Mockito.mock(JavaFileInput.class);

@Before
public void testSetup(){
    MockitoAnnotations.initMocks(this);
}

@Test
public void getNameTest(){
    mock.getName();
    Mockito.verify(mock).getName();
    Mockito.verify(mock).getPathObj();
}
}

Does anybody have some insight for me?

I have exhausted these resources, but I guess I could be easily overlooking something: http://www.vogella.com/tutorials/Mockito/article.html http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html#21

Upvotes: 1

Views: 519

Answers (3)

user3458
user3458

Reputation:

The unit test verifies how an object interacts with its environment, not with itself.

Inyour case, the environmwent is path.

Assuming that you can inject a Path mock into your object, you need to do this:

JavaFileInput input = new JavaFileInput();
when(path.getFileName()).thenReturn("xxx.txt");
// inject path into input somehow
assertEquals("xxx.txt", input.getName());

If you cannot inject path, that's a code smell. Consider redesigning.

Upvotes: 1

Makoto
Makoto

Reputation: 106430

First, you shouldn't be mocking the class that you want to test. Only mock external dependencies that you need.

Second, you need to specify behavior as to when that method is invoked. What should your Path instance return? This is where the mock comes in, as you need to decide what to return when getFileName() is invoked.

when(path.getFileName()).thenReturn(Paths.get("file://some/uri"));

Upvotes: 2

Serge Ballesta
Serge Ballesta

Reputation: 148900

Mockito only gives you mock objects. By default, calling any method on a mock does nothing at all. So when you call getName nothing happens and getPathObj is not called. You could try using a spy or callRealMethod but I've never use it because it seem to be not recommended (code smells ...) in mockito documentatin.

Upvotes: 1

Related Questions