【问题标题】:PowerMock whenNew does not return Mocked ObjectPowerMock whenNew 不返回模拟对象
【发布时间】:2021-04-22 17:52:20
【问题描述】:

尽管关注了多种不同的资源,但我无法让 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/ 相同,所以我不确定为什么它对我不起作用。

【问题讨论】:

    标签: java mocking mockito powermock powermockito


    【解决方案1】:
    @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());
        }
    }
    

    通常我会返回一个模拟对象。将 Point point = new Point(0,0) 替换为 Point point = PowerMockito.mock(Point.class)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-10
      • 1970-01-01
      相关资源
      最近更新 更多