测试 mock 时,还需要写 assert 吗?

xiaoronglv · February 17, 2014 · Last by ruohanc replied at February 18, 2014 · 2978 hits

记得以前学习 CodeSchool 的教程时,Greg 说:

# Stub
For replacing a method with code that returns a specified result.

# Mock
A stub with an assertion that the method gets called.

mock 时,还需要写 assert 吗?

既然 Mock 的作用是「检查某种方法有没有被调用」,我是不是可以不用写 assert 了?

def test_eating
  @user.expects(:wash_hand).times(1)
  @user.wash_hand
  # assert .....还要写吗?
end
  1. What's the difference between a mock & stub?

  2. 对 stub 和 mock 的理解

也看了一些资料,但是还是晕晕乎乎。各位兄台可否说一下自己的使用场景,以便我们这些菜鸟理解。

多谢。

我认为是这样的: 比如当你的 wash_hand 方法执行的内容需要另一个单独的测试,那么只要 mock 这个方法,确保它有被调用到就好了. 而我对 stub 的理解是:忽略 .

你这一句既不是 stub, 也不是 mock, 而是直接 assertion 了。

我熟悉 Rspec, 不太熟悉 simple test 和 mocha 的写法,但大致差不多。

代码

def take_dinner
  wash_hand
  sit_down
  eat
end

测试
def hand_washed_before_eating
  @user.expects(:wash_hand).times(1)
  @user.take_dinner
end

这样就可以了,这个测试确保 take_dinner 被调用时 wash_hand 也被调用。Rspec 和 mocha 里面这种带间谍的 expectation 一般写在前面而不是后面。

本意来说 mock 一般是对于 object, mock an object。但实际使用是 stub 既可以用在 object,也可以用在 method。不用揪理论,掌握 API 就行了。

我用 mock 经常是因为有一个外部调用。如果知道会被调用几次就用 mock, 如果调用次数是随机的就 stub

You need to Sign in before reply, if you don't have an account, please Sign up first.