Unit Test (Java Spring)
Pre-Action
Install J Unit and Mockito dependencies
E.g: Maven
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.23.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>2.23.0</version>
<scope>test</scope>
</dependency>Stub vs Mock vs Spy
Stub vs Mock
Stub: Initialize -> Exercise -> Verify
Mock: Initialize -> Set up expectations -> Exercise -> Verify
Mock vs Spy
Spy will actually call the real method of the class , while mock doesn't
Spy
Mock
Mockito Method
doAnswer (used to mock the void type function)
doReturn (used to mock the return value of function)
Service Testing Example
TestServiceImpl
ShopServiceImpl
testServiceTest
Controller Unit Test
MockMvc
Create a new MockMvc Object as a entry point, so that we can use it to call the link of API
Method
perform: make a request to api end point
andExpect: verify the result whether the actual is equal to actual or not
andDo: to make a handling after getting the result, such as print out the response
andReturn: return back to MvcResult
MockMvcRequestBuilders
Used to create a request
Methods
MockMvcResultMatchers
used to match the result of api end point , such as content-type, https status, return value
Methods
MockMvcResultHandlers
used to print the whole of the response of api end point
Example
Reference
Last updated
Was this helpful?