We have decided to create an HTTP logger which can be reused across multiple projects, we created a utility which looks like this.
// pseudo-code
public class HttpLog{
private readonly string uri;
private readonly RestClient client;
public HttpLog(string uri){
this.uri = uri;
// notice the initialization of rest client
this.client = new RestClient();
}
void write(object data){
this.client.uri = this.uri + endpoint;
this.client.postAsync(data);
}
}
The consumer should provide the URI and we have exposed public write methods to log the data, however, we are unable to unit test our HttpLog
class since it initializes the rest client. We are not using dependency injection since we are creating utility.
Any help would be greatly appreciated on how to refactor or unit test .write()
method.
We can think of two methods
- Constructor overload (which is not an efficient way just to unit test)
- making client property as public {get; set} which also breaks OOP principle.
Please let us know if there is a better way to unit-test this code.
The answers below stated to use constructor overloading or making the property to public
Why I am not preferring dependency injection or constructor overload because of I strongly believe the consumer/client should not care or worry about the implementation details. They should be as much as abstraction possible. If you make them in constructor overload then you are making a way to pollute the abstraction.
For example, if you are using RestClient or HttpClient they don't ask you to provide HTTP implementation on how to write data, they simply ask you URI and data to post that is what a true abstraction is to end user.
Please correct me If my assumptions are wrong