Rag*_*ghu 10 c# interface class moq concrete
我有一个接口ITransaction如下:
public interface ITransaction {
DateTime EntryTime { get; }
DateTime ExitTime { get; }
}
Run Code Online (Sandbox Code Playgroud)
我有一个派生类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
}
Run Code Online (Sandbox Code Playgroud)
我想模拟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);
Run Code Online (Sandbox Code Playgroud)
但是当我注射的时候
(mockedTxn.Object as PaymentTransaction)
在我正在测试的方法中(因为它只需要一个PaymentTransaction而不是ITransaction,我也无法更改它)调试器显示入口时间和退出时间的空引用.
我想知道是否有人可以帮助我.
谢谢你的期待.
我能够解决这个问题的唯一方法(无论哪种方式都感觉像是黑客)是要么做你不想做的事情,要么将具体类的属性设为虚拟(即使对于接口实现) ,或者在您的类上显式实现该接口。例如:
public DateTime EntryTime
{
get { return ((ITransaction)this).EntryTime; }
}
DateTime ITransaction.EntryTime
{
get { throw new NotImplementedException(); }
}
Run Code Online (Sandbox Code Playgroud)
然后,当您创建模拟时,您可以使用As<ITransaction>()
语法,并且模拟将按照您的预期运行。