mock4net icon indicating copy to clipboard operation
mock4net copied to clipboard

Proposal to send a Func when creating Responses

Open iKarthik opened this issue 8 years ago • 3 comments

Wouldn't it be a good idea if we can pass a Func while creating the Responses, this way when the response is being creating, the func will be invoked which then will decide the response For example

server
  .Given(
    Requests.WithUrl("/api").UsingGet()
  )
  .RespondWith(
    Responses
      .WithStatusCode(200)
      .WithResponseFunc((request) => new Response())
  ); 

In the lambda, we can decide what response to send. Thoughts? Kay

iKarthik avatar May 27 '16 00:05 iKarthik

Hello Kay RespondWith() method already takes as a parameter a IProvideResponses object. So you can already implement this interface to buid a dynamic way a response. Do you think we should replace this interface by a delegate in order to be able to use lambdas? Regards

Alex

alexvictoor avatar May 29 '16 19:05 alexvictoor

I want to be able to build the responses with lamdas so that we can do the following

_server.Given(Requests.WithUrl("/foo").UsingPost())
                .RespondWith(Responses.WithStatusCode(200).WithResponseFunc(Func));

Where Func could be

` private Response Func(string request)
        {
            if(request.Contains("SomeValue")) return new Response() {Body = "SomeValue Response"};
            if(request.Contains("ZeroValue")) return new Response() {Body = "ZeroValue Response"};
            if(request.Contains("OneValue")) return new Response() {Body = "OneValue Response"};
            return new Response();;
        }`

Hope that made sense

Thanks Kay

iKarthik avatar May 31 '16 12:05 iKarthik

It totally makes sens What I said in my previous message is that you can already do it, implementing interface IProvideResponses . You could have:

class Handler : IProvideResponses {

  Task<Response> ProvideResponse(Request request) {
      if(request.Url.Contains("SomeValue")) return Task.FromResult(new Response() {Body = "SomeValue Response"});
...
   }
}

_server.Given(Requests.WithUrl("/foo").UsingPost())
                .RespondWith(new Handler())

Still you cannot use any lambda. We could replace interface IProvideResponses by a delegate to make it possible.

alexvictoor avatar Jun 04 '16 14:06 alexvictoor