我试图找出为什么我对以下给定代码的单元测试没有显示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);
}
我无法通过此单元测试获得完整的代码覆盖率。我在这里进行单元测试时出错了。
答案 0 :(得分:2)
您没有测试方法的捕获路径。
编写另一个抛出异常的unittest。
我会使用ExpectedException
属性:
[ExpectedException(typeof(Exception), "No exception was thrown.")]
答案 1 :(得分:0)
将您的代码作为基础,以确保代码覆盖率增加,您仍然缺少更多案例:
单元测试以测试request == null
单元测试以确保正确抛出异常。
希望得到这个帮助。