【问题标题】:Unit test for connection / C#连接单元测试/C#
【发布时间】:2016-11-28 11:10:09
【问题描述】:

为我的应用程序编写测试。想测试与异常处理的连接,现在我已经创建了可行的方法,看起来像:

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

在最终版本中,正在处理 smth 将捕获异常 - WebExeption。已经在我即将创建连接的方法中的 try / catch 块中使用它,它可以正常工作。但在我的测试中也需要它。我在想它应该看起来像:

[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 地址,这将导致 Web 异常。我怎样才能正确地写它?

【问题讨论】:

  • 在我看来,您应该使用 Assert.Throws 而不是 ExpectedExceptionAttribute。 Assert.Throws 的使用使其在您期望异常的地方更加明确。您的代码应如下所示:Assert.Throws &lt;WebException&gt;(() =&gt; connection.CreateConnection(...)。此外,NUnit 3.0 不正式支持 ExpectedExceptionAttribute。最后,您应该有两个独立的单元测试 - 一个用于有效连接,另一个用于无效连接。

标签: c# nunit webexception


【解决方案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"););
    }

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-01
    • 2021-03-19
    相关资源
    最近更新 更多