即使经过测试的方法运行正常,UnitTesting总是返回错误的请求

时间:2018-06-19 13:02:55

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

我想对以下方法执行单元测试:

public HttpResponseMessage PostUser(User obj)
    {
        try
        {
            bool error = false;
            string errorMessage = "";

            if (obj.FullName == "")
            {
                error = true;
                errorMessage += "Please do not leave name area empty. ";
            }

            //Several other if statements to check everything is filled as expected by the user

            if(!error)
            {
                db.Users.Add(obj);
                db.SaveChanges();

                var response = Request.CreateResponse(HttpStatusCode.Created, obj);
                response.Headers.Location = new Uri(Request.RequestUri + obj.ID.ToString());
                return response;
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, errorMessage);
            }                
        }
        catch (Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
        }
    }

我知道该方法的性能很好,因为它可以将数据插入数据库而不会弹出任何错误。因此,我观看了一些视频并检查了与UnitTesting有关的其他问题,但是很遗憾,它无法使测试响应等于预期响应。下面是我的测试用例:

[TestClass]
public class ProcessControllerTests
{
    private readonly ProcessController _processController;

    public ProcessControllerTests()
    {
        _processController = new ProcessController
        {
            Request = new System.Net.Http.HttpRequestMessage(),
            Configuration = new System.Web.Http.HttpConfiguration()
        };
    }

    [TestMethod]
    public void PostUser()
    {
        User testUser = new User
        {
            ID = 10,
            FullName = "Test User",
            Email = "test@unit.com",
            UserName = "TestU",
            Password = "teus123456"
        };

        var testResponse = _processController.PostUser(testUser);

        Assert.AreEqual(HttpStatusCode.Created, testResponse.StatusCode);
    }
}

我不确定我在哪里犯错。

谢谢!

0 个答案:

没有答案