3

After we added sessions in our asp web app, now our controller unit tests fail:

data_browser.Tests.HomeControllerTests.Index [FAIL]
  System.NullReferenceException : Object reference not set to an instance of an object

Tests fail on a statement where we use sessions:

HttpContext.Session.SetString("games", JsonConvert.SerializeObject(games));

Looks like as a session service needs to be added. In our app it is done through Startup class's methods:

public void ConfigureServices(IServiceCollection services)
    {
        // Add MVC services to the services container.
        services.AddMvc();
        services.AddSession();
        services.AddCaching();
    }

and

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseSession();
        ...
    }

But when we unit test, we just instantiate our controller smth like this:

HomeController homeCtrler = new HomeController();
JsonResult jsonResult = (JsonResult)homeCtrler.Smth();
Assert.Eq(bla, bla);

So is there a way to inject sessions for controller in asp.net 5 unit tests?

1 Answer 1

1

An example (from https://github.com/aspnet/MusicStore/blob/master/test/MusicStore.Test/ShoppingCartControllerTest.cs):

// Arrange
var httpContext = new DefaultHttpContext();
httpContext.Session = new TestSession();

var controller = new ShoppingCartController()
controller.ActionContext.HttpContext = httpContext;

// Act
var result = await controller.Index();

//--------------

class TestSession : ISession
{
    private Dictionary<string, byte[]> _store
        = new Dictionary<string, byte[]>(StringComparer.OrdinalIgnoreCase);

    public IEnumerable<string> Keys { get { return _store.Keys; } }

    public void Clear()
    {
        _store.Clear();
    }

    public Task CommitAsync()
    {
        return Task.FromResult(0);
    }

    public Task LoadAsync()
    {
        return Task.FromResult(0);
    }

    public void Remove(string key)
    {
        _store.Remove(key);
    }

    public void Set(string key, byte[] value)
    {
        _store[key] = value;
    }

    public bool TryGetValue(string key, out byte[] value)
    {
        return _store.TryGetValue(key, out value);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.