Mock and Stub

description:

We have a dojo about Mock and Stub.But first we couldn't use mockito to do that and need to use to a fack class to finsh. In the class CashRegister, it has a method process.In this method, we need to call the other method print which in the class Print. At the same time, we need to call the method asString,which in other class Purchase.

Question

  • Q1: if don't use mockito, I don't know how to test the print method .
    A1: My India pair told me that we should create a class FakePrint and FakePurchaseto simulate classes.Why ? I think What we have to do is like mokito, need a fake FakePrintto show that the method printhas been called, and FakePurchase to show the method asStringhas return something.

  • Q2: what the differences between the two tests?
    A2: We test Whether print the method is called,it's Mock.Mock concerned about behavior verification; While we test the value of asStringreturned. It 's Stub.Stub focus on the state verification,For replacing a method with code that returns a specified result. As the book 《Practical Unit Testing with JUnit and Mockito》said, Mock used to verify if the SUT(System under test) calls specific methods of the collaborator ("indirect outputs"), while used for passing some values to the SUT ("indirect inputs").

  • Q3: Why we use Mock and Stub?
    A3:A unit test should test functionality in isolation. Side effects from other classes or the system should be eliminated for a unit test, if possible.

  • Q4:When we use Mock and when we use Stub?
    A4: When the behavior of the objects we simulate is uncertain, it is difficult to create and simulate, or the real object is not yet implemented,we use Mock,for example: network error. Stubs are typically encapsulated for a real object,Such as access to file systems, database connections, and remote protocols.

Reflection

sometimes,I know some concept, but I don't know how to use them.

action

When we look at the document to learn new things, according to the example to write demo again, do not just focus on the concept itself.

你可能感兴趣的:(Mock and Stub)