Reputation: 341
In my project I have a class SessionManager which sets and clears session variables for sticky forms etc. Every method in that class takes in a Silex\Application object as parameter. How can I unit test these methods? Create a Silex application object in each test method? I'm new to Silex and unit testing so and not sure how to handle this.
Example of one method:
public static function setMessage($message, $messageClass, Application &$app)
{
// store message as array, with content and class keys
$app['session']->set('message', array(
'content' => $message,
'class' => $messageClass
));
}
Upvotes: 1
Views: 626
Reputation: 29870
Firstly I think that $app
should not be a dependency of your SessionManager; $app['session']
should be. But also it should be a dependency of the object (ie: passed to the constructor) not of the individual method.
But that doesn't change the tactic for solving the problem. All you need to do is create a mock of the Session, which covers the dependent method you need to call, eg:
// in your test class
// ...
public function setup(){
$mockedSession = $this->getMockedSession();
$this->sessionManager = new SessionManager($mockedSession);
}
public function testMessage(){
// test stuff here
}
private function getMockedSession(){
$mockedSession = $this->getMockBuilder('\Symfony\Component\HttpFoundation\Session\Session')
->disableOriginalConstructor()
->setMethods(['set'])
->getMock();
$mockedSession->method('set')
->willReturn('something testable');
return $mockedSession;
}
You probably only need to test that your setMessage
method passes through its $message
and $messageClass
values to the mocked method: that's all it's doing. In this light you probably wanna have a ->with('message', [$testMessage, $testClass])
or something in your mock too. The exact implementation is down to how you want to test.
Upvotes: 3