如何进行返回类型为Void的私有方法的断言阶段?

时间:2016-11-15 07:41:13

标签: c# unit-testing private-methods

我有一个私有方法的课程

public class MyClass 
{
    private void SomeMethod(PrimaryAllocationDP packet)
    {
        ........................
        some code
        ........................
        packet.AllocatedAgency = AgencyAllocated;
    }
} 

现在通过使用MSUnit Testing框架,到目前为止我已经写过了

[TestMethod]
public void TestAllocatedAgency()
{ 

    var packet = new Fixture().Create<PrimaryAllocationDP>(); //used AutoFixture here

    PrivateObject accessor = new PrivateObject(new MyClass());     

    accessor.Invoke("SomeMethod", packet); //Act

    // what will be the Assert? Since it is void
}

什么是断言?由于它是无效的,我怎么能写断言?

2 个答案:

答案 0 :(得分:2)

很好,在示例中,测试中的方法是对其参数/依赖项进行更改,您可以声明调用该函数的所需结果是数据包的AllocatedAgency属性实际上是不是null

[TestMethod]
public void TestAllocatedAgency() { 
    //Arrange
    var packet = new Fixture().Create<PrimaryAllocationDP>(); //used AutoFixture here
    var sut = new MyClass();
    var accessor = new PrivateObject(sut);     

    //Act
    accessor.Invoke("SomeMethod", packet);

    //Assert
    Assert.IsNotNull(packet.AllocatedAgency);
}

答案 1 :(得分:0)

如果您可以更改PrimaryAllocationDP,还可以添加新界面IPrimaryAllocationDP并测试属性设置。在我的测试中,我假设AllocatedAgency是object类型,我正在使用Moq。但也许您也可以使用AutoFixture进行嘲弄?为了更清楚,我直接在AgencyAllocated

中设置了MyClass
[TestFixture]
public class DependencyInjection
{
    [TestMethod]
    public void TestAllocatedAgency()
    {
        var packet = new Mock<IPrimaryAllocationDP>();

        PrivateObject accessor = new PrivateObject(new MyClass());

        accessor.Invoke("SomeMethod", packet.Object); //Act

        packet.VerifySet(p => p.AllocatedAgency = 42);
    }
}

public interface IPrimaryAllocationDP
{
    //object or any other type
    object AllocatedAgency { set; }
}

public class PrimaryAllocationDP : IPrimaryAllocationDP
{
    public object AllocatedAgency { set; private get; }
}

public class MyClass
{
    private readonly object AgencyAllocated = 42;

    private void SomeMethod(IPrimaryAllocationDP packet)
    {
        //........................
        //some code
        //........................
        packet.AllocatedAgency = AgencyAllocated;
    }
}