C#模拟一个带有内部属性设置器的类 [英] C# Mock a Class With an Internal Property Setter

查看:81
本文介绍了C#模拟一个带有内部属性设置器的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试建立单元测试. Position类是在第三方库中实现的.但是对于我的单元测试,我需要将Size属性设置为特定值.

I am trying to build a unit test. The class Position is implemented in a third party library. But for my unit test I need the Size property to be set to a specific value.

public class Position
{
    private double _size;

    private double Size
    {
        get
        {
            return _size;
        }

        internal set
        {
            _size = value;
        }
    }
}

我阅读了这篇文章:

I read this post: How do you create a unit-testing stub for an interface containing a read-only member? but could not figure out how to make it work for me.

这是被测试的类(只是一个简化的示例). CalcPositionMetric()方法中的pos参数必须为Position类型:

This is the class under test (just a simplified example). The posargument in the CalcPositionMetric() method must be of type Position:

public class PositionMetrics
{
    public PositionMetrics()
    {}

    public double CalcPositionMetric(Position pos)
    {
        return 2 * pos.Size;
    }
}

这是我的单元测试的一部分:

Here is a piece of my unit test:

using NUnit.Framework;
using NMock;

[TestFixture]
public class PositionUnitTests
{
    [Test]
    public void TestPosition()
    {
        Mock<Position> tmpPosMock   = mFactory.CreateMock<Position>();
        tmpPosMock.Expects.One.GetProperty(v => v.Size).WillReturn(7); /* !!! Exception !!! System.ArgumentException : mock object position has a getter for property Size, but it is not virtual or abstract */

        /* Execute Test with  tmpPositions*/
        PositionMetrics pm = new PositionMetrics();
        double result      = pm.CalcPositionMetric(tmpPosMock.MockObject)
        Assert.AreEqual(14, result);
    }
}

但是正如您所看到的,我得到了一个例外.有人可以帮我解决这个问题吗?也欢迎任何其他解决方案!

But as you can see I get an exception. Could somebody help me to resolve this problem? Any other solutions are also welcome!

欢呼 康斯坦丁

推荐答案

已更新问题的新答案我建议您为此引入某种代理接口.请参见下面的代码:

New answer for the updated question I suggest you to introduce some kind of a proxy interface for that. See the code below:

interface IPosition { 
    int Size { get; }
}
class Position { //in 3rd party lib
    public int Size {
        get { return 5; }
    }
}
class RealPosition : IPosition { //use this as your real object instead of using Position directly
    private Position position;
    public RealPosition(Position position) {
        this.position = position;
    }
    public int Size {
        get { return position.Size; }
    }
}
class MockPosition : IPosition { //use this for testing
    public int Size{ get; set; }
}
public class Program {
    static void Main(string[] args) {
        var pos = new MockPosition { Size = 7 };
        Console.WriteLine(Calc(pos));    //prints 14
        Console.ReadLine();
    }
    static int Calc(IPosition pos) { //change your method signature to work with interface
        return pos.Size * 2;
    }       
}

旧答案.如果该类不是sealed,则不需要任何模拟库.只需对所需的属性使用new修饰符,如下所示:

Old answer If the class is not sealed you don't need any mocking libraries. Just use the new modifier for the required properties like this:

class Position {
    public int Size { get { return 5; } }
}

class MockPosition : Position {
    public new int Size { get; set; }
}
....
var mock= new MockPosition();
mock.Size = 7;

要在某种列表中使用这些项目,您必须像这样对它们进行投射:

To use these items in some sort of list you'll have to cast them like this:

var items = new List<Position>();
for (int i = 0; i < 5; i++) {
      items.Add(new MockPosition { Size = i });
}
foreach (var item in items.Cast<MockPosition>()) {
       Console.Write("{0}\t", item.Size); //prints 0 1 2 3 4
}

如果它是密封的并且该属性不是虚拟的,那么您将不得不使用其他一些技术,Moq(我想您正在使用)不允许这样做

If it is sealed and the property is not virtual than you'll have to use some other techniques, Moq (which I guess you are using) does not allow that

这篇关于C#模拟一个带有内部属性设置器的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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