Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override a method in unit tests that is called from which the class being tested

I am testing a class A's function func1.

Func1 has a local variable of Class B and calls B's function func2. Code looks something like this:

public Class A
{
    public func1()
    {
       B object = new B();
       int x = object.func2(something);
    }
}

When I am testing func1 in its unit tests, I don't want func2 to get called.

So I am trying to do something like this in the test:

B textObject = new B()
{
   @override
   int func2(something)
   {
      return 5;
   }
}

But it is still calling the func2 in the class B. Please suggest how to handle this.

like image 402
Khawar Ali Avatar asked Oct 27 '25 03:10

Khawar Ali


1 Answers

If you want to override the new B() constructor call - place it in an own method.

public Class A
{

    public func1()
    {
       B object = newB();
       int x = object.func2(something);
    }

    protected B newB(){
        return new B();
    }
}

In your test you can then override the B constructor call.

public class APartitialMock extends A {

   protected B newB(){
      return new BMock();
   }
}

public class BMock extends B {

    int func2(something) {
        return 5
    }

}

Then use APartitialMock to test the func1 with your kind of B.

PS If you can or want to use a framework take a look at powermock - Mock Constructor

like image 97
René Link Avatar answered Oct 29 '25 19:10

René Link