我已经使用这篇优秀的MSDN文章中找到的异步查询提供程序设置了一个测试项目:
http://msdn.microsoft.com/en-US/data/dn314429#async非常有用.
public async Task<Blog> GetBlog(int blogId) { return await _context.Blogs.FindAsync(blogId); }
并以以下格式添加以下单元测试:
[TestMethod] public async Task GetAllBlogsAsync_gets_blog() { var data = new List<Blog> { new Blog { BlogId = 1,Name = "BBB" },new Blog { BlogId = 2,Name = "ZZZ" },new Blog { BlogId = 3,Name = "AAA" },}.AsQueryable(); var mockSet = new Mock<DbSet<Blog>>(); mockSet.As<IDbAsyncEnumerable<Blog>>() .Setup(m => m.GetAsyncEnumerator()) .Returns(new TestDbAsyncEnumerator<Blog>(data.GetEnumerator())); mockSet.As<IQueryable<Blog>>() .Setup(m => m.Provider) .Returns(new TestDbAsyncQueryProvider<Blog>(data.Provider)); mockSet.As<IQueryable<Blog>>().Setup(m => m.Expression).Returns(data.Expression); mockSet.As<IQueryable<Blog>>().Setup(m => m.ElementType).Returns(data.ElementType); mockSet.As<IQueryable<Blog>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); var mockContext = new Mock<BloggingContext>(); mockContext.Setup(c => c.Blogs).Returns(mockSet.Object); var service = new BlogService(mockContext.Object); var blog = await service.GetBlog(2); Assert.AreEqual("ZZZ",blog.Name); }
但是,当从我的测试方法调用GetBlog时,等待_context.Blogs.FindAsync(blogId);抛出NullReferenceException
在TestingDemo.BlogService.< GetBlog> d__5.MoveNext()
有关如何使用MSDN文章中的测试方法调用FindAsync的方法实现单元测试的任何建议:http://msdn.microsoft.com/en-US/data/dn314429#async?