Moq: Invalid setup on a non-overridable member: x => x.GetByTitle("asdf") - c#

Not sure how I can fix this, trying to do a unit test on the method "GetByTitle"
Here are my definitions:
public class ArticleDAO : GenericNHibernateDAO(IArticle, int>, IArticleDAO
{
public IArticle GetByTitle(string title)
{
IQuery query = Session.CreateQuery("...")
return query.UniqueResult<IArticle>();
}
}
public interface IArticleDAO
{
IArticle GetByTitle(string title);
}
unit test:
[Test]
public void can_load_by_title()
{
_mockDaoFactory.Setup(x => x.GetArticleDao())
.Returns(_mockArticleDao.Object);
_mockArticleDao.Setup(x => x.GetByTitle("some title"))
.Returns(article1.Object);
_articleManager.LoadArticle("some title");
Assert.IsNotNull(_articleManager.Article);
}
Running the test gives me the error:
System.ArgumentException: Invalid setup on a non-overridable member:
x => x.GetByTitle("some title")
Update
My [Setup] looks like:
[Setup]
public void SetUp()
{
_mockDaoFactory = new Mock<IDaoFactory>();
_mockArticleDao = new Mock<ArticleDao>();
_articleManager = new ArticleManager(_mockDaoFactory.Object);
}

In order to control the behavior of a mock object (in Moq, at least), you either need to mock an interface, or make sure that the behavior you're trying to control is marked virtual. In your comment, I understand it so that the instantiating of _mockArticleDao is done something like this:
_mockArticleDao = new Mock<ArticleDAO>();
If you want to keep it as so, you need to mark the GetArticle method virtual:
public class ArticleDAO : GenericNHibernateDAO(IArticle, int>, IArticleDAO
{
public virtual IArticle GetByTitle(string title)
{
// ...
}
}
Otherwise (and this is what I recommend), mock the interface instead.
_mockArticleDao = new Mock<IArticleDAO>();

Create an inherited mockable class
I had the same issue trying to mock a class I have no control over, from a framework. In my specific case I had to mock an HttpResponseMessage setting up the status code to return Ok, but how to do it if that property is not virtual?
This code does not work because StatusCode is not virtual:
var httpResponseMessage = new Mock<HttpResponseMessage>();
httpResponseMessage.SetupGet(x => x.StatusCode).Returns(HttpStatusCode.OK);
Answer:
Create a new class in your test project, inheriting from the class you want to mock
Redefine the same set of constructors calling the base constructors
Redefine the non virtual properties or methods you want to setup as virtual (use the new keyword to explicitly hide the original members)
From the redefined virtual properties or methods, call the non virtual base property or method.
Done. Now you can mock a derived object that can be used anywhere the original one is used, because it inherits from it. Here is the code for my MockableHttpResponseMessage class:
public class MockableHttpResponseMessage: HttpResponseMessage
{
public MockableHttpResponseMessage() : base() {}
public MockableHttpResponseMessage(HttpStatusCode code) : base (code) { }
public new virtual HttpStatusCode StatusCode {
get { return base.StatusCode; }
set { base.StatusCode = value; }
}
}
Now, this code works:
var httpResponseMessage = new Mock<MockableHttpResponseMessage>();
httpResponseMessage.SetupGet(x => x.StatusCode).Returns(HttpStatusCode.OK);

Here's how I Mock HttpMessageHandler:
private HttpRequestMessage requestMessage = new HttpRequestMessage();
Mock<HttpMessageHandler> handlerMock =
GetHttpMessageHandlerMock(HttpStatusCode.OK);
MyRestService myRestService = new MyRestService();
myRestService.client = new HttpClient(handlerMock.Object);
var response = myRestService.Get("");
//At this point, the Mock of HttpRequestMessage is called and the Callback fills my class variable requestMessage. I can now look inside the requestMessage.
var headers = requestMessage?.Headers.ToString();
var queryBegin = requestMessage.RequestUri.OriginalString.IndexOf('?');
var queryString = requestMessage.RequestUri.OriginalString.Substring(queryBegin + 1);
Assert.That(headers.Contains("x-api-key: fakeApiKey"));
//Helper methods below
private Mock<HttpMessageHandler> GetHttpMessageHandlerMock(HttpStatusCode statusCode)
{
var handlerMock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
handlerMock
.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>()
, ItExpr.IsAny<CancellationToken>()
)
.Returns(Task.FromResult(GetFakeResponse(statusCode)))
.Callback<HttpRequestMessage, CancellationToken>((p, q) => requestMessage = p)
.Verifiable();
return handlerMock;
}
private HttpResponseMessage GetFakeResponse(HttpStatusCode statusCode)
{
var s = "{\"data\":{\"status\":\"SUCCESS\",\"errorCode\":\"\",\"errorMessage\":\"9\"}}";
HttpResponseMessage response = new HttpResponseMessage()
{
StatusCode = statusCode,
Content = new StringContent(s),
ReasonPhrase = "OK",
RequestMessage = new HttpRequestMessage()
};
return response;
}
I use this for almost all my REST tests, because I can pass in status, content, etc. So, I can test different return values.

Related

Inject Dependency without using Constructor injection using Ninject - Unit Tests

I am creating Unit Tests for existing .NET Framework 4.5 API project. The existing project has parameterless constructor by design and dependency injection was implemented as per the class below using Ninject.
I would like to Mock the interface and create an instance of the class for testing as shown below but the constructor is parameterless. I can't figure out how to inject my Mock member.Object. The main goal is I don't want to change the design of existing classes unless there is no other way.
public class MemberController : ApiController
{
StandardKernel DependencyKernel;
private IMember member;
public MemberController()
{
DependencyKernel = new StandardKernel();
DependencyKernel.Load(Assembly.GetExecutingAssembly());
member = DependencyKernel.Get<IMember>();
}
[HttpPost]
public HttpResponseMessage AddMember(MemberRequest model)
{
try
{
int memberRecords;
member.SaveMember(model, out memberRecords);
if (memberRecords > 0)
return new HttpResponseMessage { StatusCode = HttpStatusCode.Conflict, Content = new StringContent("Member with same reference exists") };
else
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent("Member added successfully") };
}
catch (Exception ex)
{
return new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(ex.Message) };
}
}
}
//Test Class
public class MemberControllerTests
{
StandardKernel DependencyKernel;
private MemberController memberController;
Mock<IMember> member = new Mock<IMember>();
public MemberControllerTests()
{
DependencyKernel = new StandardKernel();
DependencyKernel.Load(Assembly.GetExecutingAssembly());
}
[SetUp]
public void Setup()
{
}
[Test]
public void should_AddMember()
{
//Arrange
MemberRequest member = new MemberRequest{ };
int memberRecords;
member.Setup(x => x.SaveMember(member, out memberRecords));
memberController = new MemberController(member.Object); //This will obviously not work, the MemberController has parameterless constructor
//Act
var result = MemberController.AddMember(member);
//Assert
Assert.AreEqual(result.StatusCode, HttpStatusCode.OK);
}
}
This post has the answer to the question. If IMember member property is made public in MemberController, I can new up the MemberController class and set the value of its member property to the MOCK.

Mock a method from another class called from a mocked method

We are creating unit tests for an application and ran into a problem creating certain tests.
We are unit testing the following Handle() method of the class ActivateCommandHandler:
public class ActivateCommand : IRequest<HttpResponseMessage>
{
public string Controller { get; set; }
public ActivateCommand(string controllername)
{
this.Controller = controllername;
}
}
public class ActivateCommandHandler : CommandHandler<ActivateCommand, HttpResponseMessage>
{
protected readonly ICommandsGateway _commandsGateway;
protected readonly EndpointSettings _endpoints;
protected readonly IUserProfile _userprofile;
public ActivateCommandHandler(IMediator mediator, ICommandsGateway commandsGateway, IOptions<EndpointSettings> endpoints, IValidationContext validationContext, IUserProfile currentUser) : base(mediator, validationContext, currentUser)
{
_commandsGateway = commandsGateway;
_endpoints = endpoints.Value;
_userprofile = currentUser;
}
public override async Task<HttpResponseMessage> Handle(ActivateCommand command, CancellationToken cancellationToken)
{
if (_endpoints.EndpointExists(command.Controller))
{
// Check whether the second server controller is deactivated
string peercontroller = _endpoints.GetPeerController(command.Controller);
if (!string.IsNullOrEmpty(peercontroller))
{
BaseRedundancySwitchStatus controllerStatus = await _commandsGateway.GetRedundancySwitchStatus(_endpoints.GetEndpointAddress(peercontroller));
if ((controllerStatus.CurrentState == "Activated") || (controllerStatus.CurrentState == "ActivatedWithWarning") || (controllerStatus.CurrentState == "Activating"))
{
var resp = new HttpResponseMessage(HttpStatusCode.Conflict)
{
Content = new StringContent($"{peercontroller},{controllerStatus.CurrentState}")
};
return resp;
}
}
var result = await _commandsGateway.PostActivateCommand(_endpoints.GetEndpointAddress(command.Controller));
return result;
}
else
{
throw new InvalidControllerNameException($"ERROR: The controller {command.Controller} does not exist as an endpoint on this Control Center!");
}
}
}
For this the following were mocked: _endpoints, command and _commandsGateway (interface). This works great for unit testing the parameter validation. But we now want to test the behaviour when the peercontroller status is set to a specific value.
To do this we are trying to mock out the function _commandsGateway.GetRedundancySwitchStatus(). The following is the actual test implementation. We mock the _commandsGateway.GetRedundancySwitchStatus() function to return the expected BaseRedundancySwitchStatus with CurrentState set to "Activated". After that we call the handler of the actual function to be tested and check whether we get the expected error.
[Fact]
public async void ShouldHaveErrors_PeerControllerStateActivated()
{
var command = new ActivateCommand("Server Controller Slave1");
BaseRedundancySwitchStatus result = new BaseRedundancySwitchStatus()
{
CurrentState = "Activated"
};
_commandsGateway
.Setup(s => s.GetRedundancySwitchStatus("Server Controller Slave1"))
.ReturnsAsync(result);
HttpResponseMessage res = await _handler.Handle(command, CancellationToken.None);
Assert.True(res.StatusCode == System.Net.HttpStatusCode.Conflict);
}
Debugging the code, when I step through the code in the Handle() method where _commandsGateway.GetRedundancySwitchStatus is called, I can see that _endpoints.GetEndpointAddress(command.Controller) (which is the parameter) is called and the correct value is returned. After this the debugger steps to the next line without any indication of having executed the mock GetRedundancySwitchStatus() function. Inspecting the controllerStatus variable the value is null. I would expect the value to be the BaseRedundancySwitchStatus object which is supposed to be returned by the mocked GetRedundancySwitchStatus() function.
Where are we going wrong?

C# mocking generic repository using Moq

I have implemented generic repository in my project. Now I am writing test cases for my consumer. I am trying to mock database function through Moq but I am getting values from database rather than the one I faked through Moq. Below I am sharing my implementation. Hoping someone will help me in pointing out the mistake I made.
My interface:
public interface IEventsRepository<T> : IRepository<T> {
T GetEventsByEventId(int eventId); }
My class:
public class EventsTableRepository : EFDBRepository<EventsModel>, IEventsRepository<EventsModel> {
public EventsModel GetEventsByEventId(int eventId)
{
return _dbSet.Where(x => x.EventID == eventId).FirstOrDefault();
}
}
My Consumer:
public static Response<string> EventsAccept(EventsAlertsRequest logMsgId)
{
IEventsRepository<EventsModel> eventsRepo = (IEventsRepository<EventsModel>)RepositoryLocator.GetRepositoryObject(STMEnums.RepositoryName.EventsTableRepository.ToString());
EventsModel eventmodel = new EventsModel();
eventmodel = eventsRepo.GetEventsByEventId(eachlogMsgId);
return EventStatusChangeResponse;
}
Test Method:
public void EventsAcceptSuccessTest()
{
EventsModel eventmodel = new EventsModel();
eventmodel.Message = "TEST";
Mock<IEventsRepository<EventsModel>> obj = new Mock<IEventsRepository<EventsModel>>();
obj.Setup(m => m.GetEventsByEventId(Moq.It.IsAny<int>())).Returns(eventmodel);
EventStatusChangeResponse = Diagnostics_.EventsAccept(logMsgId);
Assert.AreEqual(eventmodel.Status, EventStatus.ACCEPTED);
}
No where in the provided example is the mock being injected into the subject under test. Also it looks like the subject method under test is using static Service Locator anti-pattern to get the desired model. Making an assumption here as the rest of the class is not shown in relation to that variable.
The locator would need to have been an injected abstraction to allow an opportunity to mock its expected behavior
public class Consumer {
private IRepositoryLocator RepositoryLocator;
public Consumer(IRepositoryLocator RepositoryLocator) {
this.RepositoryLocator = RepositoryLocator;
}
public Response<string> EventsAccept(EventsAlertsRequest logMsgId) {
IEventsRepository<EventsModel> eventsRepo = (IEventsRepository<EventsModel>)RepositoryLocator.GetRepositoryObject(STMEnums.RepositoryName.EventsTableRepository.ToString());
EventsModel eventmodel = new EventsModel();
eventmodel = eventsRepo.GetEventsByEventId(eachlogMsgId);
return EventStatusChangeResponse;
}
}
This would then mean that the locator would also have to be mocked properly for the test to be exercised to completion.
public void EventsAcceptSuccessTest() {
//Arrange
var eventmodel = new EventsModel() {
Message = "TEST"
};
var repositoryMock = new Mock<IEventsRepository<EventsModel>>();
repositoryMock
.Setup(_ => _.GetEventsByEventId(It.IsAny<int>()))
.Callback((int id) => {
eventmodel.EventID = id;
eventmodel.Status = EventStatus.ACCEPTED;
})
.Returns(eventmodel);
var locatorMock = new Mock<IRepositoryLocator>();
locatorMock.Setup(_ => _.GetRepositoryObject(It.IsAny<string>())).Returns(repositoryMock.Object);
var subject = new Consumer(locatorMock.Object);
//Act
var response = subject.EventsAccept(logMsgId);
//Assert
Assert.AreEqual(eventmodel.Status, EventStatus.ACCEPTED);
}

Mock Request Object for Web API unit test

I want to unit test my web API controller. I have a problem with one of my action method (POST) which is need value from Request object, to get the controller name.
I'm using NSubtitute, FluentAssertions to support my unit test
This is my controller code looks like:
public class ReceiptsController : BaseController
{
public ReceiptsController(IRepository<ReceiptIndex> repository) : base(repository) { }
..... Other action code
[HttpPost]
public IHttpActionResult PostReceipt(string accountId, [FromBody] ReceiptContent data, string userId = "", string deviceId = "", string deviceName = "")
{
if (data.date <= 0)
{
return BadRequest("ErrCode: Save Receipt, no date provided");
}
var commonField = new CommonField()
{
AccountId = accountId,
DeviceId = deviceId,
DeviceName = deviceName,
UserId = userId
};
return PostItem(repository, commonField, data);
}
}
And the base class for my controller :
public abstract class BaseController : ApiController
{
protected IRepository<IDatabaseTable> repository;
protected BaseController(IRepository<IDatabaseTable> repository)
{
this.repository = repository;
}
protected virtual IHttpActionResult PostItem(IRepository<IDatabaseTable> repo, CommonField field, IContent data)
{
// How can I mock Request object on this code part ???
string controllerName = Request.GetRouteData().Values["controller"].ToString();
var result = repository.CreateItem(field, data);
if (result.Error)
{
return InternalServerError();
}
string createdResource = string.Format("{0}api/accounts/{1}/{2}/{3}", GlobalConfiguration.Configuration.VirtualPathRoot, field.AccountId,controllerName, result.Data);
var createdData = repository.GetItem(field.AccountId, result.Data);
if (createdData.Error)
{
return InternalServerError();
}
return Created(createdResource, createdData.Data);
}
}
And this is my unit test for success create scenario:
[Test]
public void PostClient_CreateClient_ReturnNewClient()
{
// Arrange
var contentData = TestData.Client.ClientContentData("TestBillingName_1");
var newClientId = 456;
var expectedData = TestData.Client.ClientData(newClientId);
clientsRepository.CreateItem(Arg.Any<CommonField>(), contentData)
.Returns(new Result<long>(newClientId)
{
Message = ""
});
clientsRepository.GetItem(accountId, newClientId)
.Returns(new Result<ContactIndex>(expectedData));
// Act
var result = _baseController.PostClient(accountId, contentData, userId);
// Asserts
result.Should().BeOfType<CreatedNegotiatedContentResult<ContactIndex>>()
.Which.Content.ShouldBeEquivalentTo(expectedData);
}
I don't know if there is any way to extract Request object from the controller, or maybe is there any way to mock it on the unit test?
Right now this code Request.GetRouteData() return null on the unit test.
you can make an interface for getting Request Data(pass Request object to it). Implement that interface and use as dependency in your Controller. Then you can easily mock this interface implementation in your unit tests.
I've finally find a way to solve this. So basically I have to create some configuration related stuff to make my unit test works.
I create a helpers class for this
public static class Helpers
{
public static void SetupControllerForTests(ApiController controller)
{
var config = new HttpConfiguration();
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/products");
var route = config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}");
var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "products" } });
controller.ControllerContext = new HttpControllerContext(config, routeData, request);
controller.Request = request;
controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
}
}
Then passing my test controller on my test setup
[SetUp]
public void SetUp()
{
clientsRepository = Substitute.For<IRepository<ContactIndex>>();
_baseController = new ClientsController(clientsRepository);
Helpers.SetupControllerForTests(_baseController);
}
I don't know if this is a best way to do it, but I prefer this way instead of create a new interface and inject it to my controller.

How can I use FakeItEasy with HttpClient, in a unit test?

I'm trying to figure out how to use FakeItEasy with the HttpClient, given the following code:
public Foo(string key, HttpClient httpClient = null)
{ .. }
public void DoGet()
{
....
if (_httpClient == null)
{
_httpClient = new HttpClient();
}
var response = _httpClient.GetAsync("user/1);
}
public void DoPost(foo Foo)
{
if (_httpClient == null)
{
_httpClient = new HttpClient();
}
var formData = new Dictionary<string, string>
{
{"Name", "Joe smith"},
{"Age", "40"}
};
var response = _httpClient.PostAsync("user",
new FormUrlEncodedContent(formData));
}
So i'm not sure how to use FakeItEasy, to fake out the HttpClient's GetAsync and PostAsync methods.
production code will not pass in the HttpClient, but the unit test will pass in the fake instance, made by FakeItEasy.
eg.
[Fact]
public void GivenBlah_DoGet_DoesSomething()
{
// Arrange.
var httpClient A.Fake<HttpClient>(); // <-- need help here.
var foo = new Foo("aa", httpClient);
// Act.
foo.DoGet();
// Assert....
}
UPDATE:
I grok that FiE (and most mocking packages) works on interfaces or virtual methods. So for this question, lets just prentend that the GetAsync and PostAsync methods are virtual ... please :)
Here's my (more or less) general purpose FakeHttpMessageHandler.
public class FakeHttpMessageHandler : HttpMessageHandler
{
private HttpResponseMessage _response;
public static HttpMessageHandler GetHttpMessageHandler( string content, HttpStatusCode httpStatusCode )
{
var memStream = new MemoryStream();
var sw = new StreamWriter( memStream );
sw.Write( content );
sw.Flush();
memStream.Position = 0;
var httpContent = new StreamContent( memStream );
var response = new HttpResponseMessage()
{
StatusCode = httpStatusCode,
Content = httpContent
};
var messageHandler = new FakeHttpMessageHandler( response );
return messageHandler;
}
public FakeHttpMessageHandler( HttpResponseMessage response )
{
_response = response;
}
protected override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken )
{
var tcs = new TaskCompletionSource<HttpResponseMessage>();
tcs.SetResult( _response );
return tcs.Task;
}
}
Here is an example of it being used from one of my tests that expects some JSON as a return value.
const string json = "{\"success\": true}";
var messageHandler = FakeHttpMessageHandler.GetHttpMessageHandler(
json, HttpStatusCode.BadRequest );
var httpClient = new HttpClient( messageHandler );
You would now inject httpClient into your class under test (using whatever injection mechanism you prefer) and when GetAsync is called your messageHandler will spit back the result you told it to.
You could also create an AbstractHandler on which you can intercept a public abstract method. For instance:
public abstract class AbstractHandler : HttpClientHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return Task.FromResult(SendAsync(request.Method, request.RequestUri.AbsoluteUri));
}
public abstract HttpResponseMessage SendAsync(HttpMethod method, string url);
}
Then you can intercept calls to the AbstractHandler.SendAsync(HttpMethod method, string url) like:
// Arrange
var httpMessageHandler = A.Fake<AbstractHandler>(options => options.CallsBaseMethods());
A.CallTo(() => httpMessageHandler.SendAsync(A<HttpMethod>._, A<string>._)).Returns(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("Result")});
var httpClient = new HttpClient(httpMessageHandler);
// Act
var result = await httpClient.GetAsync("https://google.com/");
// Assert
Assert.Equal("Result", await result.Content.ReadAsStringAsync());
A.CallTo(() => httpMessageHandler.SendAsync(A<HttpMethod>._, "https://google.com/")).MustHaveHappenedOnceExactly();
More information can be found on this blog: https://www.meziantou.net/mocking-an-httpclient-using-an-httpclienthandler.htm
I did something like this when I needed to interact with the Gravatar service. I tried to use fakes/mocks but found it was impossible with HttpClient. Instead, I came up with a custom HttpMessageHandler class that lets me pre-load the expected response, along these lines:
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Tigra.Gravatar.LogFetcher.Specifications
{
/// <summary>
/// Class LoggingHttpMessageHandler.
/// Provides a fake HttpMessageHandler that can be injected into HttpClient.
/// The class requires a ready-made response message to be passed in the constructor,
/// which is simply returned when requested. Additionally, the web request is logged in the
/// RequestMessage property for later examination.
/// </summary>
public class LoggingHttpMessageHandler : DelegatingHandler
{
internal HttpResponseMessage ResponseMessage { get; private set; }
internal HttpRequestMessage RequestMessage { get; private set; }
public LoggingHttpMessageHandler(HttpResponseMessage responseMessage)
{
ResponseMessage = responseMessage;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
RequestMessage = request;
return Task.FromResult(ResponseMessage);
}
}
}
Then my test context setup goes something like this:
public class with_fake_gravatar_web_service
{
Establish context = () =>
{
MessageHandler = new LoggingHttpMessageHandler(new HttpResponseMessage(HttpStatusCode.OK));
GravatarClient = new HttpClient(MessageHandler);
Filesystem = A.Fake<FakeFileSystemWrapper>();
Fetcher = new GravatarFetcher(Committers, GravatarClient, Filesystem);
};
protected static LoggingHttpMessageHandler MessageHandler;
protected static HttpClient GravatarClient;
protected static FakeFileSystemWrapper Filesystem;
}
Then, here's an example of a test (specification) that uses it:
[Subject(typeof(GravatarFetcher), "Web service")]
public class when_fetching_imagaes_from_gravatar_web_service : with_fake_gravatar_web_service
{
Because of = () =>
{
var result = Fetcher.FetchGravatars(#"c:\"); // This makes the web request
Task.WaitAll(result.ToArray());
//"http://www.gravatar.com/avatar/".md5_hex(lc $email)."?d=404&size=".$size;
UriPath = MessageHandler.RequestMessage.RequestUri.GetComponents(UriComponents.Path, UriFormat.Unescaped);
};
It should_make_request_from_gravatar_dot_com =
() => MessageHandler.RequestMessage.RequestUri.Host.ShouldEqual("www.gravatar.com");
It should_make_a_get_request = () => MessageHandler.RequestMessage.Method.ShouldEqual(HttpMethod.Get);
// see https://en.gravatar.com/site/check/tim#tigranetworks.co.uk
It should_request_the_gravatar_hash_for_tim_long =
() => UriPath.ShouldStartWith("avatar/df0478426c0e47cc5e557d5391e5255d");
static string UriPath;
}
You can see the full source at http://stash.teamserver.tigranetworks.co.uk/users/timlong/repos/tigra.gravatar.logfetcher/browse
FakeItEasy, like most mocking libraries, does not create proxies for non-abstract components. In the case of HttpClient, the GetAsync and PostAsync methods are neither virtual nor abstract, so you can't create stub implementations of them directly. See https://github.com/FakeItEasy/FakeItEasy/wiki/What-can-be-faked.
In this case, you need a different abstraction as a dependency - one which HttpClient can fulfill, but so could other implementations, including mocks/stubs.
This isn't answering your question directly, but I wrote a library a while back that provides an API for stubbing out requests/responses. It's pretty flexible, and supports ordered/unordered matching as well as a customisable fallback system for unmatched requests.
It's available on GitHub here: https://github.com/richardszalay/mockhttp

Categories