即使通过测试,我怎样才能确认我的方法正确性

时间:2017-01-24 05:32:00

标签: c# unit-testing asp.net-web-api

这里我使用WebApi2和部门控制器

[Route("api/Employee")]
public HttpResponseMessage GetEmp()
{
    var x = objEmp.GetEmployee();
    if (x != null)
        return Request.CreateResponse(HttpStatusCode.OK, x);
    else
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Not-Found..");
}

当我在Fiddler中测试上面的代码时,它运行正常。但是当我在UNIT TEST中测试它显示Test-Pass但我怎么知道我的数据在哪里?

[TestClass]
public class App1
{
    [TestMethod]
    public  void GetEmpMethod()
    {
        var config = new HttpConfiguration();
        //configure web api
        config.MapHttpAttributeRoutes();

        using (var server = new HttpServer(config))
        {
            var client = new HttpClient(server);

            string url = "http://localhost:3609/api/Employee";

            var request = new HttpRequestMessage
            {
                RequestUri = new Uri(url),
                Method = HttpMethod.Get
            };

            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您似乎无法在单元测试中发送请求。以下是如何做到这一点并阅读回复:

CalendarViewDayItem

另外值得一提的是,如果要测试的Web API控制器位于单元测试的单独项目中,则可能需要自定义程序集解析程序。否则您将收到404错误:

CalendarViewDayItemChanging

您将在单元测试中注册:

// act
var result = client.SendAsync(request).GetAwaiter().GetResult();

// assert
result.EnsureSuccessStatusCode();
var actual = result.Content.ReadAsAsync<Employee>().GetAwaiter().GetResult();
... assert on the actual employee instance here

此外,如果您使用的单元测试框架支持异步测试方法,那么这可能是首选方式:

public class TestWebApiResolver : IAssembliesResolver
{
    public ICollection<Assembly> GetAssemblies()
    {
        return new[] { typeof(EmployeesController).Assembly };
    }
}