简体   繁体   中英

Mock non static method of a class

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()); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM