Mocking for integration tests

我只是一个虾纸丫 提交于 2019-12-02 15:30:59

Great question.

It seems like you hit the limits of Mockito. Mockito is great if what you want to inspect object interactions.

What you want, though, seems to be observability (and controllability) at a higher level of abstraction. I'm afraid that the mocks or stubs you need for that should be carefully designed and hand-crafted.

At the unit level, these mocks can be nicely generated, by means of Mockito. At the integration level, this becomes much harder, and you will need purpose made testability interfaces.

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.

If there is some http or rest mock framework, using that should be good.

All the complicated dependencies can be recorded, modified and replayed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!