Question

I am using EasyMock in my JUnit tests. I want to mock a static method that is present in the parent class. For example :

Class A {
    public void testOne() {
        Map map = StaticClass.method();
        // using map code here ...
    }
}

Class B extends A {
    public void testTwo(){
        testOne();`
    }
}

Now, I am writing a JUnit test for class B and I want to mock StaticClass.method() in class A. How to implement this ?

No correct solution

OTHER TIPS

I'd suggest (by the order of my preferences):

  1. Wrap this with a concret implementation and mock the concreted class
  2. Use a protected method with and extend the class with a testable class
  3. Use PowerMock

Option 1 - Concrete implementation:

public class StaticClassWrapper() {
   public Map method() {
      return StaticClass.method();
   }
}

Option 2 - Testable class

public class A {
    public void testOne() {
       Map map = method();
    }

    protected Map method() {
      return StaticClass.method();
    }
}

In your tests you need to create TestableA and run the tests on it (instead of running tests on A):

public class TestableA {
    protected Map method() {
       // return a mock here
    }
}

Your last (and least favorite) option is to use PowerMock. It can work with EasyMock in order to mock static calls.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top