使用VB.Net的SameAs断言调用setter
本文关键字:断言 调用 setter SameAs VB Net 使用 | 更新日期: 2023-09-27 18:01:28
我发现一些奇怪的行为在nUnit?
下面的VB。Net测试失败:
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).
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
当c#代码正常工作时:
2 passed, 0 failed, 0 skipped, took 0.19 seconds (NUnit 2.5.5).
using System;
using System.Collections.Generic;
using NUnit.Framework ;
[TestFixture ]
class Dummy
{
private List<String> CallHistory;
private String mPropValue = "ThisIsIt";
[SetUp]
public void Setup()
{
CallHistory = new List<string>();
}
public String Prop1
{
get
{
CallHistory.Add("Prop1 Get");
return mPropValue;
}
set
{
CallHistory.Add("Prop1 Set");
mPropValue = value;
}
}
[Test]
public void UseSameAs()
{
Assert.That(Prop1, Is.SameAs(Prop1));
Assert.That(String.Join(",", CallHistory.ToArray()), Is.EqualTo("Prop1 Get,Prop1 Get"));
}
[Test]
public void UseaAreSame()
{
Assert.AreSame(Prop1, Prop1);
Assert.That(String.Join(",", CallHistory.ToArray()), Is.EqualTo("Prop1 Get,Prop1 Get"));
}
}
问题实际上不是对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))