How to Unit test with Injector::inst()->get() in project code?

SilverStripe 4.4

I am updating unit tests as part of an ss3 to ss4 upgrade project. In one of my SapphireTest test cases, the test calls a static function (in the project code) that contains:

$session = Injector::inst()->get(HTTPRequest::class)->getSession();

And I get the following error when I run the test:

ArgumentCountError: Too few arguments to function SilverStripe\Control\HTTPRequest::__construct(), 0 passed and at least 2 expected

What can I do? Best case is to not modify the project code. Changing the test class to FunctionalTest would not help because these tests need $fixture_file and having a $fixture_file in a FunctionalTest doesn’t work.


It looks like Injector tries to create a new HTTPRequest on the fly, because it cannot find it in the container. When it does so, it uses constructor of the class with no parameters, that’s where the error comes from. As a workaround you could create a mock of HTTPRequest and register it in setUp of your test case.