0

It is easy to mock an interface method which is implemented by some class but if there is a class and having a static method than how we can mock it with the help of easymock??

supose the is a class A and having a void retrurned method as public static void methodA(some args..){}

    class A {
public static void methodA(//some args..){
//some logic
}
}

How we can mock A's method methodA with the help of EasyMock

1
  • Nope you can't. You'll need the help of some other libraries like the Powermock (can work in tandem with easymock). Jmockit is one great library that provides the static mocking feature among many others that make it arguably the best mocking library. Nov 19, 2014 at 12:00

1 Answer 1

0

As mystarrocks mentioned in the comment, you can mock static methods using PowerMock, even you can test final class/method and private methods too!

From the documentation:

PowerMock is a framework that extend other mock libraries such as EasyMock with more powerful capabilities. PowerMock uses a custom classloader and bytecode manipulation to enable mocking of static methods, constructors, final classes and methods, private methods, removal of static initializers and more.

For example:

public class IdGenerator {

   /**
    * @return A new ID based on the current time.
    */
   public static long generateNewId() {
      return System.currentTimeMillis();
   }
}

Then you can mock this static method using:

// This is the way to tell PowerMock to mock all static methods of a
// given class
mockStatic(IdGenerator.class);

/*
 * The static method call to IdGenerator.generateNewId() expectation.
 * This is why we need PowerMock.
 */
expect(IdGenerator.generateNewId()).andReturn(expectedId);

Check Mocking static methods for the complete example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.