Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 我可以使用PowerMockito模拟最终类中的静态方法和不同类中的非静态方法吗?_Unit Testing_Junit_Powermock - Fatal编程技术网

Unit testing 我可以使用PowerMockito模拟最终类中的静态方法和不同类中的非静态方法吗?

Unit testing 我可以使用PowerMockito模拟最终类中的静态方法和不同类中的非静态方法吗?,unit-testing,junit,powermock,Unit Testing,Junit,Powermock,我在最后一个类a中有一个静态方法,它调用类B中的非静态方法 我需要模拟A中的静态方法和B中的非静态方法来添加单元测试。PowerMock有这样的解决方案吗?您应该使用PowerMock在a中模拟静态方法,在B中模拟非静态方法。在I中,两者都有: AccountManager上的模拟获取静态方法 帐户管理器上的模拟getAccounts方法 更清楚地说,对于静态模拟: 将@RunWith(PowerMockRunner.class)添加到测试类 将@PrepareForTest(A.class

我在最后一个类a中有一个静态方法,它调用类B中的非静态方法


我需要模拟A中的静态方法和B中的非静态方法来添加单元测试。PowerMock有这样的解决方案吗?

您应该使用PowerMock在a中模拟静态方法,在B中模拟非静态方法。在I中,两者都有:

  • AccountManager上的模拟获取静态方法
  • 帐户管理器上的模拟getAccounts方法
更清楚地说,对于静态模拟:

  • 将@RunWith(PowerMockRunner.class)添加到测试类
  • 将@PrepareForTest(A.class)添加到测试类中
  • 调用PowerMockito.mockStatic(AccountManager.class)
  • 存根行为使用when(A.method(any(Param.class)).thenReturn(value) 对于非静态模拟:

  • 添加模拟字段@mock B accountManager
  • 在@Before注释的方法MockitoAnnotations.initMocks(this)中初始化mock
  • (B.method())时的存根行为。然后返回(值) 可能需要在A类上配置B对象。在这个例子中,我在get方法中这样做。在你的情况下,它可能是不同的,你必须找出如何做到这一点


    注意。

    在B中模拟方法的必要性是什么?您可以让静态方法A的模拟来完成执行过程中所需的一切。