如何模拟超级引用(超类)?(How to mock super reference (on super class)?)

编程入门 行业动态 更新时间:2024-10-09 19:22:45
如何模拟超级引用(超类)?(How to mock super reference (on super class)?)

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

我读过这个问题: 问题

这个答案回答DI建议重构代码。 但我不能

如果超类方法足够大,这个答案另一个答案是不合适的。 在我的情况下,我有非常大的代码。 是的我知道它是SOLID OOD原则,但我应该写测试。 我没有足够的时间进行重构。

4年前问了这个问题!

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

更新

代码示例:

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; } }

update

code example:

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 } }

update 2

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

and test:

@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()); } }

output: 198

最满意答案

使用Powermock,您可以替换或抑制方法,因此可以更改BaseService.save()完成的操作。 您也可以使方法无法抑制。 您甚至可以抑制静态初始化程序块。

请阅读Powermock作者的博客文章 。 请参阅“更换”一章。

更新:

抑制似乎对我有用,但不是替换。 见下图: 在此处输入图像描述

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.

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

UPDATE:

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

更多推荐

本文发布于:2023-08-04 18:13:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1419231.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:super   mock   class   reference

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!