0

I have a requirement of export data as xml through HTTP POST request. It is done by as in below code now problem is I want to create unit test with by mock http request. Can some body help me out on unit test of this?

private string WriteBytesToHttp(ExportConfiguration exportConfiguration, byte[] bytes)
    {

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(exportConfiguration.Endpoint.Address);
        Encoding encoding = exportConfiguration.Format.EncodingCodePage.ToEncoding();

        var contentType = string.IsNullOrEmpty(exportConfiguration.Format.ContentType)
            ? "text/plain"
            : exportConfiguration.Format.ContentType;

        request.ContentType = contentType;
        //request.ContentType = string.Format("{0}; charset={1}", contentType, encoding.HeaderName);
        request.ContentLength = bytes.Length;
        request.Method = "POST";

        if (!(string.IsNullOrEmpty(exportConfiguration.Endpoint.Username) ||
            string.IsNullOrEmpty(exportConfiguration.Endpoint.Password)))
        {
            var creditionStr = string.Format("{0}:{1}", exportConfiguration.Endpoint.Username,
                exportConfiguration.Endpoint.Password);

            request.Headers.Add("Authorization",
                "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(creditionStr)));
        }

        Stream newStream = request.GetRequestStream();
        newStream.Write(bytes, 0, bytes.Length);
        newStream.Close();

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream responseStream = response.GetResponseStream();

        var streamReader = string.IsNullOrEmpty(response.CharacterSet)
            ? new StreamReader(responseStream)
            : new StreamReader(responseStream, Encoding.GetEncoding(response.CharacterSet));

        string responseStr = streamReader.ReadToEnd();
        return String.IsNullOrEmpty(responseStr) ? response.StatusCode.ToString() : responseStr;

    }
Amal Shalika
  • 1,077
  • 1
  • 13
  • 22
  • 3
    What is *exactly* your problem? Any errors? –  Dec 16 '16 at 08:19
  • Need to create unittest for this method by mocking HTTP service call – Amal Shalika Dec 16 '16 at 08:23
  • 1
    i think an answer on your question is here http://stackoverflow.com/questions/9789944/how-can-i-test-a-custom-delegatinghandler-in-the-asp-net-mvc-4-web-api – Viacheslav Yankov Dec 16 '16 at 08:27
  • 2
    @AmalShalika that's not a question or a problem description. Apart from the overly complicated code (why not just use HttpClient?) or the obvious prolems like using `text/plain` instead of `text/xml`, have you tried using an y mocking framework? Or *abstracting* the request behind an interface? – Panagiotis Kanavos Dec 16 '16 at 08:28
  • You mention XML but your code has no reference to serializers or XML. Instead of using credentials you hand-code authorization headers. Instead of mocking the HttpWebRequest object, I'd be more concerned with the code itself – Panagiotis Kanavos Dec 16 '16 at 08:32
  • You should use dependency injection. See this answer for details: http://stackoverflow.com/a/9095754/4924596 – RusArt Dec 16 '16 at 08:35
  • What edition of Visual Studio do you use? – zaitsman Dec 27 '16 at 12:30
  • Visual Studio 2015 – Amal Shalika Dec 29 '16 at 09:00

1 Answers1

0

I used MockHttpServer Service to Mock HttpWebRequest request and response. Hence I would be able to unit test my code without creating extract factory for creating HttpWebReqeust. Below is unit test code using MockHttpService.

MockHttpService.

Additional References

    [Test]
    public void Http_Transport_ExportPG_Order()
    {
        var port = GetFreeTcpPort();
        var url = string.Format("http://localhost:{0}/api/ifs/import", port);
        ....................

        using (new MockServer(port, "api/ifs/import", (req, rsp, prm) => "Result Body"))
        {
            Wait.For<ExportDispatched>(() =>
                 Bus.Raise(new PutawayPlacedConfirmed(1, 2, 3)), null);
        }
    }
Community
  • 1
  • 1
Amal Shalika
  • 1,077
  • 1
  • 13
  • 22