1

单元测试时,我想检查 csv 格式的结果,所以我的测试中有以下代码。

MyDtoReq request = new MyDtoReq();
// ... assign some properties
string url = request.ToUrl("GET");
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
httpReq.Accept = "text/csv";
csv = new StreamReader(httpReq.GetResponse().GetResponseStream()).ReadToEnd();

如果请求成功,那效果很好。但是当它失败时,它会引发一个System.Net.WebException没有预期WebServiceException.ResponseStatus细节的问题。NUnit 报告异常如下:

Test Name:  TestReq
Test FullName:  [...].TestReq
Test Source:    c:\Users\[...]\UnitTestProject1\ServiceTests.cs : line 261
Test Outcome:   Failed
Test Duration:  0:00:27.104

Result Message: System.Net.WebException : The remote server returned an error: (400) Bad Request.
Result StackTrace:  at [...].TestReq() in c:\Users\[...]\UnitTestProject1\ServiceTests.cs:line 287

事实证明这是设计使然,因为大多数请求 csv 格式的客户端都无法解析ResponseStatus. 为了查看实际错误,我会在浏览器中使用 format=html 重新提交请求 - 令人沮丧的浪费时间。

4

1 回答 1

1

Here's how to get the actual error message from failing csv format requests:

// Declared in test setup
public const string Host = "http://localhost:1337";
private const string BaseUri = Host + "/";

[Test]
public void TestMyDtoReqCsvFormat()
{
    MyDtoReq request = new MyDtoReq();
    request.startDate = "20130919";
    request.endDate = "20130930";
    request.source = "Token";

    try
    {
        string requestUrl = request.ToUrl("GET");
        HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(requestUrl);
        httpReq.Accept = "text/csv";
        var csv = new StreamReader(httpReq.GetResponse().GetResponseStream()).ReadToEnd();
        // assert some facts about the contents of csv
    }
    catch (Exception)
    {
        try {
            JsonServiceClient client = new JsonServiceClient(BaseUri);
            MyDtoReqResponse response = client.Get(request);
            // do something if re-request succeeds (i.e. was a transient error)
        }
        catch (WebServiceException webEx) 
        {
            var message = webEx.ResponseStatus.ErrorCode +
                " " + webEx.ResponseStatus.Message.Trim() +
                " " + webEx.ResponseStatus.StackTrace.Trim();
            throw new WebException(message,webEx);
        }
        catch (Exception otherEx) {
            System.Diagnostics.Debug.WriteLine(otherEx.Message);
            throw new Exception(otherEx.Message, otherEx);
        }
    }
}
于 2013-10-01T16:52:38.383 回答