简体   繁体   中英

JMockit, subclass referencing member of parent class directly

I'm new to JMockit and junit in general. 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.

Coming back to testing you're going to test B - which is A as well. You're trying to treat A as it was referenced by B - it's not. 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.

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.

The fact that you are referencing a field of A is really neither here nor there. A field of A is a field of B ...

So forget about 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() . I would favor the former, since X.somethingMoreSpecific() should have its own unit tests, but you can go either way.

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