好的,我正在尝试使用模拟框架进行测试,并且我在VB.NET中工作,我是lambda表达式的新手,我之前的所有应用程序都是在2005或更早版本中编写的。我现在有2010年。 所以我尝试了Rhino.Mocks,但发现很难理解它,主要是因为语法较旧。既然,现在似乎没有人在VB.NET中使用博客,我一直在研究C#示例并试图弄清楚发生了什么。
所以我有一种情况,我将接口传递给类的构造函数并保持对该接口的引用。当在对象上调用一个方法并且引发了一个应该由实现接口的类处理的事件时。
我遇到了麻烦,所以我尝试在C#中创建一个简单的版本并重复vb.net中的步骤。
所以我的界面:
public interface IBroadcastClient
{
void MessageReceivedHandler(string msg);
}
引发事件的类:
public class Broadcaster
{
public Broadcaster(IBroadcastClient c)
{
_client= c;
this.SendMessage += new MessageReceived(_client.MessageReceivedHandler);
}
private IBroadcastClient _client;
public event MessageReceived SendMessage;
public void SendMessageNow()
{
string _Message;
if (SendMessage != null)
{
_Message = @"Yay!";
SendMessage(_Message);
}
}
}
测试:
[TestMethod]
public void TestSendMessageWithIgnoreParameter()
{
//string msg = @"Yay!";
var client = A.Fake<IBroadcastClient>();
Broadcaster b = new Broadcaster(client);
b.SendMessageNow();
A.CallTo(() => client.MessageReceivedHandler(A<string>.Ignored)).MustHaveHappened();
}
到目前为止,没有任何问题。
现在在vb.net中尝试相同的这个; 相同的接口和广播类,只是在vb.net而不是C#,最初是在单元测试后进行的。
<TestMethod()>
Public Sub TestMethod1()
Dim client = A.Fake(Of IBroadcastClient)()
Dim b As New Broadcaster(client)
b.SendMessageNow()
NextCall.To(client).MustHaveHappened()
client.MessageReceivedHandler(A(Of String).Ignored)
End Sub
此操作失败,并显示以下错误消息; “以下电话的断言失败: TestFakeItEasyVB.IBroadcastClient.MessageReceivedHandler(msg :) 预计会发现它至少一次,但在电话中发现#0次: 1:TestFakeItEasyVB.IBroadcastClient.MessageReceivedHandler(msg:“Yay!”)“
有趣地用这种方式写作;
<TestMethod()>
Public Sub TestMethod3()
Dim client = A.Fake(Of IBroadcastClient)()
Dim b As New Broadcaster(client)
b.SendMessageNow()
A.CallTo(Sub() client.MessageReceivedHandler(A(Of String).Ignored)).MustNotHaveHappened()
End Sub
同样的错误消息也会失败,但是,此版本的测试通过了。
<TestMethod()>
Public Sub TestMethod2()
Dim client = A.Fake(Of IBroadcastClient)()
Dim b As New Broadcaster(client)
b.SendMessageNow()
NextCall.To(client).MustHaveHappened()
client.MessageReceivedHandler("Yay!")
End Sub
这种变化也传递给C#,我的quandry是我做错了让测试忽略传递给伪造事件处理程序的参数?
答案 0 :(得分:0)
由于遗留原因,NextCall语法存在,最好使用表达式语法:
A.CallTo(Sub() client.MessageReceivedHandler(A(Of String).Ignored)).MustNotHaveHappened()
在上面的测试中,所有其他人都有MustHaveHappened,但是这个特定的有MustNotHaveHappened,我猜这就是你的测试失败的原因。我编译了你的代码并运行它,一旦它被改为MustHaveHappened,测试就会通过。
目前,您无法在特定于VB的“NextCall”-syntax中使用参数约束。但是,您可以使用“WhenArgumentsMatch”方法重写您的第一个测试:
<TestMethod()>
Public Sub TestMethod1()
Dim client = A.Fake(Of IBroadcastClient)()
Dim b As New Broadcaster(client)
b.SendMessageNow()
NextCall.To(client).WhenArgumentsMatch(Function(a) a.Get(Of String)(0) = "Yay!").MustHaveHappened()
client.MessageReceivedHandler(Nothing)
End Sub
或者您可以使用扩展名“WithAnyArguments”来忽略所有参数:
<TestMethod()>
Public Sub TestMethod1()
Dim client = A.Fake(Of IBroadcastClient)()
Dim b As New Broadcaster(client)
b.SendMessageNow()
NextCall.To(client).WithAnyArguments().MustHaveHappened()
client.MessageReceivedHandler(Nothing)
End Sub