我有一个私有方法的课程
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
}
什么是断言?由于它是无效的,我怎么能写断言?
答案 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;
}
}