0

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

        [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 exeption。我怎样才能以正确的方式编写它?

4

1 回答 1

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

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

于 2016-11-28T11:37:05.367 回答