mockito mock a constructor with parameter

Posted by Shengjie on Stack Overflow See other posts from Stack Overflow or by Shengjie
Published on 2012-11-13T16:17:10Z Indexed on 2012/11/14 11:00 UTC
Read the original article Hit count: 275

Filed under:
|
|
|

I have a class as below:

public class A {
    public A(String test) {
        bla bla bla
    }

    public String check() {
        bla bla bla
    }
}

The logic in the constructor A(String test) and check() are the things I am trying to mock. I want any calls like: new A($$$any string$$$).check() returns a dummy string "test".

I tried:

 A a = mock(A.class); 
 when(a.check()).thenReturn("test");

 String test = a.check(); // to this point, everything works. test shows as "tests"

 whenNew(A.class).withArguments(Matchers.anyString()).thenReturn(rk);
 // also tried:
 //whenNew(A.class).withParameterTypes(String.class).withArguments(Matchers.anyString()).thenReturn(rk);

 new A("random string").check();  // this doesn't work

But it doesn't seem to be working. new A($$$any string$$$).check() is still going through the constructor logic instead of fetch the mocked object of A.

© Stack Overflow or respective owner

Related posts about junit

Related posts about mocking