我在nUnit中发现了一些奇怪的行为吗?
以下VB.Net测试失败:
strcpy(msgf, g_fxn());
Test 'SameAsTest.UseSameAs' failed:
Expected string length 19 but was 29. Strings differ at index 19.
Expected: "Prop1 Get,Prop1 Get"
But was: "Prop1 Get,Prop1 Get,Prop1 Set"
------------------------------^
SameAsTest.vb(33,0): at SameAsTest.UseSameAs()
1 passed, 1 failed, 0 skipped, took 1.80 seconds (NUnit 2.5.5).
当c#equiv正常工作时:
Option Strict On
Imports System
Imports System.Collections.Generic
Imports NUnit.Framework
<TestFixture()>
Public Class SameAsTest
Private CallHistory As List(Of String)
Private mPropValue As String = "ThisIsIt"
Public Property Prop1 As String
Get
CallHistory.Add("Prop1 Get")
Return mPropValue
End Get
Set(ByVal value As String)
CallHistory.Add("Prop1 Set")
mPropValue = value
End Set
End Property
<SetUp()>
Public Sub Setup()
CallHistory = New List(Of String)
End Sub
<Test()>
Public Sub UseSameAs()
Assert.That(Prop1, [Is].SameAs(Prop1))
Assert.That(String.Join(",", CallHistory.ToArray()), [Is].EqualTo("Prop1 Get,Prop1 Get"))
End Sub
<Test()>
Public Sub UseAreSame()
Assert.AreSame(Prop1, Prop1)
Assert.That(String.Join(",", CallHistory.ToArray()), [Is].EqualTo("Prop1 Get,Prop1 Get"))
End Sub
End Class
2 passed, 0 failed, 0 skipped, took 0.19 seconds (NUnit 2.5.5).
答案 0 :(得分:3)
问题实际上是对SameAs
的调用。问题是属性是作为Assert.That
调用的第一个参数传递的。
Assert.That
有许多不同的重载,事实证明,在VB到C#中,重载决策的执行方式不同。在C#中,属性与以下内容匹配:
Asset.That(object actual, IResolveConstraint expression);
在VB中,它被匹配:
Assert.That<Of T>(ByRef T actual, IResolveConstraint express);
由于VB版本实际上是将非引用属性值传递给期望引用的方法,因此它似乎通过创建本地字符串来模拟引用传递,通过引用将其传递给方法然后设置属性的值到字符串的返回值。我不确定它为什么选择这种方式,硬核VB程序员可能会解释它。
您可以通过声明局部变量并将其用于第一个参数来解决它:
Dim prop1 = Prop1
Assert.That(prop1, [Is].SameAs(Prop1))
或者通过强制转换参数来强制它使用That
方法的预期重载。
Assert.That(CType(Prop1, Object), [Is].SameAs(Prop1))