简体   繁体   English

JMockit,直接引用父类成员的子类

[英]JMockit, subclass referencing member of parent class directly

I'm new to JMockit and junit in general. 我是JMockit和junit的新手。 I am dealing with an example whereby a subclass is directly referencing a member of it's parent class (I know, not ideal, but this is what I've been handed). 我正在处理一个例子,其中一个子类直接引用它的父类的成员(我知道,这不是理想的,但这就是我所掌握的)。

ex: 例如:

public class A {
  protected Something X;
  public A() {
      X = new Something();
   }
}

public class B extends A {

  public void methodUnderTest() {
     X.somethingMoreSpecific();
  }
}

I've been able to mock parent class methods fine, but how do I deal with the class under test, referencing one of it's parent member objects directly? 我已经能够很好地模拟父类方法,但是我如何处理被测试的类,直接引用其中一个父成员对象?

Regarding the design your B referencing x (which is member) of A doesn't have to be wrong design - it depends on the context - but it's different topic. 关于设计你的B引用A(它是成员)的A不一定是错误的设计 - 它取决于上下文 - 但它是不同的主题。

Coming back to testing you're going to test B - which is A as well. 回到测试你将要测试B - 这也是A. You're trying to treat A as it was referenced by B - it's not. 你正试图对待A,因为它被B引用 - 但事实并非如此。 Maybe you should consider composition instead of inheritance here. 也许你应该考虑构成而不是继承。

As it is now you can test B and forget about A. If you have setter for X in A then you have setter for X in B (unless it's private) - you can use it. 现在你可以测试B而忘记A.如果你在A中设置了X,那么你在B中设置了X(除非它是私有的) - 你可以使用它。

What is not a good idea here is that you created X inside constructor with no args which made X tightly coupuled with A, and problably it is the reason your're trying to mock A. 这里不是一个好主意是你在没有args的情况下创建了X内部构造函数,这使得X与A紧密耦合,并且可能是你试图模拟A的原因。

The fact that you are referencing a field of A is really neither here nor there. 您引用A字段的事实实际上既不在这里也不在那里。 A field of A is a field of B ... 的场A是的场B ...

So forget about A . 所以忘了A You have two choices: you can mock X and just verify that B.methodUnderTest() calls X.somethingMoreSpecific() , or you can leave X alone and test that all the various things that X.somethingMoreSpecific() does happen when you call B.methodUnderTest() . 你有两个选择:你可以模拟X并且只是验证B.methodUnderTest()调用X.somethingMoreSpecific() ,或者你可以单独留下X并测试当你调用B.methodUnderTest()X.somethingMoreSpecific()发生的所有各种事情B.methodUnderTest() I would favor the former, since X.somethingMoreSpecific() should have its own unit tests, but you can go either way. 我赞成前者,因为X.somethingMoreSpecific()应该有自己的单元测试,但你可以采用任何一种方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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