Nunit,由事件处理程序引发的测试异常

本文关键字:测试 异常 程序 事件处理 Nunit | 更新日期: 2023-09-27 18:29:48

我有两个类,服务器和客户端,我想测试当客户端发送未知或错误的数据类型时,服务器是否会抛出异常。

我写了以下内容,但它不起作用,因为它不是抛出异常的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 ] ) );
    }

如果解释很难理解,很难解释,请用一只手打字:(

Nunit,由事件处理程序引发的测试异常

我在寻找做大致相同事情的方法时发现了这个问题。这就是我后来采取的方法:

...
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);