Chad
Chad

Reputation: 177

Using Moq to create a mock the type with constructor

I'm just getting started on unit testing on a simple method and I'm stuck on the below line (specifically the web service object):

public string GetToken()
{
    WebService ws = new WebService("https://example.com/", HttpContext.Current.Server.MapPath("~/Config/agent.txt"));

    Token token = ws.GetToken(name, values, stuff);
}

At first I tried to use an interface to mock the HttpContext call, but I had trouble going that route, so I'm wondering if I can just Mock the web service? Something like below, but then I don't know how to actually 'inject' this Mock object into the getToken method/class.

var webServiceMock = new Mock<WebService>("http://test.example.com", "/test/file/path");
//maybe something along this syntax?
webServiceMock.Setup(it => it.CreateGetMethod(uri)).Returns(mockWebService.Object);

I am working through your interface solution and I can't figure out how to setup the implementation for the token without a WebService. It calls GetIssuedTokenType but that doesn't exist in WebServiceImpl

    public class TokenImpl : IToken
    {
        public Token getToken(WebService ws)
        {
             Token token = ws.GetIssuedTokenType(
                  "http://example.com",
                  "[email protected]", values,
                  WebService.TokenType.EX20);

        return samlToken;
        }
     }

    public class WebServiceImpl : IWebService
    {

        public WebService getWebService()
        {
            WebService ws = new WebService("https://example.com", HttpContext.Current.Server.MapPath("~/Config/agent.txt"));
        return ws;
    }
}

A larger snippet of the class for reference:

WebService ws = new WebService("https://example.com", HttpContext.Current.Server.MapPath("~/Config/agent.txt"));
ws.BasicAuthUsername = "username";
ws.BasicAuthPassword = "pass1234";

SecurityToken token = ws.GetIssuedTokenType(audience, nameId, values, type);

Upvotes: 1

Views: 2084

Answers (1)

abatishchev
abatishchev

Reputation: 100368

interface ITokenProvider
{
    string GetToken();
}

public class WebTokenProvider
{
    public string GetToken
    {
        // your actual implementation
    }
}

Mock in tests:

var mock = new Mock<ITokenProvider>();
mock.Setup(m => m.GetToken()).Returns("test-token-1");

Upvotes: 1

Related Questions