简体   繁体   English

如何使用 mockito / powermockito 使实例化的依赖 class 在特定方法调用上引发异常

[英]How to use mockito / powermockito to make an instantiated dependent class throw an exception on a specific method call

This is the code I want to test.这是我要测试的代码。 It's pretty straight forward这很简单

  class FileHandler {
    public boolean deleteFiles(String path) {
      // mock this to throw an exception
    }
    public static FileHandler instatiateNew(String location) {
      // creates a FileHandler
    }
  }

  class B {
    public void action {
      try {
        FileHandler x = FileHandler.instantiateNew("asd");
        x.deleteFiles();
      } catch (Exception e) {
        // untested code I want to reach
      }
    }
  }

I now want to test method action and see how it handles x.deleteFiles() throwing an exception.我现在想测试方法action ,看看它如何处理 x.deleteFiles() 抛出异常。 I have tried doThrow, thenThrow and ran into errors (NullPointerException, probably because I stubbed the method wrongly) or the method not throwing the exception in the end.我试过doThrow,thenThrow并遇到错误(NullPointerException,可能是因为我错误地存根方法)或者方法最终没有抛出异常。

I am also confused whether I need Powermockito or not.我也很困惑是否需要 Powermockito。 I will now try an approach, where I mock the whole FileHandler class.我现在将尝试一种方法,在其中模拟整个 FileHandler class。 As I need to mock the static instantiation method I will need PowerMock for that.因为我需要模拟 static 实例化方法,所以我需要 PowerMock。 But I would prefer a less heavy handed solution.但我更喜欢不那么笨拙的解决方案。 Does it exist?它存在吗?

my partial class mock is now:我的部分 class 模拟现在是:

FileHandler mockHandler = Mockito.mock(FileHandler.class)
Mockito.mock(mockHandler.deleteFiles(Mockito.anyString()).thenThrow(Exception.class);
PowerMockito.mockStatic(FileHandler.class);
PowerMockito.when(FileHandler.instantiateNew(Mockito.anyString())).thenReturn(mockHandler())

Which is still causing issues, maybe becasue FileHandler is used elsewhere and mockStatic kills all other usages.这仍然会导致问题,可能是因为 FileHandler 在其他地方使用,而 mockStatic 会杀死所有其他用法。

Make sure all the necessary members are properly arranged so that the test can be exercised.确保正确安排所有必要的成员,以便可以进行测试。

For example例如

RunWith(PowerMockRunner.class)
@PrepareForTest({FileHandler.class})
public class MyTestCase {
    public void testdeleteFilesErrorHandling() throws Exception {
        //Arrange
        //instance mock
        FileHandler handler = Mockito.mock(FileHandler.class);
        Mockito.when(handler.deleteFiles(anyString())).thenThrow(new Exception("error message"));
        //mock static call
        PowerMockito.mockStatic(FileHandler.class);
        Mockito.when(FileHandler.instantiateNew(anyString())).thenReturn(handler);
        
        B subject = new B();
        
        //Act
        subject.action();
        
        //Assert
        //perform assertion
    }
}

Reference: Using PowerMock with Mockito参考: 将 PowerMock 与 Mockito 一起使用

using mockStatic was not an option for me as FileHandler was used in setup and teardown of the tests and this heavy handed approach would cause problems.使用 mockStatic 对我来说不是一个选项,因为FileHandler用于测试的设置和拆卸,这种笨拙的方法会导致问题。

What saved me where stub and method from org.powermock.api.support.membermodification.MemberModifier .是什么从org.powermock.api.support.membermodification.MemberModifier中拯救了我的stubmethod

FileHandler mock = Mockito.mock(FileHandler.class);
Mockito.when(mock.deleteFiles(anyString()))
    .thenThrow(Exception.class);

stub(method(FileHandler.class, "instantiateNew", String.class)).toReturn(mock);

Note that it is necessary to prepare class FileHandler through a test class decorator and to use the PowerMockRunner.请注意,有必要通过测试 class 装饰器准备 class FileHandler并使用 PowerMockRunner。 This is necessary as we are stubbing a static method on FileHandler.这是必要的,因为我们在 FileHandler 上存根 static 方法。 This is done so:这是这样做的:

@PrepareForTest({FileHandler.class})
@RunWith(PowerMockRunner.class)
public class MyTest extends MyBaseTestClass {
    @Test
    public void myTest() {
        // write test code from above here.
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在调用void方法时使用PowerMock / PowerMockito / Mockito抛出异常? - How to throw exception using PowerMock/PowerMockito/Mockito when a call to void method is made? Mockito:如何使服务调用引发异常 - Mockito: How to make the service call throw exception 如何使用junit和Mockito使用私有方法测试以下类,这里我不能使用powermockito进行私有方法调用 - how to test the following class with private methods using junit and Mockito, here i cannot use powermockito for private method call 使用Mockito / PowerMockito来模拟超类的公共方法 - Use Mockito/PowerMockito to mock a public method of super class 如何使用mockito / powermockito模拟内部方法调用 - how to mock internal method call using mockito/powermockito 使用 Mockito 是否可以在没有有效匹配器时在方法调用上抛出异常 - Using Mockito is there a way to throw an exception on method call when there are no valid matchers PowerMockito:模拟私有方法以抛出私有类 - PowerMockito: mock private method to throw private class 如何覆盖在 Mockito Junit 中的方法内实例化的类? - How to cover the Class instantiated inside a method in Mockito Junit? PowerMockito如何在构造函数调用时引发异常 - PowerMockito how to throw exception on constructor calling 如何使用PowerMockito捕获/引发异常 - How to catch/throw exception using PowerMockito
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM