Skip to main content
 首页 » 编程设计

c#之在同一个类中模拟一个方法

2024年02月13日12davidwang456

这是我为调查猴子 api oauth token 实现的 webRequest Post 方法。我正在为以下代码编写单元测试。

public string GetSurveyMonkeyToken(string apiKey, string clientSecret, string tempAuthCode, string redirectUri, string clientId) 
{ 
    if (!VerifyRedirectedTempCode(tempAuthCode))//this method is in the same class which checks the temp code valid(true) or not(false) 
    { 
        return null; 
    } 
    else 
    { 
        WebRequestForTokenOfSurveyMonkey = GetWebRequestForHttpPostOfSurveyMonkeyToken(apiKey, clientSecret, tempAuthCode, redirectUri, clientId); 
        using (HttpWebResponse responseHttpPostForToken = GetResponse(WebRequestForTokenOfSurveyMonkey))//Getresponse method is in the same class which returns this (HttpWebResponse)webRequestObject.GetResponse() 
        { 
            string tokenJson = new StreamReader(responseHttpPostForToken.GetResponseStream()).ReadToEnd(); 
            AccessToken accesstokenObj = JsonConvert.DeserializeObject<AccessToken>(tokenJson); 
            string accessTokenSurvey = accesstokenObj.access_token.ToString(); 
            return (accesstokenObj.access_token.ToString()); 
        } 
    } 
} 

现在上面的代码工作正常,但我在为这个方法编写单元测试时遇到问题。下面是我对它们的单元测试,一个测试我模拟我的方法返回 false 工作正常,它返回 null。

[Test] 
public void GetSurveyMonkeyTokenTestWithValidTempCode() 
{ 
    var mockedSurveyMonkeyToken = new Moq.Mock<SurveyMonkeyAPIService>(); 
    mockedSurveyMonkeyToken.CallBase = true; 
    mockedSurveyMonkeyToken.Setup(a => a.VerifyRedirectedTempCode(It.IsAny<string>())).Returns(true); 
    var mockRequest = mockedSurveyMonkeyToken.Object.GetWebRequestForHttpPostOfSurveyMonkeyToken(TestData.TestData.SampleApiKey, TestData.TestData.SampleClientSecret, TestData.TestData.SampleTempAuthCode, TestData.TestData.SampleRedirectUri, TestData.TestData.SampleClientId); 
    mockedSurveyMonkeyToken.VerifyAll(); 
} 

这个测试方法的错误是 Moq.MockVerificationException :以下设置不匹配: SurveyMonkeyAPIService a => a.VerifyRedirectedTempCode(It.IsAny())

我的测试有什么问题。我是否正确编写了测试方法。我是第一次编写 httpwebrequest 测试方法。

请您参考如下方法:

我认为您可能错误地应用了 Mocking 的概念。

Mocking 的目的应该是用来模拟被测类的依赖性。

不幸的是,您似乎在模拟正在测试的类的方法。这是您刚开始时很容易犯的错误。然而,这样做违背了单元测试的全部目的,因为您的目标应该是独立测试类的功能。如果您模拟该类的方法,您将有效地替换您试图测试的实现。

在查看单元测试时,您会注意到整个测试围绕模拟 var mockedSurveyMonkeyToken = new Moq.Mock<SurveyMonkeyAPIService>(); 展开。 .

您要做的是确定您的类的依赖项是什么,然后模拟它们,以便您可以在测试类的公共(public)方法时控制它们的作用。

如果SurveyMonkeyAPIService是依赖项,那么您可以将该模拟传递给被测类。 (例如 var cut = new MyClassUnderTest(surveyMonkeyAPIServiceMock) 。

但是,如果 SurveyMonkeyAPIService是我怀疑的被测类,那么您将需要在测试中创建此类的实例并传入任何依赖项的模拟。我认为您的依赖项是 HttpWebResponse webRequestObject .

您的测试将包含以下内容:

var sm = new SurveyMonkeyAPIService(webRequestObjectMock); //create the class under test. Arrange 
sm.GetSurveyMonkeyToken(...); //exercise the class under test. Act 
webRequestObjectMock.Verify(...); //verify that the mock was exercised as expected. Assert 

注意:Arrange、Act、Assert是Triple A单元测试的三个步骤...

参见 this question有关如何模拟 HttpWebResponse 依赖项的示例。