Detailed and basic usage of Mockito
Mockito is a Mock framework for Java single-testing, but it can also be used with other single-testing frameworks in addition to JUnit. Mockito changes the behavior of a class or object, allowing us to focus more on testing the code logic without the effort of constructing the data.
The basic concept
Mocks can be of two types, Class and Partial,so Mockito is called spy. The behavior of changing methods on mock objects is called Stub.
A Mock process is called a Mock Session, and it records all the Stubbing. It consists of three steps:
+----------+ +------+ +--------+ | Mock/Spy | ===> | Stub | ===> | Verify | +----------+ +------+ +--------+
Class Mock
A Class Mock changes the behavior of a Class so that the object it mocks completely loses its original behavior.
Method returns default values (null, false, 0, etc.) if it is not pegged.
The most basic usage is as follows:
1 | import static org.mockito.Mockito.*; |
Partial Mock(spy)
If we only want to change the behavior of an instance, we need to use spy:
1 | List list = new LinkedList(); |
As you can see from the code, the main difference between a Spy and a MockSettings is that the MockSettings for a Spy needs to be passed in a SpiedInstance.
The default Answer to a spy is CALLS_REAL_METHODS, which means that if a method is not stub, it performs its real behavior.
The default Answer to a mock is RETURNS_DEFAULTS. Methods that are not stub return a default value.
source:
https://www.vogella.com/tutorials/Mockito/article.html
https://howtodoinjava.com/mockito/junit-mockito-example/
Comments
Post a Comment