0

I wish to unit test classes that contain fields. Because of the fact that it is unit tests, all dependencies should be mocked. Let's say that I have the classes

public class A {
   public B b = new B();
}
public class B {
}

How would you mock public/private class fields? Like when unit testing some method in A hat uses b, you would have to mock B to test the class in isolation from its real dependencies - but how?

  • from a design perspective class A should be refactored to explicitly depend on B via constructor injection. Also class A should depend on abstractions rather than concrete implementations. following a SOLID design would make testing and maintaining class A easier. – Nkosi Jun 15 '19 at 22:59
  • Okay so lets say that `b` was set via a constructor. However, would you ever do that for *all* fields? I have never seen it - the constructor would also be very ugly I think :) –  Jun 15 '19 at 23:01
  • 1
    See https://stackoverflow.com/a/2420245/173303. If your class has that many fields, that's a good hint that your class is trying to do too much. – nlawalker Jun 15 '19 at 23:03
  • @Dip This might be an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – Nkosi Jun 15 '19 at 23:10
  • before you can even start thinking about unit testing, you need to get your code in a testable state. This means, no hard-coded dependencies. start with "Inversion of Control". – Andrei Dragotoniu Jun 16 '19 at 11:15
  • @Dip: Your statement that all dependencies have to be mocked because it is a unit-test indicates a misunderstanding, see https://stackoverflow.com/a/56102108/5747415. – Dirk Herrmann Jun 19 '19 at 21:40

0 Answers0