Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Untitesting/Moq method calling webrequest

Tags:

c#

moq

I want to test a class that via a Webrequest sends texts, how can I using Moq mock the GetRequest methode, to test the GetRequest?

public class Sender

public void Send(string Message)
{
...
WebRequest myReq = GetRequest(sParmeter);
}

protected WebRequest GetRequest(string URl)
        {
            return WebRequest.Create(URl);
        }
}
like image 553
DTA Avatar asked Jan 17 '23 10:01

DTA


2 Answers

For something like this, the easy way would be to move your WebRequest instance and its action behind an interfaced intermediary.

Example:

public interface IWebRequestHandler
{
WebRequest GetRequest (string URI);
}

public class WebRequestHandler : IWebRequestHandler
{
public WebRequest GetRequest (string URI)
{
return WebRequest.Create(URl);
}
} 

Your sender class should have an injectable instance of IWebRequestHandler and you can mock it with MOQ, set up expctations, verify it gets called and anything else you might want.

public class Sender
{
public IWebRequestHandler Handler{get;set;}
public void Send(string Message)
{
Handler.GetRequest(new URI(Message));//call the method with right params, just an example
}
}
like image 148
AD.Net Avatar answered Feb 14 '23 02:02

AD.Net


One of the approaches that I was gonna suggest is the same as the response by AD.Net, but if you do not wish to modify your existing structure and still test you could do something like below:

Modify your original class as follows:

public class Sender
{
    public void Send(string Message)
    {
    ...
        WebRequest myReq = GetRequest(sParmeter);
    }

    protected virtual WebRequest GetRequest(string URl)
    {
        return WebRequest.Create(URl);
    }
}

and in your test project extend this class as follows:

public class MockSender: Sender
{
    private WebRequest _response;
    public MockSender(WebRequest response)
    {
    _response=response;       //initialize data to be returned
    }
    protected override WebRequest GetRequest(string URl)
    {
        //return your test;
    }
}

and now in your test create an instance of type MockSender and call the Send method on it.

Moq expects your class to be abstract or you to implement an interface and thus mock the interface which is what AD.Net has described

Hope this helps..

like image 41
Baz1nga Avatar answered Feb 14 '23 01:02

Baz1nga