6

在我的代码中,我有时会在同一个类中调用公共或私有方法。这些方法不适合被拉到自己的类中。我调用的这些方法中的每一个都在它们自己的单元测试中进行了测试。

那么,如果我的类 A 中有一个方法调用类 A 中的每个方法,是否有某种方法可以模拟调用?我当然可以剪切和粘贴我的期望/模拟行为,但这不仅乏味,而且混淆了测试的重点,违反了模块化,并且由于无法控制返回的内容而使测试更加困难。

如果没有,这种事情的通常解决方案是什么?

4

3 回答 3

2

听起来您正在寻找部分模拟......这是一篇涵盖它们的博客文章: http ://www.jroller.com/alessiopace/entry/partial_mocks_with_easymock

这需要 EasyMock ClassExtension,但遗憾的是它不能模拟私有方法。

于 2012-11-27T20:57:43.467 回答
1

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.

于 2012-11-27T22:28:15.110 回答
0

一般来说,如果您需要模拟私有方法(或您正在测试的同一类上的公共方法),您应该考虑将该方法中的代码移至另一个类。

从测试的角度来看,您正在测试的方法如何归档预期状态(无论它是否调用其他方法)应该是无关紧要的。重要的兴趣点应该是方法执行的状态变化,而不是它调用的方法。

于 2012-11-27T20:49:39.520 回答