user993797
user993797

Reputation: 145

Mockito mock with constructor parameter

I am using mockito 1.9.5 and wanting to test a class that i have posted on github.

The issue is that I need to mock the getStringFromExternalSources method.

MyClass code:

public class MyClass {

    String a,b,c;

    public MyClass(String a, String b, String c) {

        this.a = a;
        this.b =  b;
        this.c = c;
    }

    public String  executeLogic (String d) {

        return a + b + c + d;
    }

    public String getStringFromExternalSources (){
        return "i got it from some place else";
    }

}

My current test:

@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {


    @Test
    public void MyClassTest() {

        MyClass mc = Mockito.spy(new MyClass("a","b","c") );

        Mockito.doReturn("mock").when(mc.executeLogic("real"));

        Mockito.doReturn("externalString").when(mc.getStringFromExternalSources());

        System.out.println(mc.executeLogic("real"));

    }

}

Any pointers ?

Upvotes: 5

Views: 31537

Answers (2)

NIPHIN
NIPHIN

Reputation: 1081

You can mock any method using when().thenReturn() construct.

Example:

    MyClass mc = Mockito.spy(new MyClass("a","b","c"));

    when(mc.getStringFromExternalSource()).thenReturn("I got it from there!!");

So whenever the method 'getStringFromExternalSource()' is invoked for the mocked object mc then it will return "I got it from there!!".

if you want to Test class with different parameters then you can use @Parameters annotation to provide parameters to the class in conjunction with Parameterized runner and mention the parameters in a public static method with @Paramters annotation. A rough example would be:

 @RunWith(Parameterized.class)
 class SomeTestClass{

    @Mock
    SomeTestClass mSomeTestClassInstance;

    @Parameters
    public static Object provideParameters() {
        Object[] objects =   new Object[]{
                0,
                0,
                2
        };
      return objects;
    }
    public SomeTestClass(Object argument1){
    mArgument1 = argument1; 
    }

    @Test
    public void testSomeMethod{
     Object returnValue = mSomeTestClassInstance.testSomeMethod(mArgument1);
     assertequals(mArgument1,returnValue)
    }
}

Upvotes: 3

Dherik
Dherik

Reputation: 19060

How to mock getStringFromExternalSources method:

public class MyClassTest {

    @Test
    public void MyClassTest() {

        MyClass mc = mock(MyClass.class);
        when(mc.executeLogic("real").thenReturn("mock");
        when(mc.getStringFromExternalSources().thenReturn("externalString");

        System.out.println(mc.executeLogic("real"));
    }

}

Upvotes: 0

Related Questions