FakeItEasy-新修饰符的问题 [英] FakeItEasy - problems with new modifier

查看:75
本文介绍了FakeItEasy-新修饰符的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码似乎不符合我的预期:

It appears that the following code doesn't behave as I would expect:

using FakeItEasy;
using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        var derived = A.Fake<IDerived>();
        A.CallTo(() => derived.Dependency).Returns(null);

        IBase baseObj = derived;
        Assert.IsNull(baseObj.Dependency); //Fails
    }
}

public interface IDerived : IBase
{
    new IDependency Dependency { get; }
}

public interface IBase
{
    IDependency Dependency { get; }
}

public interface IDependency
{
}

不是返回null,而是轻松返回IDependency的伪实例.也许是设计使然?无论如何,我将如何解决此问题并确保baseObj.Dependency返回配置的内容?

Instead of returning null, fake it easy returns a fake instance of IDependency. Perhaps by design? Anyway, how would I go around this problem and ensure baseObj.Dependency returns what was configured?

推荐答案

这是正常现象. IDerived现在有两个成员.一种是从IBase继承而来的,另一种是在IDerived中定义的.

This is normal behavior. IDerived now has two members. One inherited from IBase and one defined in IDerived.

在测试方法中,您正在使用FakeItEasy设置IDerived中的值.

In your test method, your are using FakeItEasy to set the value of the one in IDerived.

未设置IBase的成员.因此,它获得了FakeItEasy给它的默认值,它是一个模拟的IDependency.

The member from IBase was not set. So it get the default value that FakeItEasy gives it which is a mocked IDependency.

如果要设置它,请使用以下代码:

If you want to set it, use the following code:

IDerived derived = A.Fake<IDerived>();

IBase baseObj = derived;

A.CallTo(() => baseObj.Dependency).Returns(null);

Assert.IsNull(baseObj.Dependency); //No error here

在此代码中,我们将设置IDerived的另一个成员,即基本接口中定义的依赖项.

In this code, we are setting the other member of IDerived, which is the dependency defined in the base interface.

这篇关于FakeItEasy-新修饰符的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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