use*_*848 1 c# nunit unit-testing moq
我的代码是这样的 我试图模拟我在 GetUrlToSurveyMonkeyAuthentication 方法中使用的 htttputility urlencode 方法。
//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);
}
Run Code Online (Sandbox Code Playgroud)
我的测试方法是这样的
[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);
}
Run Code Online (Sandbox Code Playgroud)
我的测试失败了它总是返回空值,我尝试删除 virtual 关键字,我有一个包含这两个方法定义的接口,我没有参数构造函数。我正在使用 Nunit 来测试这些方法。
你在嘲笑一个界面:
var mockUrlEncodeMethod = new Moq.Mock<ISurveyMonkeyAPIService>();
Run Code Online (Sandbox Code Playgroud)
你想模拟一个class,以便一些实现可用:
var mockUrlEncodeMethod = new Moq.Mock<SurveyMonkeyAPIService>();
Run Code Online (Sandbox Code Playgroud)
Moq 将能够模拟所述类的虚拟方法并调用非虚拟方法的实际实现。