Skip to content

Instantly share code, notes, and snippets.

@osmyn
Created August 1, 2016 22:34
Show Gist options
  • Save osmyn/e81fc90982f86f49c86309c14fee179d to your computer and use it in GitHub Desktop.
Save osmyn/e81fc90982f86f49c86309c14fee179d to your computer and use it in GitHub Desktop.
A helper to build dependencies for unit tests that still allow you to substitute your own behaviors in.
public class LocationServiceBuilder
{
//create default behaviors
IHttpService _httpService = Mock.Create<IHttpService>();
IFileService _fileService = Mock.CreateLike<IFileService>(fs => fs.ReadAllLines(Arg.AnyString) == new string[] { "key" });
//pass in your own dependency if needed
public LocationServiceBuilder WithHttpService(IHttpService httpService)
{
_httpService = httpService;
return this;
}
//pass in your own dependency if needed
public LocationServiceBuilder WithFileService(IFileService fileService)
{
_fileService = fileService;
return this;
}
//Build the service
public LocationService Build()
{
return new LocationService(_httpService, _fileService);
}
//setup other test data as needed
public string GetPlaceDetailsTestResults(string placeId)
{
return "example string..";
}
}
[TestMethod]
public void GetPlaceDetails_WithAPlaceId_ReturnsTheGooglePlace()
{
//Arrange
var serviceBuilder = new LocationServiceBuilder();
var placeId = "10302";
var httpService = Mock.Create<IHttpService>();
Mock.Arrange(() => httpService.GetResponse(Arg.AnyString))
.Returns(serviceBuilder.GetPlaceDetailsTestResults(placeId));
var service = serviceBuilder.WithHttpService(httpService).Build();
//Act
var result = service.GetPlaceDetails(placeId).result;
//Assert
Assert.AreEqual(placeId, result.place_id);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment