Reputation: 735
I am trying to test an Android app using the principle of
For this reason I wouldl ike to rely only on JUnit and Mockito for testing, not to risk abusing frameworks like PowerMockito
But I am at a stall when it comes to test the public method in a situation like this
public class ClassA {
public void publicMethod(String id) {
// something
privateMethod(id);
}
public void privateMethod(String id) {
// something
StaticClass.staticMethod(id);
}
}
Because here I can write a test for publicMethod, but then I face the questions
Upvotes: 2
Views: 418
Reputation: 21487
The solution is to:
@Before
method of your test.This conforms with the OOP principle of encapsulation (which BTW static classes can break). Example:
class WrappedStaticClass {
void wrappedStaticMethod() {
StaticClass.staticMethod();
}
}
Your refactored ClassA
now looks like this:
public class ClassA {
private final WrappedStaticClass wrappedStaticClass;
public ClassA(WrappedStaticClass wrappedStaticClass) {
this.wrappedStaticClass = wrappedStaticClass;
}
public void publicMethod(String id) {
// something
privateMethod(id);
}
private void privateMethod(String id) {
// something
wrappedStaticClass.wrappedStaticMethod(id);
}
}
Your test now looks like this:
@Mock WrappedStaticClass mockWrappedStaticClass;
//system under test
ClassA classA;
@Before
public void setUp() {
MockitoAnnotations.init(this);
classA = new ClassA(mockWrappedStaticClass);
}
@Test
public void testCallsWrappedStaticClass() {
//act
classA.publicMethod(1);
//assert
verify(mockWrappedStaticClass).wrappedStaticMethod();
}
Upvotes: 2