EasyMock -- mock methods within tested class?

14,894

Solution 1

It sounds like you're looking for Partial Mocks... here's one blog post that covers them: http://www.jroller.com/alessiopace/entry/partial_mocks_with_easymock

This requires the EasyMock ClassExtension, which unfortunately can't mock private methods however.

Solution 2

This can be done with EasyMock 2.2 class extension, or EasyMock 3.0 and on (which includes class extension.)

Partial mocking is documented here:

http://www.easymock.org/EasyMock2_2_2_ClassExtension_Documentation.html

The syntax is fairly simple. You specify the class you're mocking and which methods you're mocking. In this example, imagine that the class is "Dog" and it has two methods, "eat" and "eatUntilFull". You might put this code in the eatUntilFull test:

mockDog = createMockBuilder(Dog.class).addMockedMethod("eat").createMock();

You can then treat that like any other mock.

Caveats:

1) Calling one method within your class from another might be an indication of poor design -- can you abstract out that logic to another class?

2) Even if you can't, there may be no problem in letting your method call another method itself during the test. This may be the preferred behavior.

3) You still can't target private methods, so you may want to set them as package-private instead of private.

Share:
14,894
Jeremy
Author by

Jeremy

Updated on June 13, 2022

Comments

  • Jeremy
    Jeremy almost 2 years

    In my code I sometimes call public or private methods within the same class. These methods aren't a good candidate for being pulled out into their own class. Each of these methods that I call are tested in their own unit test.

    So, if I have a method in my class A that calls each of those methods also in class A, is there some way to mock the calls? I can certainly cut and paste my expectations/mock behavior, but not only is that tedious, it obfuscates the point of the test, violates modularity, and makes testing more difficulty because of the inability to control what is returned.

    If not, what is the usual solution to this kind of thing?