在编写单元测试时,我想使用 Assert.AreSame(..)
针对 Nullable<T>
类型,我得到了意想不到的结果。然后我意识到下面的代码失败了:
int? k = 10;
Assert.IsTrue(ReferenceEquals(k, k));
这里发生了什么?
此外,我如何确保我的方法返回的实例与我传递给模拟/ stub 的实例完全相同,而不仅仅是执行 return 10
?
编辑:
我通常会执行以下操作以确保我在单元测试中获得一致的结果:
//Arrange
var result = new string(new[] {'1', '2', '3'});
mock.SetUp(x => x.Method("something").Returns(result);
//Act here
//Assert
Assert.AreSame(result, instance.ValueAssigned);
如果我这样做 return "123"
里面Method(..)
,上述测试将失败。我试图找到一种对 Nullable 执行相同操作的方法。
最佳答案
What is happening here?
两个参数都被装箱到不同的对象。
想象一下您的代码实际上是这样的:
int? k = 10;
object x = k; // Boxing operation 1
object y = k; // Boxing operation 2
Assert.IsTrue(ReferenceEquals(x, y));
不要忘记可为 null 的值类型仍然是值类型 - 因此当您将它们转换为引用类型表达式时它们会被装箱。
Also, how can I make sure my method is returning the very same instance I passed to the mock/stub and not just doing return 10?
对于值类型,这个问题根本没有意义。基本上,对引用类型使用 Assert.AreSame
,对值类型使用 Assert.AreEqual
。请注意,这与可空性无关。 Assert.AreSame(10, 10)
也会失败。
关于c# - ReferenceEquals 和 Nullable<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20087704/