Search code examples
c#unit-testingmockingmoqmstest

MsTest : Actual value increases everytime test method runs


Here is my test class

[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>>();

    }

}

Here is the ShouldEqual method

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

and here is the GetList method

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();
    }
}

Every time I run GetPushableQueues_gets_all_pushable_entries() method

The actual value is increased by 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

This problem persists even if I clean the test project and rebuild it. Any idea why this is happening and what am I missing?

Note: There are other test methods that use _yourRepository and call Create method to create an entity.


Solution

  • The problem is that you are actually using some kind of repository there. You don't mock it. _yourRepository = new Mock< YourRepository >().Object;

    Should be _yourRepository = new Mock< IYourRepository >().Object;

    And all the methods you use from the IYourRepository interface should be mocked/set up as well.