2016-11-28 7 views
0

私のアプリケーションのテストを書く。 WebExeption - 例外をキャッチしますなめらかに取り組んfinallバージョンでは接続/ Cのユニットテスト

 [Test] 
     public void TestCreateConnection() 
     { 
      Connection testConnection = new Connection(); 
      connection.CreateConnection(correctURL, IDName + connection.ApiKey, connection.ContentType, connection.MediaType, connection.Get, false, "name"); 
      testConnection.CreateConnection(correctURL, IDName + connection.ApiKey, connection.ContentType, connection.MediaType, connection.Get, false, "name"); 
     } 

:作品とのように見える今、私が作成している方法のため、exeptionハンドリングとの接続をテストしたいと思います。すでに接続を作成しようとしている私の方法の中にtry/catchブロックで既に持っている、それはofcの動作します。しかし、私のテストでもそれが必要です。私たちが見ることができるように私は、URLアドレスであるメソッドの最初の引数を変更し

[Test] 
     [ExpectedException(typeof(WebException))] 
     public void TestCreateConnection() 
     { 
      Connection testConnection = new Connection(); 
      connection.CreateConnection(correctURL, IDName + connection.ApiKey, connection.ContentType, connection.MediaType, connection.Get, false, "name"); 

      testCconnection.CreateConnection(correctURL, IDName + connection.ApiKey, connection.ContentType, connection.MediaType, connection.Get, false, "name"); 
      Assert.Catch<WebException>(() => connection.CreateConnection("test", IDName + connection.ApiKey, connection.ContentType, connection.MediaType, connection.Get, false, "name");); 
     } 

、それはウェブexeptionをカウスます:私はそれが必要考えていたことのように見えます。どうすれば正しい方法で書くことができますか?

+0

私の意見では、ExpectedExceptionAttributeの代わりにAssert.Throwsを使用するべきです。 Assert.Throwsを使用すると、例外が予想される場所が明示的になります。あなたのコードは次のようになります: 'Assert.Throws (>)connection.CreateConnection(...)'さらに、NUnit 3.0はExpectedExceptionAttributeを公式にサポートしていません。 1つは有効な接続用であり、もう1つは無効な接続用です。 –

答えて

0

例外をテストする方法に間違いはないと思います。しかし、私はあなたのテストを2つのテストに分割することをお勧めします.1つは有効な接続を取得する場合、もう1つは接続が不良な場合です。

[Test] 
    public void WhenCorrectUrlIsPassedConnectionCreatedSuccessfully() 
    { 
     Connection testConnection = new Connection(); 
     connection.CreateConnection(correctURL, IDName + connection.ApiKey, connection.ContentType, connection.MediaType, connection.Get, false, "name"); 
    } 

    [Test] 
    [ExpectedException(typeof(WebException))] 
    public void WhenIncorrectUrlIsPassedThenWebExceptionIsThrown() 
    { 
     Connection connection = new Connection(); 
     Assert.Catch<WebException>(() => connection.CreateConnection("test", IDName + connection.ApiKey, connection.ContentType, connection.MediaType, connection.Get, false, "name");); 
    } 

これは、テスト接続の実装方法の詳細がわからないためです。接続の作成を担当する内部コンポーネントがあり、そのコードがその周りのラッパーである場合は、内部コンポーネントをInterfaceとして渡し、その動作を嘲笑することを検討する必要があります。