本文介绍了如何创建包含一个只读成员的接口的单元测试存根?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一些单元测试因为我已经写在的IPrincipal 的扩展方法。为了帮助,我已经创建了几个辅助类的(一些代码,接口没有实现的成员已为简洁起见省略):

I am writing some unit tests for an extension method I have written on IPrincipal. To assist, I have created a couple of helper classes (some code for not-implemented members of the interfaces has been omitted for brevity):

public class IPrincipalStub : IPrincipal
{
    private IIdentity identityStub = new IIdentityStub();

    public IIdentity Identity
    {
        get { return identityStub; }
        set { identityStub = value; }
    }
}

public class IIdentityStub : IIdentity
{
    public string Name { get; set; } // BZZZT!!!
}



但是,名称的IIdentity 接口属性为只读(即的IIdentity 接口指定的名称一个getter而不是setter属性)。

However, the Name property in the IIdentity interface is read-only (the IIDentity interface specifies a getter but not a setter for the Name property).

我如何可以设置为测试目的我的存根对象的Name属性,如果接口定义了它作为一个只读属性?

How can I set the Name property in my stub object for testing purposes if the interface has defined it as a read-only property?

推荐答案

您正在使用自动属性C#功能,而是你应该去手动路线和属性创建一个支持字段。一旦你有一个支持字段,你可以在构造函数中设置它的值(或使它成为一个公共领域,并设置它,你有对象后,但是这是一个有点丑陋)。

You're using the auto-properties feature of C# but instead you should go the manual route and create a backing field for the property. Once you have a backing field you can set its value in the constructor (or make it a public field and set it after you have the object, but this is a little uglier).

public class IIdentityStub : IIdentity{
    private string _name;

    public IIdentityStub(string name){
        _name = name;
    }

    public string Name { get { return _name; } }
}

这篇关于如何创建包含一个只读成员的接口的单元测试存根?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 15:15