mardi 5 juillet 2016

Mock static using powermockito using whenNew()

Code sample :

public class A{

    public static B connectA(){
        B b = new B();
        return b;
    }

    public void A(){
       B b = connectA();
    }
}



public class B{

  public B(String A){
     //does something
  }

}

So, now if i am testing method "A", :

  1. when it calls "connectA() method", i want it to return a mocked object that i want

OR

  1. when "new B" is called i want it to return a mocked object i want

it works if the connectA() method is not static, but i dont know how to make it work if its static using powermockito and mockito

so test class would be somethinng like:

@RunWith(PowerMockRunner.class)
@PrepareForTest({A.class,B.class})
public class ATest(){
    public void testMethodA(){
       PowerMockito.whenNew(B.class).withAnyArguments().thenReturn(BMock);
       A a = new A();
    }
 }

where BMock is any object i create!

Any possible solutions ?

Aucun commentaire:

Enregistrer un commentaire