问题
What is the difference between mocks and stubs in jMock? I can create both with jMock? how i can create stubs with it and what the situation is most appropriate for this, I believe that using stubs is when I need to prepare some state for test.
Thanks
回答1:
Wikipedia has an article regarding Mock objects, but the terminology is not explained as good as could be. We used to make this distinction (which may be subject to discussion, of course):
Mocks and stubs both simulate an object which is required for testing a component.
The word "mock" is used when you want to assert that a specific kind of interaction between the tested component and the mocked object takes place. That's why mock frameworks (like EasyMock) provide methods to assert that all expected calls have actually been performed. E. g. you want to see that your service actually calls a (mocked) DAO. So this call is part of your test conditions / assertions.
The word "stub" however is used when you are simply trying to provide an implementation which helps testing your component. What kind of interaction takes place does not matter, you just want the stub to fill in the gaps so you can test your component. Your focus lies on the tested components and what it does.
So it's just two words for the same thing, depending on what you are trying to achieve with it.
回答2:
Mocha is a traditional mocking library very much in the JMock mould. Stubba is a separate part of Mocha that allows mocking and stubbing of methods on real (non-mock) classes. It works by moving the method of interest to one side, adding a new stubbed version of the method which delegates to a traditional mock object. You can use this mock object to set up stubbed return values or set up expectations of methods to be called. After the test completes the stubbed version of the method is removed and replaced by the original.
for more detail with example
http://jamesmead.org/blog/2006-09-11-the-difference-between-mocks-and-stubs
回答3:
We usually make a distinction between queries and actions. Queries don't change the state of the world outside the mocked object--we can call it once or 5 times. They're like pre-conditions if you've done Design by Contract.
Actions change the outside world (e.g. subtract a value), and we specify mocks for those. It matters how many times we call a mock because the results will be different. These are like post-conditions.
Stub Queries, Mock Actions.
来源:https://stackoverflow.com/questions/5764981/what-is-the-difference-between-mocks-and-stubs-jmock