[英]Nunit, test exception thrown by event handler
I have 2 classes, server and client, and I'd like to test that the server throws an exception when the client sends an unknown or wrong data type.我有 2 个类,服务器和客户端,我想测试当客户端发送未知或错误的数据类型时服务器是否抛出异常。
I wrote the following but it doesn't work since it's not the Send function that throws the exception:我写了以下内容,但它不起作用,因为抛出异常的不是发送函数:
// Unit test
var serverEventRaised = new ManualResetEvent( false );
Assert.That( () =>
{
_server.DataReceived += ( sender, args ) =>
{
// Should not reach here since exception should be thrown before raising event
Console.WriteLine( "Server received data" );
serverEventRaised.Set();
};
_client.Send( new[] { "html", "<html><head><title>test</title></head><body>test</body></html>" } );
}, Throws.Exception.TypeOf< Exception >() );
Assert.That( serverEventRaised.WaitOne( 5000 ), Is.False );
The server itself gets the event from its socket before raising another event:服务器本身在引发另一个事件之前从其套接字获取事件:
// Server class
public event EventHandler< CustomEventArgs > DataReceived;
private void OnMessageReceived( object sender, MySocketEventArgs args )
{
var dataType = args.Data[ 0 ].GetString();
switch ( dataType )
{
case "text":
// Do something
break;
case "image":
// Do something else
break;
default:
throw new Exception( "Unknown type" );
}
// Raise DataReceived event
var handler = DataReceived;
handler?.Invoke( this, new CustomEventArgs( args.Data[ 1 ] ) );
}
Sorry if the explanations are difficult to understand, hard to explain and typing with 1 hand:(抱歉,如果解释难以理解,难以解释并用一只手打字:(
I found this question while looking for a way of doing roughly the same thing.我在寻找一种方法来做大致相同的事情时发现了这个问题。 This is the approach I subsequently took:
这是我后来采取的方法:
...
bool exceptionWasThrown = false;
try
{
_client.Send( new[] { "html", "<html><head><title>test</title></head><body>test</body></html>" } );
}
catch(Exception e)
{
//Check the exception details here too
exceptionWasThrown = true;
}
Assert.IsTrue(execptionWasThrown);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.