Mockito - @Spy vs @Mock

后端 未结 7 1007
南旧
南旧 2020-11-29 17:33

Mockito - I understand a spy calls the real methods on an object, while a mock calls methods on the double object. Also spies are to be avoided unless there is a code smell.

7条回答
  •  忘掉有多难
    2020-11-29 18:20

    The best place to start is probably the docs for mockito.

    On a general note the mockito mock allows you to create stubs.

    You would create a stub method if, for example, that method does an expensive operation. Say, it gets a database connection, retrieves a value from the database and returns it to the caller. Getting the db connection might take 30 seconds, slowing your test execution to the point where you'll likely context switch (or stop running the test).

    If the logic you are testing doesn't care about the database connection then you could replace that method with a stub which returns a hard coded value.

    The mockito spy lets you check whether a method calls other methods. This can be very useful when trying to get legacy code under test.

    It is usful if you are testing a method that works through side effects, then you would use a mockito spy. This delegates calls to the real object and allows you to verify method invocation, number of times invoked etc.

提交回复
热议问题