Reputation: 53
I have two classes:
public class Foo {
public int getInt(){
return 10;
}
}
public class Bar {
Foo testClass = new Foo();
public Foo getTestClass() {
return testClass;
}
public void setTestClass(Foo testClass) {
this.testClass = testClass;
}
public int get(){
return testClass.getInt();
}
}
And finally I have test class with mock for Foo:
public class TestClass {
Foo test;
@Before
public void init(){
test = Mockito.mock(Foo.class);
Mockito.when(test.getInt()).thenReturn(5);
}
@Test
public void tst(){
Bar t = new Bar();
Assert.assertEquals(t.get(), 5);
}
}
Could you tell me, why I'm getting 10 from t.get() although in mock "I say" that I want 5 ?
How can I write Mock to get mocking value?
Thanks in advance.
Upvotes: 0
Views: 49
Reputation: 1047
When you're writing :
public class TestClass {
Foo test;
@Before
public void init(){
test = Mockito.mock(Foo.class);
Mockito.when(test.getInt()).thenReturn(5);
}
@Test
public void tst(){
Bar t = new Bar();
Assert.assertEquals(t.get(), 5);
}
}
You are mocking your Foo
class, but not using it in the Bar
class. So if you call the return method, it won't send the result you tried to mock
Upvotes: 0
Reputation: 4536
You forgot to actually set your mock with a call to t.setTestClass(test);
.
Upvotes: 1