栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Mockito:如何模拟JodaTime的界面

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Mockito:如何模拟JodaTime的界面

这是一个典型的测试案例,显示了设计中的潜在缺陷。您不能嘲笑,

JodaTime
因为您在被测类中对这些类有硬性依赖。

看一下SOLID原理以了解为什么这可能是个问题(尤其是在这种情况下是Dependency Inversion
Principle
)。如果您将

JodaTime
某个地方作为依赖项注入,那么在单元测试中,您可以根据需要用模拟,存根或间谍替换它的真实实例。

但是:

JodaTime
在生产环境中,无论使用寿命多长,这种东西极不可能注入其他任何东西。取而代之的是,在这种情况下,使用组合方法设计模式可能会更好。在这里,您将提取用于生成的任何计算/算法,并将其转换
printjobName
为另一种方法(由于您的代码段从未为该变量分配值,因此我在这里看不到如何做)。然后,您可以监视(部分模拟)您的被测类,以仅模拟该方法并返回固定值,而与
JodaTime
传递的实际日期时间无关,例如:

public class PrintProcessor {    ...    public String getPrintJobName(Shipper shipper) {        String printJobName = null;        String timeHash = this.getTimeHash();        if (this.isBeforeFourPM()) { switch(shipper) {     printJobName = // Do something with timeHash to generate name }        } else { ...        }        return printJobName;    }    public boolean isBeforeFourPM() {        return (jodaTime.getCurrentDateTimeEST().isBefore(jodaTime.getFourPM_EST()) || jodaTime.getCurrentDateTimeEST().isAfter(jodaTime.getSevenPM_EST()));    }    public String getTimeHash() {        ... // Do something to hash the time value in to a String    }}

现在您可以在测试中编写:

@Testpublic void testGetPrintJobNameBeforeFourPM() {    PrintProcessor concretePrintProcessor = new PrintProcessor();    PrintProcessor printProcessor = spy(concretePrintProcessor);    doReturn(true).when(printProcessor).isBeforeFourPM();    String printJobName = printProcessor.getPrintJobName(Shipper.X);    assertEquals("XNCRMNCF", printJobName);}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/435230.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号