Using Moq to determine if a method is called

后端 未结 3 1974
暗喜
暗喜 2020-11-29 02:21

It is my understanding that I can test that a method call will occur if I call a higher level method, i.e.:

public abstract class SomeClass()
{    
    publi         


        
3条回答
  •  悲哀的现实
    2020-11-29 02:56

    Even though I agree that the @Paul's answer is the recommended way to go I just want to add one alternative way which is provided by moq off the self.

    Since SomeClass is abstract it is indeed mockable, but public void SomeMehod() isn't. The point is to find the way to mock and somehow invoke that method and then using CallBase propagate the call to the SomeOtherMethod(). It might sound as a hack but it is simple in essence. It could be used in the case if the proposed refactoring is not possible.

    // This class is used only for test and purpose is make SomeMethod mockable
    public abstract class DummyClass : SomeClass
    {
        public virtual void DummyMethod() => base.SomeMethod();
    }
    

    Then you could setup DummyMethod() to propagate the call by setting CallBase flag.

    //Arrange
    var mock = new Mock();
    mock.Setup(m => m.DummyMethod()).CallBase();
    
    //Act
    mock.Object.SomeMethod();
    
    //Assert
    mock.Verify(m => m.SomeOtherMethod(), Times.Once);
    

提交回复
热议问题