Asp.net core testing controller with IStringLocalizer

I have a controller with localization

public class HomeController : Controller
{
    private readonly IStringLocalizer<HomeController> _localizer;

    public HomeController(IStringLocalizer<HomeController> localizer)
    {
        _localizer = localizer;
    }

    [HttpPost]
    public IActionResult SetLanguage(string culture, string returnUrl)
    {
        Response.Cookies.Append(
            CookieRequestCultureProvider.DefaultCookieName,
            CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
            new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
        );

        return LocalRedirect(returnUrl);
    }

    public IActionResult Index()
    {
        ViewData["MyTitle"] = _localizer["Hello my dear friend!"];

        return View("Index");
    }
}

and I added an xUnit project for testing and wrote the following code

public class HomeControllerTest
{
    private readonly IStringLocalizer<HomeController> _localizer;
    private HomeController _controller;
    private ViewResult _result;

    public HomeControllerTest()
    {
        _controller = new HomeController(_localizer);
        _result = _controller.Index() as ViewResult;
    }

    [Fact]
    public void IndexViewDataMessage()
    {
        // Assert
        Assert.Equal("Hello my dear friend!", _result?.ViewData["MyTitle"]);
    }

    [Fact]
    public void IndexViewResultNotNull()
    {
        // Assert
        Assert.NotNull(_result);
    }

    [Fact]
    public void IndexViewNameEqualIndex()
    {
        // Assert
        Assert.Equal("Index", _result?.ViewName);
    }
}

When I run all the tests, they return false with the exception:

Message: System.NullReferenceException: The object reference is not set to the object instance.

When you double-click a method in StackTrace, the cursor appears in the line

ViewData["MyTitle"] = _localizer["Hello my dear friend!"];

I think this is due to IStringLocalizer. How to fix it? Maybe someone knows the reason?

+7
source share
1 answer

Adjust the layout to return the expected result.

var mock = new Mock<IStringLocalizer<HomeController>>();
string key = "Hello my dear friend!";
var localizedString = new LocalizedString(key, key);
mock.Setup(_ => _[key]).Returns(localizedString);

_localizer = mock.Object;
_controller = new HomeController(_localizer);
+10
source

Source: https://habr.com/ru/post/1016593/


All Articles