我有2个类,服务器和客户端,我想测试服务器在客户端发送未知或错误的数据类型时抛出异常。
我编写了以下内容,但它不起作用,因为它不是抛出异常的Send函数:
// 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 );
服务器本身在引发另一个事件之前从其套接字获取事件:
// 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 ] ) );
}
很抱歉,如果解释难以理解,很难用一只手解释和打字:(
答案 0 :(得分:0)
我在寻找一种做大致相同事情的方法时发现了这个问题。这是我后来采取的方法:
...
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);