asp.net5 dbContext依赖注入xUnit test

时间:2016-01-14 22:53:38

标签: c# asp.net entity-framework xunit asp.net-core

尝试将我的服务正确注入我的单元测试中。在我的控制器中正常工作,使用与构造函数中的DbContext相同的方法。

 public class PostTest
{

    public BlogContext db { get; set; }

    public PostTest(BlogContext Context)
    {
        db = Context;
    }

我的所有后续测试都因以下原因而失败:

以下构造函数参数没有匹配的fixture数据:BlogContext Context

我的OnConfigure设置

  public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();

        // Adding CORS to api
        services.AddCors(options =>
        {
            options.AddPolicy("AllowAllOrigins", builder => builder.AllowAnyOrigin());
        });

        string connstr = "Data Source=(localdb)\\ProjectsV12;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";


        services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext<BlogContext>(options =>
                options.UseSqlServer(connstr));

        //services.AddScoped<BlogContext>(provider => provider.GetService<BlogContext>());

    }

这是我的博客控制器的一个例子 - 这很好用。

[Route("api/[controller]")]
public class BlogController : Controller
{

    private BlogContext db;

    public BlogController(BlogContext dbContext)
    {
        db = dbContext;

      //  db = new BlogContext();

    }

    //public BlogContext db;


    [HttpGet("{id}")]
    //public IEnumerable<Post> Get()
    public Post Get(int id)
    {
        try {
            Post FoundPost = db.Posts.Where(x => x.id == id).Single();
            return FoundPost;
        }
        catch
        {
            return new Post { id = 0 };
        }  
    }

任何建议都会非常感激

1 个答案:

答案 0 :(得分:1)

您需要在测试类中略有不同:

 public class BlogControllerFacts
 {
        public class Index
        {
            [Fact]
            public void GetDoesSomething()
            {
                // Arrange
                BlogContext db = new BlogContext(); // This should be mocked somehow
                const int id = 5;
                var controller = new BlogController(db);

                // Act
                var result = controller.Get(id);

                // Assert something
            }

        }
    }
}