将Mock对象传递给class

时间:2013-11-19 15:55:23

标签: unit-testing mocking mstest rhino-mocks


在下面的代码块中,我需要在“obizEmail.GetEmailContent”方法中使用类RETTemplateLoader(创建为“obiz”)的对象,因此我为类BizCampaignEmailSend(创建为“obizEmail”)创建了Mock,但我找不到如何链接这两个对象,以便在调用方法“GetEmailContent”时,我希望它返回"<HTML>"(我的硬编码文本)

<TestMethod(), Owner("TestEmail"), TestCategory("Testing")> _
    Public Sub GetEmailContent()
        Using oClass As New SessionClass("UnitTesting", Me.GetType.Name)
            Dim oSvcJPEmailProductsCampaignStruct As New SvcJPEmailProductsCampaignStruct
            'Class obj 1
            Dim obiz = MockRepository.GeneratePartialMock(Of RETTemplateLoader)(New Object() {"", "", "", False})
            obiz.Stub(Function(c) c.LoadEmailTemplateNew(oClass)).Return("<HTML>")
            'Class obj 2
            Dim obizEmail = MockRepository.GeneratePartialMock(Of BizCampaignEmailSend)()
            Assert.AreEqual(obizEmail.GetEmailContent(oClass , oSvcJPEmailProductsCampaignStruct), "<HTML>")
        End Using
    End Sub

这是我需要提供测试覆盖率的方法

Public Overridable Function GetEmailContent(ByVal oClass As SessionClass, ByVal oCampaignStruct As SvcJPEmailProductsCampaignStruct) As String          
    Dim sEmailTemplate As String = String.Empty
    Dim oRETTemplateLoader As New RETTemplateLoader(oCampaignStruct.CampaignContent, "",    oCampaignStruct.AutoResponseDID, True)
    sEmailTemplate = oRETTemplateLoader.LoadEmailTemplateNew(oClass)
    Return sEmailTemplate
End Function

1 个答案:

答案 0 :(得分:0)

我认为你不需要在这里进行任何链接。在这种情况下,您不需要将SUT(系统测试中)称为模拟对象。我没有看到通过调用

设置存根以返回“”的好处
  

oRETTemplateLoader.LoadEmailTemplateNew(oClass)

然后为你的SUT设置一个模拟对象,调用上面的方法并期望它返回你已经模拟过的东西。你的SUT没有太多行为。

我唯一建议它来验证是否调用oRETTemplateLoader.LoadEmailTemplateNew(oClass)。

如下所示。 (注意我不是VB.NET专家,但你应该能够解决任何语法错误。我只是表明我的意图。)

 <TestMethod(), Owner("TestEmail"), TestCategory("Testing")> _
Public Sub GetEmailContent()
    Using oClass As New SessionClass("UnitTesting", Me.GetType.Name)
        Dim oSvcJPEmailProductsCampaignStruct As New SvcJPEmailProductsCampaignStruct
        'Set your expectation
        Dim obiz = MockRepository.GeneratePartialMock(Of RETTemplateLoader)(New Object() {"", "", "", False})
        obiz.Expect(Function(c) c.LoadEmailTemplateNew(oClass)).Return("some string")

        'Call SUT
        Dim sut As New BizCampaignEmailSend
        Dim r = sut.GetEmailContent(oClass , oSvcJPEmailProductsCampaignStruct)

         'Verify
         obiz.VerifyAllExpectations()
    End Using
End Sub