4

So I have three classes: A, B, C. I need to write unit tests for class A.

  class A extends B{
   //fields go here ...

   public A(String string, ...){
      super.(string,...);
   }
   //other methods here ...
 }

 class B{
   C stuff;
   //other stuff
 }

So C is an important resource (like JDBC or ssh Session). Naturally, I am mocking C. How do I mock B. Imagine B has many children classes that extends it.

My main problem is that A is calling super.(...). I don't want to inject methods into A just for testing. To me that's bad design. Any ideas how to mock the parent?

For example I cannot do class MockB extends B{...} and then try MockB obj = new A(); This would not work because both MockB and A would be children of B.

4

2 回答 2

10

您真的不应该尝试模拟被测类的超类。虽然一些模拟框架允许“部分模拟”,这可能使部分模拟您实际测试的类成为可能,但这是一个坏主意。

如果类和和A之间的关系足够复杂以至于您认为您需要它,那么它们可能根本不应该处于继承关系中。AB

考虑更改您的代码,以便B委托A而不是扩展它。

于 2012-07-23T00:01:50.587 回答
3

你想模拟 B 类,这意味着你可能没有测试 B 或 A。所以你为什么关心它是否调用 super、foo、bar 或其他方法?你知道jdbc调用了多少方法吗?但正如你所说,嘲笑它没有问题。同样在这里。你只是做

B mockOfB = Mockito.mock(B.class);

而已。你有一个 B 的模拟,你可以测试你喜欢的任何调用。

如果您正在测试 A 那么为什么不能简单地实例化它呢?B 的构造函数是否需要一些静态依赖项?在这种情况下,您应该重构它或使用类似 powermock 的东西(如果您真的无法重构该类)。如果你不能实例化 B 因为它是抽象的,那么只需在你的测试中扩展它

于 2012-07-22T23:47:33.620 回答