【发布时间】:2018-10-18 05:49:55
【问题描述】:
我有一个实体框架数据库上下文文件。 我将如何设置 DBContext,并在运行测试之前每次运行 SetUp(以拥有干净的填充数据库)?它在 NUnit 测试中看不到 dbcontext。
电子数据库上下文文件
public partial class ElectronicsContext : DbContext
{
public ElectronicsContext()
{
}
public ElectronicsContext(DbContextOptions<ElectronicsContext> options)
: base(options)
{
}
public virtual DbSet<Product> Product { get; set; }
public virtual DbSet<ProductCategory> ProductCategory { get; set; }
Nunit 设置
public class TestClass
{
[SetUp]
public void TestProducts()
{
var options = new DbContextOptionsBuilder<ElectronicsContext>()
.UseInMemoryDatabase(databaseName: "Products Test")
.Options;
using (var context = new ElectronicsContext(options))
{
context.Product.Add(new Product { ProductId = 1, ProductName = "TV", ProductDescription = "TV testing", ImageLocation = "test" , ProductCategoryId = 2});
context.SaveChanges();
}
}
此处出现错误消息
The name 'context' does not exist in the current context
[Test]
public void TestProductRepository()
{
ProductRepository productRepository = new ProductRepository(context);
Assert.AreEqual("TV", productRepository.GetById(1).ProductName);
}
}
SetUp 的替代想法也不起作用:
[SetUp]
public void TestProducts()
{
var options = new DbContextOptionsBuilder<ElectronicsContext>()
.UseInMemoryDatabase(databaseName: "Products Test")
.Options;
ElectronicsContext context = new ElectronicsContext(options);
【问题讨论】:
-
虽然已经有两个人回答了,但是如果不知道你使用的NUnit的版本,至少是V2还是V3,实际上是不可能给你的问题一个好的答案的。 :-(我可以写两个答案,但我很懒。:-)
标签: c# entity-framework asp.net-core nunit