简体   繁体   English

Moq具有“新”成员的模拟接口

[英]Mocking interfaces that have 'new' members with Moq

I'm having problems mocking an set of interfaces: 我在模拟一组接口时遇到问题:

interface IFoo
{
    object Blah { get; }
}

interface IBar : IFoo
{
    new string Blah { get; }
}

I tried mocking as: 我尝试嘲笑为:

var mock = new Mock<IFoo>();
mock.SetupGet(m => m.Blah).Returns("Blah");

This works now: 现在可以使用:

Assert.That(mock.Object.Blah, Is.EqualTo("Blah"));

The problem is that when I add the following, to also have a value for the IBar interface, the value of IFoo.Blah is null. 问题是,当我添加以下,也有对价值IBar接口,价值IFoo.Blah为空。

var bar = mock.As<IBar>();
bar.SetupGet(m => m.Blah).Returns("Blah");

This works now: 现在可以使用:

Assert.That(((IBar)mock.Object).Blah, Is.EqualTo("Blah"));

But the old one fails: 但是旧的失败了:

Assert.That(mock.Object.Blah, Is.EqualTo("Blah"));
// mock.Object.Blah is null now

Is there a way to get both to work? 有办法让两者都起作用吗?

With MOQ (v4.0.10827) and .Net 4, this code is working: 使用最小起订量(v4.0.10827)和.Net 4,此代码有效:

var mock = new Mock<IFoo>();
var bar = mock.As<IBar>();
mock.SetupGet(m => m.Blah).Returns("Blah");
Assert.That(mock.Object.Blah, Is.EqualTo("Blah"));
bar.SetupGet(m => m.Blah).Returns("BlahBlah");
Assert.That(((IBar)mock.Object).Blah, Is.EqualTo("BlahBlah"));
Assert.That(mock.Object.Blah, Is.EqualTo("Blah"));

You must initialize your interface before setting up your property. 在设置属性之前,必须先初始化接口。

I think you need to use "override" instead of "new". 我认为您需要使用“替代”而不是“新”。 When you use "new", you're actually making a second function. 当使用“ new”时,实际上是在做第二个功能。 Here's the doc: http://msdn.microsoft.com/en-us/library/ms173153.aspx 这是文档: http//msdn.microsoft.com/en-us/library/ms173153.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM