PowerMock whenNew 不 return 模拟对象
PowerMock whenNew does not return Mocked Object
我无法让 PowerMock whenNew
工作,尽管遵循了多个不同的资源。这是我的例子:
public class MyClass {
public void foo() {
Point p = new Point(2, 3);
System.out.println(p);
}
}
我正在尝试将构造函数模拟为 Point
这样:
@RunWith(PowerMockRunner.class)
@PrepareForTest({MyClass.class})
public class MyClassTest {
public void testFoo() {
MyClass c = new MyClass();
PowerMockito.whenNew(Point.class).withAnyArguments().thenReturn(new Point(0, 0));
c.foo() // Still (2, 3) is printed instead of the mocked (0, 0)
}
}
我是不是做错了什么?我应该提到我在 gradle 项目中使用 PowerMock。这似乎与 https://automationrhapsody.com/mock-new-object-creation-powermock/ 相同,所以我不确定为什么它对我不起作用。
@RunWith(PowerMockRunner.class)
@PrepareForTest({MyClass.class})
public class MyClassTest {
@Test
public void testFoo() throws Exception {
//Arrange
MyClass c = new MyClass();
Point point = new Point(0,0);
PowerMockito.whenNew(Point.class).withAnyArguments().thenReturn(point);
//Act
c.foo();
//Assert
PowerMockito.verifyNew(Point.class).withArguments(anyInt(), anyInt());
}
}
通常我会 return 模拟对象。将 Point point = new Point(0,0) 替换为 Point point = PowerMockito.mock(Point.class)
我无法让 PowerMock whenNew
工作,尽管遵循了多个不同的资源。这是我的例子:
public class MyClass {
public void foo() {
Point p = new Point(2, 3);
System.out.println(p);
}
}
我正在尝试将构造函数模拟为 Point
这样:
@RunWith(PowerMockRunner.class)
@PrepareForTest({MyClass.class})
public class MyClassTest {
public void testFoo() {
MyClass c = new MyClass();
PowerMockito.whenNew(Point.class).withAnyArguments().thenReturn(new Point(0, 0));
c.foo() // Still (2, 3) is printed instead of the mocked (0, 0)
}
}
我是不是做错了什么?我应该提到我在 gradle 项目中使用 PowerMock。这似乎与 https://automationrhapsody.com/mock-new-object-creation-powermock/ 相同,所以我不确定为什么它对我不起作用。
@RunWith(PowerMockRunner.class)
@PrepareForTest({MyClass.class})
public class MyClassTest {
@Test
public void testFoo() throws Exception {
//Arrange
MyClass c = new MyClass();
Point point = new Point(0,0);
PowerMockito.whenNew(Point.class).withAnyArguments().thenReturn(point);
//Act
c.foo();
//Assert
PowerMockito.verifyNew(Point.class).withArguments(anyInt(), anyInt());
}
}
通常我会 return 模拟对象。将 Point point = new Point(0,0) 替换为 Point point = PowerMockito.mock(Point.class)