I'm trying to migrate an asp.net mvc 5 controller to use async/await. I have a problem with testing that the correct culture has been set.
In the old (non-async) version of the code, the unit test passes because everything is running on the same thread. In the new (async) version of the code, the unit test fails because the current culture is not maintained after calling an async/await method.
In the new version of the code, the culture is set correctly, and the view has the correct culture set. The only problem is that I can't test this in my NUnit test, because it's outside of an await call.
Do you know how I can fix this? I have provided a pseudocode-like version of the code I use below.
Old code:
public ActionResult Index()
{
// Look up user in database
var dbUser = database.GetUser(User.Identity.GetUserId());
// Set preferred culture
Thread.CurrentThread.CurrentCulture = new CultureInfo(dbUser.PreferredCulture);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(dbUser.PreferredCulture);
// Do some other work
DoSynchronousWork();
return View();
}
[TestFixture]
public class TestClass
{
[Test]
public void TestIndex_CorrectCulture()
{
// Mock database
database.GetUser().Returns(new User(){PreferredCulture = "de"});
// Call controller
_controller.Index();
// Check that the thread culture was correctly set - this passes
Assert.AreEqual("de", Thread.CurrentThread.CurrentCulture);
Assert.AreEqual("de", Thread.CurrentThread.CurrentUICulture);
}
}
New code:
public async Task<ActionResult> Index()
{
// Look up user in database
var dbUser = database.GetUser(User.Identity.GetUserId());
// Set preferred culture
Thread.CurrentThread.CurrentCulture = new CultureInfo(dbUser.PreferredCulture);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(dbUser.PreferredCulture);
// Do some other work
await DoAsynchronousWork();
return View();
}
[TestFixture]
public class TestClass
{
[Test]
public async Task TestIndex_CorrectCulture()
{
// Mock database
database.GetUser().Returns(new User(){PreferredCulture = "de"});
// Call controller
await _controller.Index();
// Check that the thread culture was correctly set - this fails because the culture inside _controller.Index() is lost after the await call
Assert.AreEqual("de", Thread.CurrentThread.CurrentCulture);
Assert.AreEqual("de", Thread.CurrentThread.CurrentUICulture);
}
}