连接单元测试/C#

Unit test for connection / 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");
        }

在 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 地址,它会导致网络异常。我怎样才能以正确的方式写它?

我认为您测试异常的方法没有任何问题。但是,我确实建议您将测试分成两个测试 - 一个用于获得有效连接的情况,另一个用于获得不良连接的情况。

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

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