Unit test protected method in C# using Moq

前端 未结 3 1902
闹比i
闹比i 2021-02-18 14:48

It came to my attention lately that you can unit test abstract base classes using Moq rather than creating a dummy class in test that implements the abstract base class. See How

3条回答
  •  花落未央
    2021-02-18 15:36

    Another way in Moq to call protected member is the following template:

    1. In your class, with protected member mark your function as virtual. For example:

      public class ClassProtected
          {
              public string CallingFunction(Customer customer)
              {
                  var firstName = ProtectedFunction(customer.FirstName);
                  var lastName = ProtectedFunction(customer.LastName);
      
                  return string.Format("{0}, {1}", lastName, firstName);
              }
      
              protected virtual string ProtectedFunction(string value)
              {
                  return value.Replace("SAP", string.Empty);
              }
          }
      

    Then in your unit test add reference to

     using Moq.Protected;
    

    and in your unit test you can write the following:

        [TestFixture]
        public class TestClassProttected
        {
            [Test]
            public void all_bad_words_should_be_scrubbed()
            {
                //Arrange
                var mockCustomerNameFormatter = new Mock();
    
                mockCustomerNameFormatter.Protected()
                    .Setup("ProtectedFunction", ItExpr.IsAny())
                    .Returns("here can be any value")
                    .Verifiable(); // you should call this function in any case. Without calling next Verify will not give you any benefit at all
    
                //Act
                mockCustomerNameFormatter.Object.CallingFunction(new Customer());
    
                //Assert
                mockCustomerNameFormatter.Verify();
            }
        }
    

    Take note of ItExpr. It should be used instead of It. Another gotcha awaits you at Verifiable. I don't know why, but without calling to Verifiable Verify will not be called.

提交回复
热议问题