vendredi 18 septembre 2015

Unit testing inheritance hierarchies with Moq

I've an inheritance hierarchy which looks like the following:

public class Foo{
        public virtual IList<string> Messages{get;set;}
}

public class Foo2: Foo{
    public bool DoSomething(){
        //Evaluate something;
    }
}

public class Bar: Foo2{
    public override bool DoSomething(){
        var res = base.DoSomething();
        if(res)
            Messages.Add("Hello World");
        return res;
    }
}

My subject under test is Bar and test framework is Moq.

        [TestMethod]
        public void TestBar()
        {

            var mockedBar= new Mock<Bar>() {CallBase = true};
            mockedBar.SetupGet(x => x.Messages).Returns(new List<string>());
            mockedBar.Setup(x => x.DoSomething()).Returns(false);

            var result = mockedBar.Object.DoSomething();

            Assert.IsFalse(result, "This should fail");
            mockedBar.Verify(x => x.DoSomething(), Times.Once, "The base DoSomething is called only once.");
         }

I'm just starting to invest in unit testing and I'm not sure if I'm doing it correctly. Question:

  1. This is passing right now but I'm not confident of my test method. The mockedBar.Setup(x=>x.DoSomething()) should setup my base.DoSomething() call. Is that correct?

  2. How do I test that The Bar.DoSomething() is actually populating the Messages in the Foo class?

Any guidance is much appreciated.

Aucun commentaire:

Enregistrer un commentaire