【问题标题】:C# Entity Test - While debugging, test pass but in run mode failC# 实体测试 - 调试时,测试通过但在运行模式下失败
【发布时间】:2016-09-10 16:09:29
【问题描述】:

我想检查我的删除方法是否有效 :) 我在我的数据库中添加了一个元组。

测试方法

 [TestMethod]
    public void DeleteIngredient()
    {
        using (var ctx = new TestDbContext())
        {
            //Arrange
            Ingredient ingredient = new TestClass.Ingredient();
            ingredient.Id = 1;
            ingredient.Name = "Watermelon";
            ingredient.VegeOrVegetarian = VeganType.Both;
            //Act
            ctx.ingredients.Add(ingredient);
            ctx.SaveChanges();
            IngredientService service = new IngredientService(ctx);
            service.removeIngredient(1);
            service.saveChanges();

            //Assert
            Assert.AreEqual(0, ctx.ingredients.Count());
        }
    }

服务

        public class IngredientService
{
    private readonly TestDbContext _TestDbContext;

    public IngredientService(TestDbContext TestDbContext)
    {
        _TestDbContext = TestDbContext;
    }

    public List<Ingredient> getIngredients()
    {
        return _TestDbContext.ingredients.ToList();
    }

    public void removeIngredient(int id)
    {
        var toRemove = _TestDbContext.ingredients.Find(id);       
        _TestDbContext.ingredients.Remove(toRemove);

    }
    public void saveChanges()
    {
        _TestDbContext.SaveChanges();
    }
}

一切都在调试模式下工作。

Assert.AreEqual(0, ctx.ingredients.Count());

我被告知测试通过。 但是在运行模式下运行所有​​测试(包括此删除)后,我得到了错误。

Assert.AreEqual 失败预期:。实际

我认为上下文存在问题。任何线索如何解决这个问题?

【问题讨论】:

  • 我不知道您是如何配置数据库的,但您可以尝试致电service.removeIngredient(ingredient.Id); 吗?你可能会得到其他不是 1 的 id
  • 是的,我知道它只是临时添加的 XD
  • 您确定您没有运行其他使用相同数据库的测试吗?您可以在开头添加一个 clear 并保存更改以确保

标签: c# unit-testing testing


【解决方案1】:

短版:

不要使用 DbContext 来获取验证所需的数据。要获取此数据,请不使用 ORM 方法:DbConnection、DbCommand 等。

测试算法:

  1. 通过非 ORM 方法从 db 获取 StartData。
  2. 用 ORM 方法做你想测试的事情。
  3. 释放 ORM 上下文或关闭会话。
  4. 通过非 ORM 方法从 db 获取 EndData。
  5. 验证数据。

为什么要这样做的答案很复杂。由于使用不同版本和类型的库进行测试,ORM 和数据库提供者对于可能出现的问题没有简单的答案。

对不起我的英语。

【讨论】:

    猜你喜欢
    • 2021-06-10
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 2013-11-08
    • 2013-02-16
    相关资源
    最近更新 更多