mardi 4 août 2015

Moq: Not getting the same object on second call

I am trying to write a simple test with moq. When calling the mocked method for the second time, after changing the return value from the first call, the moq framework returns the modified object. I guess this is because I am changing the same reference.

How can I ensure that each call to the moq will return the same value?

public class VersionData
{
    public int Number { get; set; }
    public string Str { get; set; }
}

public interface ILogic
{
    VersionData GetVersion();
}

[TestClass]
public class LogicTester
{
    private Mock<ILogic> _mock;

    [TestInitialize]
    public void InitSingleTest()
    {
        _mock = new Mock<ILogic>();
    }

    [TestMethod]
    public void Test()
    {
        _mock.Setup(x => x.GetVersion()).Returns(new VersionData { Number = 1, Str = "1" });

        VersionData l1 = _mock.Object.GetVersion(); // OK
        l1.Number = 2;
        l1.Str = "2";


        // Not OK - I'd expect l2.Number = 1 and l2.Str = "1" but l2.Number = 2 and l2.Str = "2"
        VersionData l2 = _mock.Object.GetVersion(); 

        return;
    }
}

Aucun commentaire:

Enregistrer un commentaire