Reputation: 31
I am new to Android unit testing and I am using Mockito to do it.
I want to test my method which has a method from another class. I want to stub that method so that it should not be called. I am using doReturn().when()
so that original method is not called but it is calling the original method.
Here is my code:
doReturn(true).when(myclass1mock).methodofclass1();
boolean a = myclass1mock.methodofclass1(); //here it return true
class2spy.methodofclass2(anyvalue);
The method I am testing is:
public class2 {
public void methodofclass2(Value) {
boolean value = class1.methodofclass1(); //here I don't want to call this method
}
}
The problem is method of class1
is called everytime. I want something so that class1.methodofclass1()
is not called.
I am injecting using:
@Mock
class1 myclass1mock;
@InjectMocks
class2 myclass2;
@Before
public void setUp() {
myclass2 = new myclass2();
class2spy = Mockito.spy(myclass2);
}
Upvotes: 1
Views: 661
Reputation: 26492
As you want to test the behavior of Class2, then i think you mixed up the annotations. Also i would take advantage of @Spy
annotations rather that configuring it by hand:
@Spy
class1 myclass1Spy;
@InjectMocks
class2 myclass2;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
Also, do not try not to spy the class which is being under test (class2). Use the real implementation.
Upvotes: 1