MsTest:每次测试方法运行,实际值都会增加

时间:2018-08-15 08:56:37

标签: c# unit-testing mocking moq mstest

这是我的考试班

[TestClass]
public class FooServiceTest
{
    private IYourRepository _yourRepository;

    [TestInitialize]
    public void Initialize()
    {
        _yourRepository = new Mock<YourRepository>().Object;

    }

    [TestMethod]
    public void GetPushableEntries_gets_all_pushable_entries()
    {
        var yourObjectList = new List<YourObject>
        {
            new WaitingQueue
            {                   
                ProfileId = 26,
                IsDeleted = false,
                Pushable = true
            },
            new WaitingQueue
            {                    
                ProfileId = 27,
                IsDeleted = false,
                Pushable = true
            },
            new WaitingQueue
            {                   
                ProfileId = 28,
                IsDeleted = false,
                Pushable = false
            }

        };

        foreach (var yourObject in yourObjectList)
        {
            _yourRepository.Create(yourObject);
        }

        var pushableEntries = _yourRepository.GetList(x => x.Pushable);
        pushableEntries.Count.ShouldEqual(2);
        pushableEntries.ShouldNotBeNull();
        pushableEntries.ShouldBe<IReadOnlyCollection<WaitingQueue>>();

    }

}

这是ShouldEqual方法

public static T ShouldEqual<T>(this T actual, object expected)
{
    Assert.AreEqual(expected, actual);
    return actual;
}

这是GetList方法

public IReadOnlyCollection<T> GetList(Expression<Func<T, bool>> @where, params Expression<Func<T, object>>[] nav)
{
    using (var dbContext = new MyDbContext())
    {
        return GetFiltered(dbContext, nav).Where(where).ToList();
    }
}

每次我运行GetPushableQueues_gets_all_pushable_entries()方法

实际值增加2。

Assert.AreEqual failed. Expected:<2>. Actual:<2>. //first run
Assert.AreEqual failed. Expected:<2>. Actual:<4>. //second run
Assert.AreEqual failed. Expected:<2>. Actual:<6>. //third run

即使我清理测试项目并重新构建,此问题仍然存在。 知道为什么会这样,我想念什么吗?

注意:还有其他测试方法使用_yourRepository并调用Create方法来创建实体。

1 个答案:

答案 0 :(得分:1)

问题是您实际上在那里使用某种存储库。 你不要嘲笑它。 _yourRepository = new Mock ()。Object;

应该是 _yourRepository = new Mock ()。Object;

您也应该模拟/设置从IYourRepository接口使用的所有方法。