用Moq模拟基类方法调用 [英] Mocking a base class method call with Moq

查看:70
本文介绍了用Moq模拟基类方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在修改一个类方法,该方法格式化一些输入的参数日期,这些日期随后用作对基类(位于另一个程序集中)的方法调用中的参数.

I am modifiying a class method which formats some input paramater dates which are subsequently used as params in a method call into the base class (which lives in another assembly).

我想验证传递给我的方法的日期在传递给基类方法时的格式是否正确,以便我想对基类方法调用进行Moq. Moq有可能吗?

I want to verify that the dates i pass in to my method are in the correct format when they are passed to the base class method so i would like to Moq the base class method call. Is this possible with Moq?

推荐答案

截至2013年,您可以使用最新的最低起订量.这是一个示例

As of 2013 with latest Moq you can. Here is an example

public class ViewModelBase
{
    public virtual bool IsValid(DateTime date)
    {
        //some complex shared stuff here
    }
} 

public class MyViewModel : ViewModelBase
{
    public void Save(DateTime date)
    {
        if (IsValid(date))
        {
            //do something here
        }
    }
}

public void MyTest()
{
    //arrange
    var mockMyViewModel = new Mock<MyViewModel>(){CallBase = true};
    mockMyViewModel.Setup(x => x.IsValid(It.IsAny<DateTime>())).Returns(true);

    //act
    mockMyViewModel.Object.Save();

    //assert
    //do your assertions here
} 

这篇关于用Moq模拟基类方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆