Search code examples
javaunit-testingeasymock

Using EasyMock to test a method that constructs another object


I have a method like this:

public void MyMethod(int p1, int p2) {
  //some logic here
  MyObject mo = new MyObject(var1,var2);
  int returnedId = mo.doOperation(something);
  //Do something with the returnedId;
}

I want to test this method but I can't mock the constructor call, so a test around this would break modularity. I could do it with a factory method or something but since I only have one constructor there is no point.

How is this generally done using EasyMock?


Solution

  • You can't do that with EasyMock only. But there are workaround solutions, like using PowerMock as an extension to EasyMock, so that you can mock static methods, constructor calls, final methods etc.

    But before doing that, analyze your problem carefully. Do you really need to create MyObject inside MyMethod? In general, it is far better to design classes in a way that all its dependencies are passed in as constructor arguments or via setters. This is the pattern commonly called "dependency injection". By doing dependency injection, you avoid testability problems like the one you mentioned.

    Also, MyMethod could take MyObject as a parameter or it could be obtained by a factory, as Duncan Jones points out. Both solutions are usually better than mixing object instantiation with the application logic.