且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

以下代码的junit测试类

更新时间:2023-11-19 23:35:52

首先我要做一些假设.user.getUsername() &user.getPass() 没有副作用.System.out.println 对您来说并不重要.

First I'm going to make some assumptions. user.getUsername() & user.getPass() have no side affects. The System.out.println are not important to you.

这样你的类就变成了:

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() 要么是test",然后返回done",要么不是,返回failed".

So your test has two conditions. Either phone.getA() is "test" and you return "done" or it is not and you return "failed".

那么如何设置getA".有一件事是肯定的,我们需要能够从测试中设置名称".为此,我们需要注入"它(我们可以通过多种其他方式进行操作,但我喜欢注入).我会使用 Guice,很多人会使用 Spring.有些人会使用其他注入框架之一.但是在测试中,我们大多数人会使用手动注入.

So how to set set "getA". One thing is for sure, we will need to be able set "name" from the test. For that we need to "inject" it (we can do it a number of other ways, but I loves injection). I'd use Guice, many would use Spring. Some would use one of the other injection frameworks. But in the tests most of us would use manual injection.

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 之类的工具.

The implementation of setPhoneIntoTestMode/setPhoneIntoLiveMode will depend on how complex Phone is. If it is complex than we would look at "facking" it in some way (mocks, stubs, etc). This could be a chunk of code you write, it could be using a tool like Mocketo.

如果 Phone 对象很简单,并且有或可以有一个setA"方法,那么就使用它.

If the Phone object is simple, and has or can have a "setA" method, then just use that.

我相信以后你会需要userdao.到时候也会做同样的事情.注入和模拟/设置对象.

I'm sure later you will need userdao. The same thing will be done at that point. Inject and mock/setup the object.