Moq - How to verify that a property value is set via the setter

前端 未结 5 1885
梦如初夏
梦如初夏 2020-12-16 09:22

Consider this class:

public class Content
{      
   public virtual bool IsCheckedOut {get; private set;}
   public virtual void CheckOut()
   {
      IsChec         


        
5条回答
  •  星月不相逢
    2020-12-16 09:47

    I agree with you: mocking has no value in this scenario because it is intended to test the interactions between your class (under test) and the rest of the world, not to test the inner mechanism of your class.

    I think that this test

    Content c = new Content();    
    c.CheckIn();    
    Assert.AreEqual(false, c.IsCheckedOut); //State verification
    

    that you write has sense and it is not a false positive! You must ensure that the state is in that way after the CheckIn regardless on why it is so; if in the future you will set the state in the constructor (or in other methods) this test will save you and you will be forced to implement the CheckIn method!

    In some cases similar to your I want to set the initial state to be sure that I does not forget to implement the CheckIn method; in this case I use 2 methods (the first is very ugly):

    1. I call c.CheckOut() before c.CheckIn(); this is very ugly, because you test 2 methods instead of one ... but I admit that I wrote something similar few times :-)
    2. I make the private setter protected, and I write a test class that inherits from the class under test; in this manner I can set the property to true before to call c.CheckIn() to ensure that the method is doing his job.

    Here it is the code:

        public class Content2
    {
        public virtual bool IsCheckedOut { get; protected set; }
        public virtual void CheckOut()
        {
            IsCheckedOut = true;
        }
    
        public virtual void CheckIn()
        {
            //Do Nothing for now as demonstrating false positive test.
        } 
    }
    
        [TestClass]
    public class Content2Test : Content2
    {
        [TestMethod]
        public void CheckOutSetsCheckedOutStatusToTrue()
        {
            this.CheckOut();
            Assert.AreEqual(true, this.IsCheckedOut); //Test works as expected
        }
    
        [TestMethod]
        public void CheckInSetsCheckedOutStatusToFalse()
        {
            this.IsCheckedOut = true;
            this.CheckIn();
            Assert.AreEqual(false, this.IsCheckedOut); //Test does not work as expected
        }
    }
    

    Hope to help.

提交回复
热议问题