Not all code is worth unit testing. This is usually an indication that your code can be simplified. When you are unit test code, which is somewhat complex, tests can become a burden, and as a general rule, it would be better to integrate the test from edge to edge in these cases. It is also unclear in your example how your class receives RequestStack , so I assume it was introduced in __construct .
With that said here, how you will test this code:
protected function setUp() { $this->requestStack = $this->getMock('Fully-qualified RequestStack namespace'); $this->SUT = new MyClass($this->requestStack); } public function it_should_store_value_in_the_session() { $value = 'test value'; $request = $this->getMock('Request'); $request->request = $this->getMock('ParameterBag'); $session = $this->getMock('Session'); $this->requestStack ->expects($this->atLeastOnce()) ->method('getCurrentRequest') ->will($this->returnValue()); $request->request ->expects($this->atLeastOnce()) ->method('get') ->with('something') ->will($this->returnValue($value)); $request ->expects($this->once()) ->method('getSession') ->will($this->returnValue($session)); $session ->expects($this->once()) ->method('set') ->with('somevar', $value); $this->SUT->doSomething(); }
This should give you a starting point, but be careful that you have bullying in your tests, because very small changes in the implementation details may cause your tests to fail, even if the behavior is still correct, and this is something you want to avoid as much as it is possible that the tests are not worth supporting.
Edit: I thought a little about your question and realized that you can usually introduce a session as a dependency. If possible in your use case, this will simplify the tests.
Kevin archer
source share