Before: You must init mockito in @Before of JUnit.
@Before
public void setUp() throws Exception
{
MockitoAnnotations.initMocks(this);
}
Annotation: @Mock@InjectMocks
@Mock : This annotation is used to mock an object. It seems like new Object() to give memory for this pointer.
@InjectMocks : This annotation is used to inject other mocks objects to the annotation decorated obejct.
Method: when()verify()any()
when() : This method is used to listen the emthod if be invoked.And when this method is invoked, you can give return value for this method. So you do not need to care the specific implemention of this method.
verify(): It is used to verify if this method be invoked and you also can verify the invoke times as params of this method.
any(): It is used for mock objects. You can only give the type of the param without specific value. It is common used in when method to instead of specific params.
Example:
package tech.shunzi.testdev.service;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import tech.shunzi.testdev.model.User;
import tech.shunzi.testdev.model.dto.UserDto;
import tech.shunzi.testdev.repo.UserRepository;
import tech.shunzi.testdev.service.impl.UserServiceImpl;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class UserServiceImplTest {
@Mock
private UserRepository userRepository;
@InjectMocks
private UserServiceImpl userService;
@Before
public void setUp() throws Exception
{
MockitoAnnotations.initMocks(this);
}
@Test
public void testGetAllUsers() {
// Prepare data
List<User> userList = new ArrayList<>();
User user = new User();
user.setDesc("DESC");
user.setId(1111);
user.setName("Shunzi");
userList.add(user);
List<UserDto> dtos = new ArrayList<>();
UserDto dto = new UserDto();
dto.setGroupNo(1);
dto.setName(user.getName());
dto.setId(user.getId());
dto.setIntroduction("Hello, I am Shunzi. And my id is 1111. DESC");
dtos.add(dto);
// When
when(userRepository.findAll()).thenReturn(userList);
// Act
List<UserDto> users = userService.findAllUsers();
// Verify
verify(userRepository).findAll();
// Assert
// override method equals() in UserDto class
assertEquals(dtos, users);
}
@Test
public void testGetUserById() {
// prepare data
int id = 1;
User user = new User();
user.setId(id);
user.setName("shunzi");
user.setDesc("desc");
// when
// anyInt() will match all params whose type is int
when(userRepository.findById(anyInt())).thenReturn(user);
// Act
UserDto userDto = userService.findSingleUser(id);
// verify
verify(userRepository).findById(anyInt());
// assert
assertEquals(id, userDto.getId());
}
}
SpringTest
mockMvc unit test
Before: You must init the MockMvc and bind it to controller class.
package tech.shunzi.testdev.integration.test;
import org.junit.Before;
import org.junit.Rule;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
@ActiveProfiles("test")
public abstract class BaseIntegrationTest {
@Autowired
protected MockMvc mockMvc;
@Rule
public final EnvironmentVariables environmentVariables = new EnvironmentVariables();
@Before
public void setUpEnv()
{
environmentVariables.set("key","value");
}
}
其余具体的 Integration Test Class均可继承 BaseIntegrationTest
package tech.shunzi.testdev.integration.test;
import org.junit.Test;
import org.springframework.http.MediaType;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public class UserControllerIntTest extends BaseIntegrationTest {
@Test
public void testFindAll() throws Exception {
// Prepare data
String requestUrl = "/users";
// Act
String responseStr = mockMvc.perform(get(requestUrl).accept(MediaType.APPLICATION_JSON_UTF8)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
// Advise to use assert, sout in here is just to show query result from DB
System.out.println(responseStr);
}
}