1

我试图找出为什么我对以下给定代码的单元测试在 vs2010 中没有显示完整的代码覆盖率。这是我用来获取记录的方法。

public Records GetTestRecords(HttpWebRequest request)
{
    var Records = new Records();

    try
    {
        if (null != request)
        {
            var response = (HttpWebResponse)request.GetResponse();

            using (var sr = new StreamReader(response.GetResponseStream()))
            {
                jsonResult = sr.ReadToEnd();
            }

            Records = myHelper.Deserialize<Records>(jsonResult);
        }
    }
    catch (Exception exception)
    {

        throw (exception);
    }

    return Records;
}

这是我对上述方法的单元测试

[TestMethod()]
    public void GetRecordsTest()
    {
        string mockjsonResult = "{\"recordId\":\"8cccf2deb-4dde-450c-97cd-a6ec\",\"billingAccountId\":\"fake\",\"userid\":81233,\"Checkid\":2533004436741,\"partName\":\"redcredetest\",\"Description\":\"not yet pulling- test\",\"productId\":\"rr43556-23re\",\"created\":\"2013-04-12T21:09:54.4890986Z\",\"enddate\":null,\"autoRenewal\":true,\"changeLog\":{\"reason\":\"dummy.\",\"state\":1,\"time\":\"2013-04-12T21:09:54.48126Z\",\"extensions\":null,\"transactionId\":null}}";


        var mocrequest = HttpWebRequest.Create("http://social.stackoverflowtest.com/Forums/getfile/2234");
        myProvider target = new myProvider (); 
        HttpWebRequest request = (HttpWebRequest)mocrequest;
        request.Method = "GET";
        request.ContentType = "application/json"; 
        Records records = GetMockRecords();
        string jsonResult = string.Empty;

        var mockWebResponse = request.GetResponse();
        var response = (HttpWebResponse)request.GetResponse();
        using (var sr = new StreamReader(response.GetResponseStream()))
        {
            jsonResult = sr.ReadToEnd();
        }

        records = MyHelper.Deserialize<Records>(mockdjsonResult);
        Assert.IsNotNull(records.ProductId);
    }

我无法通过此单元测试获得完整的代码覆盖率。我在这里的单元测试做错了什么。

4

2 回答 2

2

好吧,您没有测试方法的捕获路径。

编写另一个引发异常的单元测试。

我会使用ExpectedException属性:

[ExpectedException(typeof(Exception), "No exception was thrown.")]
于 2013-04-23T13:28:42.170 回答
0

以您的代码为基础,以确保增加代码覆盖率,您仍然缺少更多案例:

  1. 用于测试用例的单元测试 request == null

  2. 单元测试以确保正确抛出异常。

希望这有帮助。

于 2013-04-23T13:36:50.030 回答