samedi 25 novembre 2017

Moq : how can mock property and side Effect?

this is test scenario.

when kid age over 3, IsAdult == true.

i want test with Moq. but fail. because Age always return 2 (setted)

how can i test this? maybe Mocking is bad idea?

using DebugMethod or bruteForce is not inteded...

have a nice day!


using NUnit.Framework;
using Moq;

namespace TDDKATA
{
public class Kid
{
    public virtual float Age { get; private set; } = 0;
    public bool IsAdult { get; private set; }
    private float _ageIncreasePerHour = 1;

    public void OnHourPass()
    {
        Age += _ageIncreasePerHour;

        if (Age >= 3)
        {
            IsAdult = true;
        }
    }

    public void Debug_SetAge(float newAge)
    {
        Age = newAge;
    }
}

public class Test_Kid
{
    //fail. how can i mocking?
    [Test]
    public void WhenAgeOver3_Kid_IsAdult_UseMocking()
    {
        var mockKid = new Mock<Kid> { CallBase = true };
        mockKid.Setup(x => x.Age).Returns(2);
        Assert.AreEqual(2, mockKid.Object.Age);
        mockKid.Object.OnHourPass();
        Assert.AreEqual(3, mockKid.Object.Age); // but 2.
        Assert.AreEqual(true, mockKid.Object.IsAdult); // but false.
    }

    //success. but not intended. Debug-Method is anti pattern!
    [Test]
    public void WhenAgeOver3_Kid_IsAdult_UseDebugMethod()
    {
        var newKid = new Kid();
        newKid.Debug_SetAge(2);
        newKid.OnHourPass();
        Assert.AreEqual(true, newKid.IsAdult);
    }

}
}

Aucun commentaire:

Enregistrer un commentaire