5

I am working with existing test cases that use EasyMock to mock a class. I overloaded a no-parameter method so that now a method exists to take a string. For example:

public class HelloClass {
   // This method always existed.
   public String methodHello() {
       ...
   }
   // This method is new; it overloads the methodHello() method.
   public String methodHello(String msg) {
       ...
   }
}

In the test class, the HelloClass is mocked. As a result, I added the overloaded method so that we have the declaration:

public static HelloClass mockHelloClass = createMockBuilder(HelloClass.class)
   .addMockedMethod("methodHello")
   .addMockedMethod("methodHello", String.class)
   .createMock();

However, the test cases fail when I run them. When I make the methodHello(String) method private then the test cases pass again.

Is EasyMock able to handle several overloaded methods being added to the createMockBuilder?

whyceewhite
  • 6,317
  • 7
  • 43
  • 51
  • I've done this plenty of times and have never had a problem. What is the error message you are getting after adding the overloaded method to the set of methods to be mocked? The full stack trace will certainly help. – mystarrocks Dec 19 '14 at 02:20

1 Answers1

6

I think you encountered this exception at runtime:

java.lang.RuntimeException: Ambiguous name: More than one method are named methodHello

Here's what your mock object should have looked like instead:

public static HelloClass mockHelloClass = createMockBuilder(HelloClass.class)
   .addMockedMethod("methodHello", new Class[]{}) // you got this one wrong
   .addMockedMethod("methodHello", String.class)
   .createMock();

You should clearly specify which methods you want to mock - adding a mocked method like

addMockedMethod("methodHello")

doesn't automatically mean you are talking about the overloaded variant that takes no parameters. This is how you represent it instead:

addMockedMethod("methodHello", new Class[]{})

mystarrocks
  • 4,040
  • 2
  • 36
  • 61