I am trying to write a test with stubbing but mocking one of the methods does not happen as expected.
class A {
public static getInstance(){
return new A();
}
public String getConn(){
return "Hello";
}
}
class B {
public String createConn(){
A instance = A.getInstance();
return instance.getConn();
}
}
My Test class:
@RunWith(PowerMockRunner.class)
@PrepareForTest(A.class)
public class TestClassB{
@Spy
B classB = new B();
@Test
public void testConn(){
PowerMockito.mockStatic(A.class);
given(A.getConn()).thenReturn("Welcome");
assertEquals("Welcome", classB.createConn());
}
I want to create a test on Class B, createConn
method, and when I get the connection, instead of "Hello", I want to receive "Welcome" using mockito?
I found the solution of the problem.
PowerMockito.mockStatic(A.class);
PropertyManager mock = PowerMockito.mock(A.class);
given(A.getInstance()).willReturn(mock);
given(mock.getConn()).willReturn("Welcome");
assertEquals("Welcome", classB.createConn());