首頁  >  文章  >  後端開發  >  如何在表驅動測試中覆寫模擬呼叫期望

如何在表驅動測試中覆寫模擬呼叫期望

WBOY
WBOY轉載
2024-02-10 21:42:09844瀏覽

如何在表驅動測試中覆寫模擬呼叫期望

php小編小新今天為大家介紹一個在表格驅動測試中覆寫模擬呼叫期望的方法。表驅動測試是一種有效的測試技術,能夠透過資料驅動的方式進行測試,提高程式碼的可維護性和可擴展性。在測試中,我們經常需要模擬呼叫期望,以確保被測試的程式碼行為符合預期。本文將詳細介紹如何使用表格驅動測試來實現模擬呼叫期望的覆蓋,幫助開發人員更好地進行單元測試。

問題內容

在進行表格驅動測試時,我使用mockery 產生的一些模擬,並設定一些方法呼叫期望,這些期望取決於每個測試案例的數據集中提供的數據。我面臨的問題是,模擬呼叫始終傳回第一個測試案例中期望的結果集,而不是為執行的測試案例定義的結果集。

func (s *MyTestSuite) TestMySampleTest() {
    testCases := []struct {
        Name     string
        Requests []*service.CreateCredentialRequest
    }{
        {
            Name:     "first case",
            mockedResult: 1,
            expected: 1,
        },
        {
            Name:     "second case",
            mockedResult: 2,
            expected: 2,
        },
    }

    for _, tc := range testCases {
        s.Run(tc.Name, func() {
            s.someMock.On("SomeMethodCall", mock.Anything).Return(tc.mockedResult)

            result := s.SUT.SomeMethodThatCallsTheMockedObe()

            s.Equal(expected, result)
        })
    }
}

當我執行此測試時,第二種情況失敗,因為結果是1 而不是預期的2 ,我可以看到問題是模擬方法返回 1 (為第一個測試案例設定的值)而非 2(為目前測試案例設定的值)。

知道如何解決這個問題嗎?

解決方法

這可能不是最優雅的解決方案,我想知道是否還有其他方法可以做到這一點,但目前,我已經找到了這個解決方案。它包括為表驅動測試運行的每個子測試產生一個新的模擬,因此在每個子測試中,我們使用一個全新的模擬實例,該實例沒有從先前的子測試中設定任何期望。考慮到我使用 testify.suite 來組織和處理我的測試,這樣做就像在每個子測試中手動呼叫 s.setuptest() 方法一樣簡單:

// SetupTest is executed before every test is run, I instantiate the SUT and 
// its dependencies here.
func (s *MyTestSuite) SetupTest() {
    // Instantiate the mock
    s.someMock = mocks.NewSomeMock(s.T())
    // Instantiate the SUT, injecting the mock through the constructor function
    s.SUT = NewSUT(s.someMock)
}

func (s *MyTestSuite) TestMySampleTest() {
    testCases := []struct {
        Name     string
        Requests []*service.CreateCredentialRequest
    }{
        // test cases here 
    }

    for _, tc := range testCases {
        s.Run(tc.Name, func() {
            // Manually calling s.SetupTest() to generate new instances of the mocks in every subtest.
            // If we don't do this, the mock will always return the first expectation set (the one set for the first test case).
            s.SetupTest()

            // Here comes the logic of the text as we had it before
            s.someMock.On("SomeMethodCall", mock.Anything).Return(tc.mockedResult)

            result := s.SUT.SomeMethodThatCallsTheMockedObe()

            s.Equal(expected, result)
        })
    }
}

以上是如何在表驅動測試中覆寫模擬呼叫期望的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除