I have an ASP.NET Web Application and want to write some UT for the main controller.
Most of the controller methods are interactions with the UI. For instance, whenever the main page loads, it calls the controller to get all the users from the database through an API call.
This method is the one in the controller that get all the users.
public JsonResult GetAllUsers()
{
List<User> users = null;
try
{
users = new List<User>();
var allUsersJsonResults = Requests.GetFromUri(Settings.AllUsersUri);
users = JsonConvert.DeserializeObject<List<User>>(allUsersJsonResults.ToString());
return Json(new
{
usersDetails = users,
errorMessage = ""
}, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new
{
usersDetails = users,
errorMessage = "Error loading users"
}, JsonRequestBehavior.AllowGet);
}
}
This will be the method to do the actual call to the API
public static string GetFromUri(string fullUri)
{
HttpClientHandler handler = new HttpClientHandler
{
Credentials = Settings.ServiceCredential
};
using (HttpClient client = new HttpClient(handler))
{
return client.GetStringAsync(fullUri).Result;
}
}
Lastly, this is how the User class looks like
public class User
{
public int UserId {get; set;}
public string UserName {get; set;}
public string UserLastName {get; set;}
public int UserAge {get; set;}
public int UserNationality {get; set;}
}
What I am trying to do at this point is to write some Unit Tests to validate GetAllUsers() call but I am not sure how to do that. I think I should not call neither the Test or the Production API calls since they could return completely different data from time to time and make the Unit Tests fail but I am not sure how to 1) Test the controller without calling the server API and 2) mock some data to simulate the answer.