This class contains some logic about logged user and normally it's works, but when i run feature tests it's fails because in constructor of MyCustomStateClass i don't have access to logged user yet - Auth::user() is null. I pass to constructor Request and I check session $request->session() i get error: RuntimeException: Session store not set on request.
MyCustomStateClass is used mainly in Middlewares, and i call it by resolve() method.
Workaround for now is:
if (!$this->app->runningUnitTests()) { $this->app->singleton(MyCustomStateClass::class); }
and generally it works but i don't like to leave such conditions in my code. Any sugestions?
It could be one of two things, either your not actingAs() a user in your feature test prior to making your http request, for example:
/** @test */
public function it_checks_if_a_user_needs_to_be_onboarded()
{
...
$this->actingAs(
factory(User::class)->create()
);
$response = $this->get('/user');
...
}
Or, you could be injecting the wrong class into your MyCustomStateClass. If you using dependency injection make sure your resolving Illuminate\Auth\AuthManager and not Illuminate\Support\Facades\Auth, as the Auth facade actually resolves the AuthManager .
I've whipped up a working example with feature and unit tests for you to take a look at.
I forgot about one important things. My class is run multiple time and debug shows that Auth::user() is empty only when my class is resolved as the first time, next \Auth::user() return User model normally. So this is why tests without singleton working.
I tried your first idea but nothing changed - web is ok, testing null.
I think i have app/env specific problem (maybe third parties libs) and i need make own investigation. My guess is that session problem because i tried to pass simply session variable withSession(['foo' => 'bar']) and still no session initiated. I think MyCustomStateClass is called by UnitTest before session is initiated at all. I need to know why and where.
In the beginning of breadcrumbs.php i have
$activeAccess = app('App\Session\MyCustomStateClass');
because in breadcrumbs also i need this specific session info. Interesting..