我的单元测试中有这个奇怪的问题.请参阅以下代码
_pos = null;
Utilities.InitPOS(_pos, trans);
Assert.IsNotNull(_pos); //fails
Run Code Online (Sandbox Code Playgroud)
该InitPOS功能看起来像
public static void InitPOS(POSImplementation pos, Transaction newTransaction)
{
pos = new POSImplementation();
pos.SomeProp = new SomeProp();
pos.SomeProp.SetTransaction(newTransaction);
Assert.IsNotNull(pos);
Assert.IsNotNull(pos.SomeProp);
}
Run Code Online (Sandbox Code Playgroud)
该对象POSImplementation是一个接口的实现,它是一个类,所以它是一个引用类型...
任何的想法?
您将对象的引用传递给InitPOS(即null引用),而不是对名为的变量的引用_pos.其效果是,新的POSImplementation实例被分配给本地变量pos的InitPOS方法,但是_pos变量保持不变.
将您的代码更改为
_pos = Utilities.InitPOS(trans);
Assert.IsNotNull(_pos);
Run Code Online (Sandbox Code Playgroud)
哪里
public static POSImplementation InitPOS(Transaction newTransaction)
{
POSImplementation pos = new POSImplementation();
// ...
return pos;
}
Run Code Online (Sandbox Code Playgroud)