2015-11-04 79 views
3

我們加入我們的ASP Web應用程序會話之後,現在我們的控制器單元測試失敗:加入會話的ASP.NET 5控制器單元測試

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)); 

看起來像需要添加會話服務。

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

一個例子(從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); 
    } 
}