C# 单元测试存储库。为什么DBContext返回错误的值?

C# 单元测试存储库。为什么DBContext返回错误的值?,c#,asp.net-mvc,unit-testing,caching,dbcontext,C#,Asp.net Mvc,Unit Testing,Caching,Dbcontext,我正在单元测试ASP MVC应用程序。现在我正在测试一个存储库。我在数据库中有一个表,它具有atributes ID(主键int)、ItemName(varchar)、IsValid(位-true/false)。 在存储库中,有创建、更新、删除等方法,我正在使用单元测试对这些方法进行测试(使用atribute的测试是有效的)。还有方法getAllItems public IEnumerable<Item> GetAllItems() { return _db.ItemSet.Wher

我正在单元测试ASP MVC应用程序。现在我正在测试一个存储库。我在数据库中有一个表,它具有atributes ID(主键int)、ItemName(varchar)、IsValid(位-true/false)。 在存储库中,有创建、更新、删除等方法,我正在使用单元测试对这些方法进行测试(使用atribute的测试是有效的)。还有方法getAllItems

public IEnumerable<Item> GetAllItems()
{
return _db.ItemSet.Where(w => w.isValid);
}
如果我单独运行所有测试,它工作正常。如果我同时运行所有测试,就会出现问题。 在变量allWorkitems中,有isValid=false和isValid=true的项


我认为dbContext正在缓存查询和数据,以提高测试速度。是否有任何功能可以禁用此切换。或者还有其他问题吗?

在执行每个单元测试之前,必须将测试的上下文设置为干净状态。我的意思是,您需要清除前一个测试可能创建的任何数据,为下一个测试清除路径

一种方法是使用测试设置方法,例如

[TestInitialize]
public void Setup()
{
    // This function will be executed before each test.
    // Use this function as an opportunity to clear any shared objects e.g.
    // dbContext <- Delete all data that is not required.
}

[TestMethod]
public void Test1()
{
    // Arrange.
    // Add 1 item to the dbContext

    // Act
    var actual = _ws.GetAllItems();

    // Assert.
    Assert.AreEqual(1, actual.Count());
}

[TestMethod]
public void Test2()
{
    // Arrange.
    // Here, the dbContext will have been cleared in the Setup() function.
    // Add 5 items to the dbContext

    // Act
    var actual = _ws.GetAllItems();

    // Assert.
    Assert.AreEqual(5, actual.Count()); // Total items should be 5, not 6.
}

这样,每个测试都将使用新的对象,并且没有以前测试中的延迟数据。

您是否在所有测试之间共享
\ws
对象?是的,我会,还有一个dbContext。听起来很完美。那么我应该在设置中做什么呢?我有私有静态MyIContainer _db=new MyIContainer();和IItemService _ws=新的ItemService(_db);我是否应该在带有注释[TestInitialize]的方法中再次将其取消标记?
[TestInitialize]
public void Setup()
{
    // This function will be executed before each test.
    // Use this function as an opportunity to clear any shared objects e.g.
    // dbContext <- Delete all data that is not required.
}

[TestMethod]
public void Test1()
{
    // Arrange.
    // Add 1 item to the dbContext

    // Act
    var actual = _ws.GetAllItems();

    // Assert.
    Assert.AreEqual(1, actual.Count());
}

[TestMethod]
public void Test2()
{
    // Arrange.
    // Here, the dbContext will have been cleared in the Setup() function.
    // Add 5 items to the dbContext

    // Act
    var actual = _ws.GetAllItems();

    // Assert.
    Assert.AreEqual(5, actual.Count()); // Total items should be 5, not 6.
}
[TestInitialize]
public void Setup()
{
    _db = new MyIContainer();
    _ws = new ItemService(_db);
}