I run my tests inside nUnit and normally I can mock out dependencies and have then Return certain values or throw errors.
I have a class that as an internal HttpClient and I would like to test the class, what are my options.
here is my code, its not complete so as not to flood the message. As you can see I am using the HttpClient internally and not injected as a dependency. The class throws a number of custom exceptions, I would like to Moq these otherwise I need to pass REAL username and passwords that would give me the status codes i required to throw the exceptions.
Anyone have an ideas? If I can't mock the httpclient then i can never test my class that it raises exceptions.
Do I really have to change HttpClient to a dependency on the constructor ?
public bool ItemsExist(string itemValue) { var relativeUri = string.Format(UrlFormatString, itemValue.ToUpper()); var uri = new Uri(new Uri(this.baseUrl), relativeUri); using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", this.encodedCredentials); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); var response = client.GetAsync(uri).Result; switch (response.StatusCode) { case HttpStatusCode.Unauthorized: // DO something here throw new CustomAuthorizationException(); case HttpStatusCode.Forbidden: throw new CustomAuthenticationException(); } return true;