I highly encourage anyone stumbling upon this to look at some of the tests as they are implemented in UE4 project (search for UWorld keyword in Tests files).
The following solution works for me and I scraped it together from observing UE4 Tests implementations.
inline UWorld* GetWorldForTestSafe()
{
if (GEditor && GEditor->GetWorldContexts().Num() && GEditor->GetWorldContexts()[0].World())
{
UE_LOG(LogGameGeneric, Verbose, TEXT("Getting world from editor"))
return GEditor->GetWorldContexts()[0].World();
}
if (GEngine && GEngine->GetWorldContexts().Num() && GEngine->GetWorldContexts()[0].World())
{
UE_LOG(LogGameGeneric, Verbose, TEXT("Getting world from engine"))
return GEngine->GetWorldContexts()[0].World();
}
if (GEditor)
{
UE_LOG(LogGameGeneric, Verbose, TEXT("Creating new world for editor"))
return FAutomationEditorCommonUtils::CreateNewMap();
}
UE_LOG(LogGameGeneric, Verbose, TEXT("GEditor was not present, could not create World (map)"))
return nullptr;
}
But this might not be the best approach as the World Contexts might not be present at all for different types of tests.
It would be better to check against the test type which is being run.
I have tested this only few times and it seems to work, so I hope it at least helps somebody to find the correct direction if stumbeled upon this.