如何模拟超级参考(在超级类上)?

How to mock super reference (on super class)?(如何模拟超级参考(在超级类上)?)
本文介绍了如何模拟超级参考(在超级类上)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

有时当我编写单元测试时,我应该模拟对超类的引用.

Sometimes when I write unit tests I should to mock reference to superclass.

我读过这个问题:问题

此答案answer with DI 建议重构代码.但我做不到

This answer answer with DI advice to refactor code. But I cannot it

如果超类方法足够大,则此答案另一个答案不适合.就我而言,我有非常大的代码.是的,我知道它违反了 SOLID OOD 原则,但我应该编写测试.我没有足够的时间进行重构.

this answer another answer is not suitable if superclass method is enough big. In my case I have very big code. Yes I know that it is brokes SOLID OOD principes but I just should to write test. I have not enough time for refactor.

该问题是 4 年前提出的!

said question was asked 4 years ago!

目前 Mockito 或 Powermock 是否可以解决此问题?

Does currently Mockito or Powermock can resolve this issue ?

代码示例:

class BaseService {  
    public void save() {
      // a lot of code here! I cannot change this code.
    }  
}

public Childservice extends BaseService {  
    public void save(){  
        //logic for testing
        super.save();
       //logic for testing
    }  
} 

更新 2

public class Parent {
    public int save() {
         return 99;
    }   
}

public class Child extends Parent {
    public int save() {
        int i = super.save();
        return i*2;
    }
}

和测试:

@RunWith(PowerMockRunner.class)
@PrepareForTest(Parent.class)
public class ParentTest {
    @Test
    public void testSave() {       
        PowerMockito.suppress(PowerMockito.methodsDeclaredIn(Parent.class));        
        System.out.println(new Child().save());
    }
}

输出:198

推荐答案

使用 Powermock 您可以替换或抑制方法,因此可以更改 BaseService.save() 完成的操作.您还可以使方法对抑制不做任何事情.您甚至可以抑制静态初始化程序块.

With Powermock you can replace or suppress methods, so it is possible to change the action done by BaseService.save(). You can also make methods to do nothing with suppressing. You can even suppress static initializer blocks.

请阅读 Powermock 作者的这篇博文.请参阅更换"一章.

Please read this blog entry of the Powermock authors. See chapter "Replacing".

更新:

抑制似乎对我有用,但替换不行.见下图:

Suppress seems to work for me, but replace not. See the picture below:

这篇关于如何模拟超级参考(在超级类上)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Show progress during FTP file upload in a java applet(在 Java 小程序中显示 FTP 文件上传期间的进度)
How to copy a file on the FTP server to a directory on the same server in Java?(java - 如何将FTP服务器上的文件复制到Java中同一服务器上的目录?)
FTP zip upload is corrupted sometimes(FTP zip 上传有时会损坏)
Enable logging in Apache Commons Net for FTP protocol(在 Apache Commons Net 中为 FTP 协议启用日志记录)
Checking file existence on FTP server(检查 FTP 服务器上的文件是否存在)
FtpClient storeFile always return False(FtpClient storeFile 总是返回 False)