英文:
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("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?
</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("Welcome");
assertEquals("Welcome", classB.createConn());
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论