为ASP.NET 5控制器单元测试添加会话

时间:2015-11-04 16:22:45

标签: unit-testing asp.net-core

在我们的asp web应用程序中添加会话后,现在我们的控制器单元测试失败了:

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

在我们使用会话的声明中测试失败:

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

看起来需要添加会话服务。在我们的应用程序中,它是通过Startup类的方法完成的:

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

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

但是当我们进行单元测试时,我们就像这样实例化我们的控制器:

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

那么有没有办法在asp.net 5单元测试中为控制器注入会话?

1 个答案:

答案 0 :(得分:1)

一个例子(来自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);
    }
}