2

I have to mock private field:

public class A{
    private final B b;
    public A(){
        this.b = new B(new OtherService)
    }

    public test(){
        int i = b.test()
        if(i == 0)
           b.test1()
        else
           b.test2()
    }
}

and I have to create unit tests for methods in this kind of class and I have to mock class B is it even possible here?

Mateusz Sobczak
  • 1,551
  • 8
  • 33
  • 67
  • generally if class members are private they are NOT subject to test, unless you have some sort of legacy software you can not change – injecteer Oct 29 '20 at 11:55
  • @injecteer unit tests I don't want to test other classes so is it possible to test it? – Mateusz Sobczak Oct 29 '20 at 11:58
  • 1
    show some example of the test you want to make – injecteer Oct 29 '20 at 12:03
  • @injecteer I added function which I want to test – Mateusz Sobczak Oct 29 '20 at 12:05
  • sorry, but it doesn't look like a test to me. Maybe as a debugging playground but definitely not a test. It looks like you are trying to test the mock, which is you know... – injecteer Oct 30 '20 at 00:05
  • I would appreciate feedback to my answer. You might want to accept it if you think the explanation is correct. Otherwise, feel free to ask follow-up questions by commenting. Thank you. – kriegaex Dec 13 '20 at 03:12

1 Answers1

2

Please read my remarks here and here or in many other questions of this kind I answered concerning dependency injection (DI). The lack thereof in your tightly coupled application design is what stops you from testing and refactoring effectively.

So go refactor! Make sure your class has a constructor or setter by which to inject the dependency (here: the instance of B you wish to mock).

If your member was not final, you could use a Groovy-ism, just using the known private member name in the constructor like A a = new A(b: Mock(B)) according to my answer here, but this is an ugly alternative to driving good application design with automated tests and decouple your classes. If any class is difficult to test, in many cases (also here) it does not mean your testing skills or tools need to get better but your application design is flawed.

kriegaex
  • 63,017
  • 15
  • 111
  • 202