kioli
kioli

Reputation: 735

Properly test static method in Android

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

Answers (1)

David Rawson
David Rawson

Reputation: 21487

The solution is to:

  1. Wrap your static utilities class in a mockable object.
  2. Instead of calling the static utils in the system under test (SUT), pass a dependency on the wrapped class.
  3. Call the constructor for the SUT with a mocked wrapped class in the @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

Related Questions