添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
  • 使用 PowerMockito
  • PowerMockito 是一个 Mockito 的扩展库,可以用于模拟私有方法的调用。您可以使用 PowerMockito.when() 方法来模拟私有方法的调用,如下所示:

    @RunWith(PowerMockRunner.class)
    @PrepareForTest(YourClass.class)
    public class YourTestClass {
        @Test
        public void test() throws Exception {
            YourClass yourClass = PowerMockito.spy(new YourClass());
            PowerMockito.doNothing().when(yourClass, "yourPrivateMethod");
            yourClass.yourPublicMethod();
    

    使用 Java 反射机制可以获取类的私有方法并调用它。以下是一个示例:

    @Test
    public void test() throws Exception {
        YourClass yourClass = new YourClass();
        Method yourPrivateMethod = YourClass.class.getDeclaredMethod("yourPrivateMethod");
        yourPrivateMethod.setAccessible(true);
        yourPrivateMethod.invoke(yourClass);
        // test the behavior of the public method that calls the private method
        // ...
    

    在某些情况下,您可能需要重构代码以使私有方法成为公共方法,以便在测试中调用它。这可以通过将方法的可见性更改为公共方法来实现,如下所示:

    public class YourClass {
        public void yourPublicMethod() {
            // some logic here
            yourPrivateMethod();
            // some other logic here
        public void yourPrivateMethod() {
            // implementation here
    

    总之,使用 Mockito 模拟私有方法调用的方法有很多,具体取决于您的代码和测试需求。以上是其中的一些示例。

  •