加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c#用Moq模拟具体类的接口成员

发布时间:2020-12-15 06:50:55 所属栏目:百科 来源:网络整理
导读:我有一个接口ITransaction如下: public interface ITransaction { DateTime EntryTime { get; } DateTime ExitTime { get; }} 我有一个派生类PaymentTransaction如下: public class PaymentTransaction : ITransaction { public virtual DateTime LastPaym
我有一个接口ITransaction如下:
public interface ITransaction {

        DateTime EntryTime { get; }

        DateTime ExitTime { get; }
}

我有一个派生类PaymentTransaction如下:

public class PaymentTransaction : ITransaction {

        public virtual DateTime LastPaymentTime
        {
            get { return DateTime.Now; }
        }

        #region ITransaction Members

        public DateTime EntryTime
        {
            get  { throw new NotImplementedException(); }
        }

        public DateTime ExitTime
        {
            get  { throw new NotImplementedException(); }
        }

        #endregion
}

我想要模拟PaymentTransaction对象的所有三个属性.

我尝试了以下,但它没有工作:

var mockedPayTxn = new Mock<PaymentTransaction>();
mockedPayTxn.SetUp(pt => pt.LastPaymentTime).Returns(DateTime.Now); // This works

var mockedTxn = mockedPayTxn.As<ITransaction>();
mockedTxn.SetUp(t => t.EntryTime).Returns(DateTime.Today); 
mockedTxn.SetUp(t => t.ExitTime).Returns(DateTime.Today);

但是当我注射

(mockedTxn.Object作为PaymentTransaction)

在我正在测试的方法中(因为它只需要PaymentTransaction而不是ITransaction,我也不能更改它),调试器显示入口时间和退出时间的空引用.

我想知道有人能帮我吗

感谢预期.

解决方法

我能够解决这个问题的唯一方法(它感觉像是一个黑客)是要做你不想做的,并使具体类的属性虚拟(即使是接口实现),或者也明确地实现你的类的接口.例如:
public DateTime EntryTime
{
  get  { return ((ITransaction)this).EntryTime; }
}

DateTime ITransaction.EntryTime
{
  get { throw new NotImplementedException(); }
}

然后,当您创建Mock时,您可以使用As< ITransaction>()语法,并且模拟将按照您期望的行为.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读