Can we mock a method with powermockito and testng

76 views Asked by At

I am writing a TestNG testcase which extends atgdustcase. I need to mock a method in class B. This class B is injected into class A using properties file in ATG. Class C is a test class for testing functionality of class A. D is a test class which extends AtgDustCase.

@RunWith(PowerMockRunner.class)
@PrepareForTest({A.class, B.class})
Public class c extends D{
    @InjectGlobalComponent(Path for component A)
    @InjectMocks
    private A aClass;
    public void testMethod(){
        String string = "abc";
        Map map = new HashMap();
        map.put("a", "c");
        aClass = getRequest.resolveName(Component A path);
        B b = PowerMockito.mock(B.class);
        A a = PowerMockito.spy(new A());
        PowerMockito.whenNew(A.class).withNoArguments().thenReturn(a);
        a.setB(B);
        PowerMockito.when(a.getB()).thenReturn(b);
        Mockito.stub(b.getMethodToMock(string)).toReturn(map);
        Mockito.verify(b).getMethodToMock(string);
        aClass.invokeTestMethod();// This method calls the b.getMethodToMock()
    }
}

I need to mock getMethodToMock(). When I execute invokeTestMethod(), this calls getMethodToMock(). At that time, map should be returned. Instead it is executing getMethodToMock() and it is throwing an error(The problem with execution is I need to fetch some records from DB. I need to mock this method and return a map which contains information retrieved from DB). I am not sure whether mocking is happening properly or not, as in debug mode I am able to see that the getMethodToMock() is getting invoked. Please help me how can I mock this method and skip the execution of this method.

Note: I tried using Powermockito, but my testcase is TestNGsuite. I need to run TestNGSuite instead of running it as Junit.

0

There are 0 answers