简体   繁体   中英

EasyMock — mock methods within tested class?

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?

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.

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.

Generally speaking, if you are facing the need to mock a private method (or a public method on the same class you're testing), you should really consider moving the code in this method to another class.

From the test's point of view, it should be of no interest how the method you are testing archives the expected state (whether it calls some other method or not). The essential point of interest should be the resulting change of state a method performs, not which methods it calls to do so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM