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

junit测试类的以下代码

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

junit测试类的以下代码

首先,我要做一些假设。

user.getUsername()
user.getPass()
无副作用的影响。该
System.out.println
是对你并不重要。

这样,您的课程就变成了:

public class Fortest {    Phone name = new Phone();    public String handleUser(User user) {        String ph = name.getA();        if(ph.equalsIgnoreCase("test")){ return "done";        }        return  "failed";    } }

因此,您的测试有两个条件。要么

phone.getA()
是“测试”,然后返回“完成”,要么不是,然后返回“失败”。

那么如何设置设置为“

getA
”。可以肯定的是,我们需要能够从测试中设置“名称”。为此,我们需要“注入”它(我们可以通过其他多种方式来实现它,但是我喜欢注入)。我会用Guice,许多人会用Spring。有些人会使用其他注入框架之一。但是在测试中,我们大多数人会使用手动注射。

public class Fortest {    Phone name;    Fortest(Phone name) {        this.name = name;    }    public String handleUser(User user) {        String ph = name.getA();        if(ph.equalsIgnoreCase("test")){ return "done";        }        return  "failed";    } }public class TestFortest {   @Before   public void before() {          name = ; //...subject = new Fortest(name);   }}

现在测试非常简单:

public void whenTestModeIsEnabledThenReturnDone() {     setPhoneIntoTestMode();     String actual = subject.handleUser(null);     assertEquals(actual, "done");}public void whenTestModeIsDisabledThenReturnFailed() {     setPhoneIntoLiveMode();     String actual = subject.handleUser(null);     assertEquals(actual, "failed");}

setPhoneIntoTestMode
/
的实现
setPhoneIntoLiveMode
取决于复杂
Phone
程度。如果它比我们要复杂的话,我们会以某种方式(模拟,存根等)看待它。这可能是您编写的代码块,也可能使用了Mocketo之类的工具。

如果Phone对象很简单,并且具有或可以具有“

setA
”方法,则只需使用该方法。

我相信以后你将需要

userdao
。届时将做同样的事情。注入并模拟/设置对象。



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

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

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