开发者

How can I unit test this kind of code?

开发者 https://www.devze.com 2023-03-28 07:18 出处:网络
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.

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

精彩评论

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