模拟类的非静态方法

huangapple go评论89阅读模式
英文:

Mock non static method of a class

问题

我正在尝试编写一个使用存根的测试但是对其中一个方法进行模拟并未如预期般发生

```java
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();
 }
}

我的测试类:

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

我想要对类B的createConn方法创建一个测试,当我获取连接时,我希望使用mockito而不是收到“Hello”,而是收到“Welcome”?


<details>
<summary>英文:</summary>

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(&quot;Welcome&quot;);  
          assertEquals(&quot;Welcome&quot;, classB.createConn()); 
      }

I want to create a test on Class B, `createConn` method, and when I get the connection, instead of &quot;Hello&quot;, I want to receive &quot;Welcome&quot; using mockito?


</details>


# 答案1
**得分**: 0

我找到了这个问题的解决方法。

      PowerMockito.mockStatic(A.class);
      PropertyManager mock = PowerMockito.mock(A.class);
      given(A.getInstance()).willReturn(mock);
      given(mock.getConn()).willReturn("Welcome");
      assertEquals("Welcome", classB.createConn());

<details>
<summary>英文:</summary>

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(&quot;Welcome&quot;);
      assertEquals(&quot;Welcome&quot;, classB.createConn()); 


</details>



huangapple
  • 本文由 发表于 2020年9月18日 17:58:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/63953526.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定