question

samSol-2232 avatar image
0 Votes"
samSol-2232 asked samSol-2232 commented

Unit Testing Issue

Dear All,

I want to add Unit testing functionality for my following code

 public class MyImage
     {
         public string ImageID { get; set; }
         public string ImageFullName { get; set; }
         public string ImageURL { get; set; }
         public string ImageDimensions { get; set; }
     }
 [Route("api/[controller]")]
     [ApiController]
     public class ImageController : ControllerBase
     {
         [HttpGet("{id}")]
         public string Get(string date)
         {
             string result = string.Empty;
             var url = "https://myurl.com";
             var httpRequest = (HttpWebRequest)WebRequest.Create(url);
             var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
             using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
             {
                 result = streamReader.ReadToEnd();
    
             }
             return result;
         }
    
     }


Any help would be greatly appreciated

dotnet-csharpdotnet-aspnet-core-webapi
· 7
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Your design is not unit testable. Plus the date parameter and MyImage class are not used so it is not clear why you are showing us these items.

Unit testable code typically revolves around an interface. This allows you to mock operations like making an HTTP request or fetching data from a database. Unit tests are usually only concerned with the data from an HTTP request or database query.

Can you explain the expected results if the unit test? What are you testing exactly?

1 Vote 1 ·

Any one please?

0 Votes 0 ·

As stated, your code cannot be unit tested. IMHO, you need to take some unit testing classes and learn how to unit test.

If you were going to unit test the controller, the code you have in the controller action method would be moved to a class in the Models folder with the class using an Interface and the class/object would be dependency injected into the controller. Because DI of the object into the controller, you can use a mocking framework such as Moq and mocked out the object and returned some mocked/fake data in the unit test.



0 Votes 0 ·

My Unit test should return a valid JSON result. I want to use mock operations. A sample code would be greatly appreciated. My code is in the controller

0 Votes 0 ·
Show more comments

0 Answers