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);
}
}
Mockito
How
service/dao unit test
@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.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 inwhen
method to instead of specific params.SpringTest
mockMvc unit test
MockMvc
perform()
,get() post() put() delete()
,contentType()
,param()
,andExpect()
,status()
,isOk()
,andReturn()
,getResponse()
,getContentAsString()
//PUT String responseData = mockMvc.perform(put(requestURI).param("tenantId", "dev")). andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
//DELETE String data = mockMvc .perform(delete(requestURI).contentType(MediaType.APPLICATION_JSON).content("the params with json format") .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
PowerMock
public static returnValue methodName(T param)
How to use:
@PrepareForTest(IncludeStaticMethodClass.class)
to annotate unit test class.@RunWith(PowerMockRunner.class)
to annotate unit test class.PowerMockito.mockStatic()
// mock static classPowerMocckito.when()
// mock static method invokeCaution:
Mockito
version集成测试 Integration Test (IT)
@Mock
的方式进行注入的,在集成测试的场景下可以直接@Autowire
相关对象,同时能够和DB
进行交互,也能对相关接口进行实际场景的测试。Spring Integration Test
Prepare:
ActiveProfiles("test")
代码实例:
Integration Test Class
均可继承BaseIntegrationTest
系统测试 System Test (ST)
JMeter
Download and Launch
How to use JMeter
Example Code
Head First
Step 1. Create Thread Group
Step 2. Define some common variables
Step 3. New Http Request
Step 4. New Asserters.(JSON Assertion, Response Assertion etc.)
Step 5. Processor (Pre/Post)
Step 6. Result Tree
自动化测试(Auto UI Test)
Katalon Studio
Groovy (Based on Java)