-1

I am having a class:

class A
{
    public void methodA()
    {
        new B().methodB("string");
        ----
        ----
    }
}


class B
{
    public void methodB(String s)
    {
        ---
        ---
    }
}

I need to write a mock, so that I can bypass call to methodB(), inside class A's methodA().

I tried doing:

//B b = PowerMockito.spy(new B());
//PowerMockito.doNothing().when(b).methodB(null);

Also tried spying:

//B b = Mockito.spy(new B());
//Mockito.doNothing().when(b).methodB("dummy");

But nothing working, and the methodB(), is getting invoked in my unit test.

Yash Bansal
  • 402
  • 5
  • 10

2 Answers2

0

You could use AspectJ to intercept all calls to B.methodB() and choose whether or not to forward the call to the method.

Jason
  • 11,744
  • 3
  • 42
  • 46
  • Thanks Jason, for the response I am using junit and PowerMockito for the unit test cases, can it be done with the help of that – Yash Bansal Apr 01 '19 at 23:44
0

Instead, use the inversion of control principle to pass the instance of B to either methodA or the constructor of class A. (If you want, you could also have a default constructor A() { this(new B()); }.) This will allow you to cleanly pass in a different instance (e.g., a mock) when desired and is a major technique for keeping coupling under control in programs of significant size.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
  • I thought so, but this is an old code, and modification needs a lot of change, so wanted to write test case without any modifications. – Yash Bansal Apr 02 '19 at 00:20
  • @YashBansal Then the best initial approach is to add a constructor that accepts a `B` and change the current constructor to a chained `this(new B())` call. Write your tests to the new constructor, deprecate the old one, and migrate your client code gradually. – chrylis -cautiouslyoptimistic- Apr 02 '19 at 00:32