简体   繁体   中英

Create new instance from Moq.object failed unit test

I am trying to instantiate a new object using the moq that I have set up but I am not getting the data I've set up in moq. Why?

For instance: I've set up MyProperty to true in mock. But when I create the new instance from mock.object I am getting false for MyProperty .

Interface:

 public interface IMyClass
    {
        bool MyProperty { get; set; }
        bool MyMethod();
    }

Class

        public class MyClass : IMyClass
            {
                public bool MyProperty { get; set; }
        
                public bool MyMethod()
                {
                    return MyProperty;
                }
        
                public MyClass(IMyClass myClass)
                {
                   this.MyProperty = myClass.MyProperty;
                    _myClass = myClass;
                }
        
                private IMyClass _myClass { get; set; }
            }

TestMethod

 [TestProperty]
    public void MyMethodTest()
    {
         var moq = new Mock<IMyClass>();
         moq.Setup(m => m.MyProperty).Returns(true);
    
         var sut = new MyClass(moq.Object);
         Assert.AreEqual(sut.MyMethod, true);
    }

Update: Test MyMethod

[TestMethod]
public void MyMethodTest()
{
    var moq = new Mock<IMyClass>();
    moq.Setup(m => m.MyMethod()).Returns(true);

    var sut = new MyClass(moq.Object);
    Assert.AreEqual(sut.MyMethod(),true); // => this test fails. why?
}

The test fails because you are not assigning any value in the class to the public member being compared.

MyClass.MyProperty is never assigned a value, so in

Assert.AreEqual(sut.MyMethod(), true);

sut.MyMethod() will be false

You would need to refactor the class to use the value from the injected interface and assign it to the respective member.

public class MyClass : IMyClass {
    public bool MyProperty { get; set; }

    public bool MyMethod() {
        return MyProperty;
    }
    
    public MyClass(IMyClass myClass) {
        this.MyProperty = myClass.MyProperty; // assigning value to property
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM