Mocking for integration tests

后端 未结 3 1881
死守一世寂寞
死守一世寂寞 2021-01-30 13:05

How does one mock the many dependencies needed for integration tests?

I use Mockito for my \'pure\' unit tests. \'Pure\' in this case means testing a single class, mock

3条回答
  •  伪装坚强ぢ
    2021-01-30 14:00

    In order to mock things like databases, web services, the file system and so on, you will probably want to refactor a little. For each external service, you should write a wrapper class that has a method for each operation that you wish to perform. Each such method should have no actual logic, but just pass through its parameters in the way that the external service will understand, and return an object that contains whatever data the external service returns. For example, if you're interacting with a database, the wrapper class might format its parameters into an SQL statement, submit them into an existing Connection object, and return a List for the result.

    Because the methods of the wrapper class contain no logic (that is, no if/else, no loops and no exception handling); there is no need to unit test the wrapper class. You should integration test the wrapper class, to make sure that its responsibilities are performed correctly (that is, that the SQL statement has the desired effect on the database, for example).

    Now re-write the classes that interact with the external services so that they interact with the wrapper classes instead. It's then easy to unit test them - you just have to mock the wrapper classes.

提交回复
热议问题