Click here to Skip to main content
15,867,453 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Please help me how do I write a test for the following controller without changing the program code ???

***ProductController:***
C#
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> CreateProductAsync(ProductDTO objProduct)
{
    if (ModelState.IsValid)
    {
        HttpClient client = new HttpClient
        {
            BaseAddress = new Uri("http://localhost:2090")
        };
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        HttpResponseMessage response = await client.PostAsJsonAsync<ProductDTO>("/api/Product/Create/{product}", objProduct);
        var ProductDetails = response.Content.ReadAsStringAsync().Result;
        if (response.IsSuccessStatusCode)
        {
            TempData["Message"] = ProductDetails;
            return View();
        }
        ViewBag.MessageViewCreate = ProductDetails;
        return View();
    }
    else { return View(); }
}


What I have tried:

The following test was written using the RichardSzalay.MockHttp library, which encountered an error:

***ProductControllerTest:***
C#
[Fact]
public async System.Threading.Tasks.Task CreateProductAsync_ReturnsViewForCreateProductAsync()
{           
    var mockHttp = new MockHttpMessageHandler();
    var product = new ProductDTO
    {
        ProductName = "Product01",
        ProductPrice = 535             
    };            
    mockHttp.When(HttpMethod.Post, "http://localhost:2090//api/Product/Create/{product}")
        .Respond(HttpStatusCode.OK, "application/json","");
    var client = new HttpClient(mockHttp);
    HttpResponseMessage response = await client.PostAsJsonAsync<ProductDTO>("/api/Product/Create/{product}", product);
    //var response = await client.PostAsJsonAsync<ProductDTO>("http://localhost:2090/api/Product/Create/{product}", product);         
    var ProductDetails = await response.Content.ReadAsStringAsync();
    var result = productController.CreateProductAsync(product);           
    Assert.IsType<ViewResult>(result.Result);
}

Thanks
Posted
Updated 16-Apr-20 3:56am
v2

1 solution

You can't, if you want your code to be unit testable you have to write it with unit testing in mind.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900