0

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 ?

Mickäel A.
  • 9,012
  • 5
  • 54
  • 71
  • What have you tried so far? Also, please consider whether it's really necessary to call the static method, or whether an instance of `StaticClass` could be passed to class `A` instead. – SimonC Mar 02 '14 at 12:04

1 Answers1

0

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.

Avi
  • 21,182
  • 26
  • 82
  • 121