hibri / HttpMock

A library for creating Http servers on the fly in tests and stubbing responses
MIT License
128 stars 44 forks source link

Add new type handler #99

Closed malves closed 5 years ago

malves commented 5 years ago

Hi,

I am trying to setup a stub to return en empty image when Chrome tries to get /favicon.ico:

server.Stub(x => x.Get("/favicon.ico")) .AsContentType("image/x-icon") .Return(favicon) .OK();

In my browser I have a 404 error, in the HTTP response header I see this key/value:

X-HttpMockError: No handler found to handle request

Is there a way to add an handler to handle .ico extension ?

Thank you

hibri commented 5 years ago

Hi @malves

I tried this in a test and it does work. See the example below. You don't need to add handlers for each type of request. HttpMock matches the URL and the request, that you've setup in the stub. Can you turn on logging to see what the incoming request is? https://github.com/hibri/HttpMock/blob/master/src/HttpMock.Integration.Tests/App.config


[Test]
        public void SUT_should_return_stubbed_response()
        {
            _stubHttp = HttpMockRepository.At(_hostUrl);

            const string expected = "<xml><>response>Hello World</response></xml>";
            _stubHttp.Stub(x => x.Get("/favicon.ico"))
                .Return(expected)
                .OK();

            string result = new WebClient().DownloadString(string.Format("{0}/favicon.ico", _hostUrl));

            Assert.That(result, Is.EqualTo(expected));
        }
malves commented 5 years ago

Hi @hibri

Thank you for your prompt reply and for your help :)

I have investigated the issue and I found what is going wrong. In your test, I suppose that _hostUrl parameter is a string. If I try the same test I also have the good behavior.

But if you send an Uri parameter instead of string, the test is not passing anymore:

        [Test]
        public void SUT_should_return_stubbed_response()
        {
            var address = new Uri("http://localhost:4242");
            IHttpServer stubHttp = HttpMockRepository.At(address);

            const string expected = "<xml><>response>Hello World</response></xml>";
            stubHttp.Stub(x => x.Get("/favicon.ico"))
                .Return(expected)
                .OK();

            string result = new WebClient().DownloadString(string.Format("{0}/favicon.ico", address));

            Assert.That(result, Is.EqualTo(expected));
        }
hibri commented 5 years ago

Found the issue :)

Uri.ToString() adds a trailing slash. This makes the request be "//favicon.ico" to HttpMock. This doesn't match the stub "/favicon.ico"

 string result = new WebClient().DownloadString(string.Format("{0}/favicon.ico", address));

Changing the above to, makes it work.

 string result = new WebClient().DownloadString(string.Format("{0}favicon.ico", address));

Hope this helps. Will look into cleaning up the request later. Happy to accept a PR for it.