Reputation: 181
my code goes like this I am trying to mock the htttputility urlencode method which I am using in GetUrlToSurveyMonkeyAuthentication method.
//this is the method which uses urlencode method which is in the same class
public string GetUrlToSurveyMonkeyAuthentication(string redirectUri, string clientId, string apiKey)
{
string urlToOauthSurveyMonkeyAuthentication = SurveyMonkeyBaseUrl + AuthCodeEndUrl + ParameterSeparator + ParameterRedirectUriName + UrlEncodes(redirectUri) + ParameterAdditioner + ParameterClientIdName + UrlEncodes(clientId) + ParameterAdditioner + ParameterResponseTypeName + UrlEncodes(ResponseType) + ParameterAdditioner + ParameterAPIKeyname + UrlEncodes(apiKey);
return urlToOauthSurveyMonkeyAuthentication;
}
// my urlencode method which needs to be mocked it is in the same class SurveyMonkeyAPIService
public virtual string UrlEncodes(string value)
{
return HttpUtility.UrlEncode(value);
}
my test method goes like this
[Test]
public void GetUrlToSurveyMonkeyAuthenticationTest()
{
var mockUrlEncodeMethod = new Moq.Mock<ISurveyMonkeyAPIService>();
mockUrlEncodeMethod.CallBase = true;
mockUrlEncodeMethod.Setup(x => x.UrlEncode(It.IsAny<string>())).Returns(TestData.TestData.SamplehttpUtilityURLEncodeMockString);
string tempURL = mockUrlEncodeMethod.Object.GetUrlToSurveyMonkeyAuthentication(TestData.TestData.SampleRedirectUri, TestData.TestData.SampleClientId, TestData.TestData.SampleApiKey);
Assert.IsNotNullOrEmpty(tempURL);
}
my test fails it always returnsnull value , I have tried removing the virtual keyword , I have an interface which has these two method definitions, I have no parameter constructor.I am using Nunit to test these methods.
Upvotes: 1
Views: 4777
Reputation: 31444
You are mocking an interface:
var mockUrlEncodeMethod = new Moq.Mock<ISurveyMonkeyAPIService>();
You want to mock a class, so that some implementation is available:
var mockUrlEncodeMethod = new Moq.Mock<SurveyMonkeyAPIService>();
Moq will be able to mock virtual methods of said class and call actual implemenation of non-virtual ones.
Upvotes: 6