开发者

How can I unit test this kind of code?

Let's say I'm doing something like the following, and I want to test to make sure each Letter is getting initialized with the right $data.

public someMethod()
{
    for ($i = 0; $i < 5; $i++)
    {
        $letter = new Letter($data);
        $letter-&g开发者_运维百科t;send();
    }
}

The main problem I wanted to point out is there are 5 letters completely encapsulated in the someMethod() call. They never leave the scope of the method, so I can't test the return value, and there is more than one, so dependency injection doesn't seem to be an option.


Dependency injection is possible:

public someMethod($letterFactory)
{
    for ($i = 0; $i < 5; $i++)
    {
        $letter = $letterFactory->create($data);
        $letter->send();
    }
}

(Pseudo-code, because I'm not sure what language this is supposed to be.)

Your unit test can then provide a mock implementation of $letterFactory, which generates mock Letter objects.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜