断言和验证都失败了

时间:2017-05-16 22:10:37

标签: c# unit-testing moq

请参阅以下代码:

[TestClass]
public class UnitTest1
{
    Moq.Mock<ISayGoodMorning> GoodMorningMock;

    [TestInitialize]
    public void init()
    {
        GoodMorningMock = new Moq.Mock<ISayGoodMorning>();
        GoodMorningMock.Setup(x => x.GoodMorning()).Returns(Test());
    }

    [TestMethod]
    public void TestMethod1()
    {
        GoodMorningMock.Verify(x => x.GoodMorning(), Times.Once());
        Assert.AreEqual(g.SayGreeting(), "Hola");           
    }

    public string Test()
    {
        return "Hola";
    }
}

断言和验证失败。这是为什么?以下是经过测试的代码:

namespace ClassLibrary1
{
    public class SayGoodMorning : ISayGoodMorning
    {
        public string GoodMorning()
        {
            return "Good Morning";
        }
    }

    public interface ISayGoodMorning
    {
        string GoodMorning();
    }
}

namespace ClassLibrary2
{
    public class Greeting
    {
        public string SayGreeting()
        {
            ISayGoodMorning s = new SayGoodMorning();
            return s.GoodMorning();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

首先,需要对要测试的主题进行重构以注入依赖项,以允许在测试时使用模拟。通过构造函数或方法注入。 (Explicit Dependencies Principle

此示例使用构造函数注入

namespace ClassLibrary2 {
    public class Greeting {
        private readonly ISayGoodMorning speaker;

        public Greeting(ISayGoodMorning speaker) {
            this.speaker = speaker;
        }

        public string SayGreeting() {
            return speaker.GoodMorning();
        }
    }
}

接下来需要对测试进行重组,以便在执行测试方法后完成Verify;

[TestClass]
public class UnitTest1 {
    Mock<ISayGoodMorning> GoodMorningMock;

    [TestInitialize]
    public void init() {
        //Arrange
        GoodMorningMock = new Mock<ISayGoodMorning>();
        GoodMorningMock.Setup(_ => _.GoodMorning()).Returns(Test());
    }

    [TestMethod]
    public void TestMethod1() {
        //Arrange cont'd
        var g = new ClassLibrary2.Greeting(GoodMorningMock.Object);
        var expected = "Hola";

        //Act
        var actual = g.SayGreeting();

        //Assert
        GoodMorningMock.Verify(_ => _.GoodMorning(), Times.Once());
        Assert.AreEqual(expected, actual);  
    }

    public string Test() {
        return "Hola";
    }
}