繁体   English   中英

使用 moq 和 xunit 测试由另一个类方法返回的类对象的私有成员

[英]Testing private members of a class object returned by another class method using moq and xunit

我有一个这样的场景:

public class A
{
    private int p1;

    public A(int x)
    {
        p1 = x;
    }
}

public class B
{
    public A Func1(int x)
    {
        if (x < 0)
        {
            return (new A(-1 * x));
        }
        else
        {
            return (new A(x));
        }
    }
}

我想知道有哪些选项可以测试Func1是否正确设置了返回对象的p1属性。

谢谢!

你总是可以通过反射到达一个领域:

[Fact]
public void TestMethod()
{
    A a = new B().Func1(-15);

    Assert.Equal(15,
        (int)a.GetType().GetField("p1", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).GetValue(a));
}

暂无
暂无

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

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