2016-11-28 131 views
0

为我的应用程序编写测试。想测试与exeption处理连接,其工作原理和貌似现在我已经创建方法:单元测试连接/ 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"); 
     } 

在finall版本上的不便,这将赶上异常工作 - WebExeption。已经在我的方法里面的try/catch块中创建连接,它的作用就是c。但是在我的测试中也需要它。我想它应该是这样的:

[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");); 
     } 

就像我们可以看到,我改变这是URL地址的方法的第一个参数,它会淡然网络exeption。我怎样才能以正确的方式写出来?

+0

在我看来,你应该使用Assert.Throws而不是ExpectedExceptionAttribute。 Assert.Throws的使用使得它更加明确你希望发生异常的地方。你的代码应该如下所示:'Assert.Throws (()=> connection.CreateConnection(...)'。此外,NUnit 3.0并没有正式支持ExpectedExceptionAttribute。最后,你应该有两个独立的单元测试 - 一个用于有效连接,一个用于无效连接。 –

回答

0

我不认为你测试异常的方法有什么问题。然而,我建议你将测试分成两个测试 - 一个用于获得有效连接的情况,另一个用于连接不良的情况。

[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");); 
    } 

这不知道你如何实现测试连接的确切细节。如果您有一些负责创建连接的内部组件,并且您的代码是一个包装器,那么您应该考虑将内部组件作为接口传递并嘲笑它的行为。