jeudi 23 juin 2016

How to spy on a Method that belongs to an object not accessible from outside?

I'm very new to Mockito and I have a situation for which I can't find a solution. There's a method that I want to test using Mockito. The problem is that inside this method, there's an object created and that object has a function that I want to mock.

So for example, here is a small sample code which illustrates my issue:

public class ClassA {

  public functionDoingDBStuff() {
    //...........
  }

}

public class ClassB {

  final ClassA classAObj = null;

  public functionXYZ() {

    classAObj = new ClassA();

    classAObj.functionDoingDBStuff();

  }
}


@Test MyTestFunction() {

  ClassB classBObj = new ClassB();

  // How to access and mock functionDoingDBStuff() here ???

}

So in MyTestFunction(), I want to test functionXYZ(), but mock the function functionDoingDBStuff() that is called inside functionXYZ(). By mock, I mean return a specific result that I want for the test. However function functionDoingDBStuff() belongs to an object that's created inside functionXYZ(), so I don't know how I can tell Mockito to access it from within MyTestFunction(). I hope you're able to understand what I mean.

Aucun commentaire:

Enregistrer un commentaire