简体   繁体   中英

How to test this code in Phpunit

I am beginner in the testing. There is an application . Uses singelton (methods A :: getMainApp () that would return to the application). In the test class has a method :

protected function endApp ()
{
    $ logger = new MainLogger ();
    $ logger-> log ();

    $ this-> response-> send ();
    exit ( 0);
}

this method use two classes (MainLogger, ResponseManager ($ this-> response)), which in turn may use even other classes.

In this test, I do not need "to emulate and create " all the required classes ? I basically need to test what has been called log (), response-> send () and exit ( 0) They result I'll check when I tested separately by each class and when I test the application on the " browser level" Right?

How to verify that method were induced exactly the desired function in the right order? I understand that I can not use mock objects , because I use singelton ?

Thx.

Your problem is that your class is tightly coupled to MainLogger and ResponseManager you cannot mock them, so you cannot test your method in isolation. A little re-factoring is needed.

I don't know how your class is written, but you need to inject dependencies like this to make it testable. Passing them into the constructor is one way of doing it. That way you can pass in a mock object instead to allow testing.

Alternatively, you can pass dependencies into the method that needs them, like this for example:-

protected function endApp(MailLogger $logger)
{
    $ logger->log();

    $ this->response->send();
    exit(0);
}

On a side note; I'm not sure you want to exit() here as that stops your script completely, return would be more appropriate I think.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM