Are mocks better than stubs?

前端 未结 6 928
梦毁少年i
梦毁少年i 2021-02-13 09:01

A while ago I read the Mocks Aren\'t Stubs article by Martin Fowler and I must admit I\'m a bit scared of external dependencies with regards to added complexity so I would like

6条回答
  •  遥遥无期
    2021-02-13 09:54

    It just depends on what type of testing you are doing. If you are doing behavior based testing you might want a dynamic mock so you can verify that some interaction with your dependancy occurs. But if you are doing state based testing you might want a stub so you verify values/etc

    For example, in the below test you notice that I stub out the view so I can verify a property value is set (state based testing). I then create a dynamic mock of the service class so I can make sure a specific method gets called during the test (interaction / behavior based testing).

     _
    Public Sub Should_Populate_Products_List_OnViewLoad_When_PostBack_Is_False()
        mMockery = New MockRepository()
        mView = DirectCast(mMockery.Stub(Of IProductView)(), IProductView)
        mProductService = DirectCast(mMockery.DynamicMock(Of IProductService)(), IProductService)
        mPresenter = New ProductPresenter(mView, mProductService)
        Dim ProductList As New List(Of Product)()
        ProductList.Add(New Product())
        Using mMockery.Record()
            SetupResult.For(mView.PageIsPostBack).Return(False)
            Expect.Call(mProductService.GetProducts()).Return(ProductList).Repeat.Once()
        End Using
        Using mMockery.Playback()
            mPresenter.OnViewLoad()
        End Using
        'Verify that we hit the service dependency during the method when postback is false
        Assert.AreEqual(1, mView.Products.Count)
        mMockery.VerifyAll()
    End Sub
    

提交回复
热议问题