mercredi 6 mai 2015

Mock Local variable of inner class - using mockito / powermock

I m trying to mock local variable of an innerclass(Class2.class), but it is not working. I am sharing my code below please help me to run the second testCase.

Class1.java which contain Class2 as inner class

public final class Class1 {

    Class2 class2 = new Class2();

    public String echoString(String s) {
        return class2.echoString2(s);
    }

    public class Class2 {

        public String echoString2(String s) {
            Class3 class3 = new Class3(null);
            System.out.println("######## Class3 = " + class3);
            return class3.getResult(s);
        }
    }
}

Class3.java

public class Class3 {
    private String data;

    public Class3(String data){
        this.data=data;
    }

    public String getResult(String s) {
        return data;
    }
}

Below is my TestNG test cases i want to run the second test case- pLease help

@PrepareForTest({ Class1.class, Class2.class, Class3.class })
public class MockTest extends PowerMockTestCase {
    String testInput = "input";
    String mockedResult = "Mocked - " + testInput;

    @InjectMocks
    private Class1 tested;

    @Mock
    Class2 tested2;

    @BeforeMethod
    public void InjectingMocks() {
        MockitoAnnotations.initMocks(this); // Creates a fresh set of mocks
    }

    @Test
    public void mockTest() {

        PowerMockito.doReturn(mockedResult).when(tested2)
                .echoString2(testInput);

        Assert.assertEquals(tested.echoString(testInput), mockedResult);
    }

    @Test
    public void mockTest2() throws Exception {
        Class3 c3 = PowerMockito.mock(Class3.class);

        PowerMockito.whenNew(Class3.class).withAnyArguments().thenReturn(c3);

        PowerMockito.doReturn(mockedResult).when(c3).getResult(testInput);

        Assert.assertEquals(tested.echoString(testInput), mockedResult);
    }
}

It is showing error

PASSED: mockTest
FAILED: mockTest2
java.lang.AssertionError: expected [Mocked - input] but found [null]

Please help - how would i run it successfully without making any major change to actual Code.

Aucun commentaire:

Enregistrer un commentaire