一 导入的依赖
<!-- test -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.verison}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>${power-mock.verison}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${power-mock.verison}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-core</artifactId>
<version>${power-mock.verison}</version>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${power-mock.verison}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4-rule</artifactId>
<version>${power-mock.verison}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-mock</artifactId>
<version>${spring-mock.verison}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.verison}</version>
</dependency>
二 依赖版本
<power-mock.verison>2.0.9</power-mock.verison>
<spring-mock.verison>2.0.8</spring-mock.verison>
<junit.verison>4.13.2</junit.verison>
<mockito.verison>3.12.0</mockito.verison>
三 controller测试示例代码
controller
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.xbook.common.constant.SysConstant;
import com.xbook.common.core.Result;
import com.xbook.entity.product.ProductDetail;
import com.xbook.product.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/product")
@Slf4j
public class ProductController {
@Reference(version = SysConstant.XBOOK_MALL_PRODUCT_VERSION, retries = 0, timeout = 1800000)
private ProductService productService;
/**
* 分页查询产品列表
* @param keyword
* @param categoryId
* @param pageNum
* @param pageSize
* @param orderBy
* @return
*/
@RequestMapping("/list")
public Result<PageInfo> list(@RequestParam(value = "keyword",required = false) String keyword,
@RequestParam(value = "categoryId",required = false) Integer categoryId,
@RequestParam(value = "pageNum",defaultValue = "1") int pageNum,
@RequestParam(value = "pageSize",defaultValue = "10") int pageSize,
@RequestParam(value = "orderBy",defaultValue = "") String orderBy){
PageInfo pageInfo = productService.pageProduct(keyword,categoryId,orderBy,pageNum,pageSize);
return Result.success(pageInfo);
}
}
controllerTest
import com.github.pagehelper.PageInfo;
import com.xbook.entity.product.ProductDetail;
import com.xbook.product.service.ProductService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
//@WebMvcTest(value = ProductController.class)
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class ProductControllerTest {
@MockBean
ProductService productService;
MockMvc mockMvc;
@Autowired
ProductController productController;
@Before
public void setUp(){
mockMvc = MockMvcBuilders.standaloneSetup(productController).build();
MockitoAnnotations.openMocks(productService);
}
@Test
public void testProductList() throws Exception {
PageInfo pageInfo = new PageInfo();
//Mockito.verify(productService);
given(productService.pageProduct(Mockito.anyString(),Mockito.anyInt(),Mockito.anyString(),Mockito.anyInt(),Mockito.anyInt())).willReturn(pageInfo);
//when(productService.pageProduct(Mockito.anyString(),Mockito.anyInt(),Mockito.anyString(),Mockito.anyInt(),Mockito.anyInt())).thenReturn(pageInfo);
mockMvc.perform(get("/product/list")
//.param("keyword","")
.param("categoryId","100008")
.param("pageNum","1")
.param("pageSize","20")
.param("orderBy","default")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(print());
}
}
测试结果:覆盖率100%
带异常的Controller
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.xbook.common.constant.SysConstant;
import com.xbook.common.enums.CodeMsgEnum;
import com.xbook.common.redis.key.UserKey;
import com.xbook.common.utils.CookieUtil;
import com.xbook.entity.user.User;
import com.xbook.redis.service.RedisService;
import com.xbook.user.service.exception.UserException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
@Slf4j
public class BaseController {
@Reference(version = SysConstant.XBOOK_MALL_REDIS_VERSION)
private RedisService redisService;
Integer getCurrentUserId(HttpServletRequest httpServletRequest) {
String loginToken = CookieUtil.getCookieValue(httpServletRequest, SysConstant.LOGIN_TOKEN);
if (StringUtils.isBlank(loginToken)) {
throw new UserException(CodeMsgEnum.SESSION_ERROR);
}
String jsonStr = redisService.get(UserKey.loginUser, loginToken);
if (StringUtils.isBlank(jsonStr)) {
throw new UserException(CodeMsgEnum.SESSION_ERROR);
}
User user = JSON.parseObject(jsonStr, User.class);
return user.getId();
}
}
带异常提示的ControllerTest
import com.alibaba.fastjson.JSON;
import com.xbook.common.constant.SysConstant;
import com.xbook.common.redis.key.UserKey;
import com.xbook.common.utils.CookieUtil;
import com.xbook.entity.user.User;
import com.xbook.redis.service.RedisService;
import com.xbook.user.service.exception.UserException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.mock.web.MockHttpServletRequest;
import javax.servlet.http.Cookie;
import static org.mockito.Mockito.when;
@WebMvcTest(BaseController.class)
@RunWith(PowerMockRunner.class)
@PrepareForTest(CookieUtil.class)
public class BaseControllerTest {
@Mock
RedisService redisService;
@InjectMocks
BaseController baseController;
@Test
public void testGetCurrentUserId(){
String cookie = "c0bd4c287a1a4465a80eb339916e19ef";
MockHttpServletRequest request = new MockHttpServletRequest();
String session = "{\"id\":53,\"username\":\"root\"}";
String cookieName = SysConstant.LOGIN_TOKEN;
request.setCookies(new Cookie(cookieName,cookie));
PowerMockito.mockStatic(CookieUtil.class);
PowerMockito.when(CookieUtil.getCookieValue(request, cookieName)).thenReturn(cookie);
when(redisService.get(UserKey.loginUser,cookie)).thenReturn(session);
Integer currentUserId = baseController.getCurrentUserId(request);
Assert.assertEquals(currentUserId, JSON.parseObject(session,User.class).getId());
}
@Test(expected = UserException.class)
public void testGetCurrentUserIdCookieIsNull(){
String cookie = "";
MockHttpServletRequest request = new MockHttpServletRequest();
String session = "{\"id\":53,\"username\":\"root\"}";
String cookieName = SysConstant.LOGIN_TOKEN;
request.setCookies(new Cookie(cookieName,cookie));
PowerMockito.mockStatic(CookieUtil.class);
PowerMockito.when(CookieUtil.getCookieValue(request, cookieName)).thenReturn(cookie);
when(redisService.get(UserKey.loginUser,cookie)).thenReturn(session);
baseController.getCurrentUserId(request);
}
@Test(expected = UserException.class)
public void testGetCurrentUserIdSessionIsNull(){
String cookie = "c0bd4c287a1a4465a80eb339916e19ef";
MockHttpServletRequest request = new MockHttpServletRequest();
String session = "";
String cookieName = SysConstant.LOGIN_TOKEN;
request.setCookies(new Cookie(cookieName,cookie));
PowerMockito.mockStatic(CookieUtil.class);
PowerMockito.when(CookieUtil.getCookieValue(request, cookieName)).thenReturn(cookie);
when(redisService.get(UserKey.loginUser,cookie)).thenReturn(session);
baseController.getCurrentUserId(request);
}
}
测试结果,覆盖率100%
三 service测试示例代码
service
import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.xbook.common.constant.SysConstant;
import com.xbook.common.enums.CodeMsgEnum;
import com.xbook.dao.user.ShippingMapper;
import com.xbook.entity.user.Shipping;
import com.xbook.user.service.AddressService;
import com.xbook.user.service.exception.UserException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
@Service(version = SysConstant.XBOOK_MALL_USER_VERSION)
public class AddressServiceImpl implements AddressService {
@Autowired
private ShippingMapper shippingMapper;
@Override
@Transactional
public Map saveAddress(Shipping shipping, Integer userId) {
shipping.setCreateTime(LocalDateTime.now());
shipping.setUserId(userId);
int shippingId = shippingMapper.insert(shipping);
Map result = Maps.newHashMap();
result.put("shippingId", shippingId);
return result;
}
}
serviceTest
import com.xbook.dao.user.ShippingMapper;
import com.xbook.entity.user.Shipping;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Map;
@RunWith(PowerMockRunner.class)
@SpringBootTest
public class AddressServiceImplTest {
@InjectMocks
AddressServiceImpl addressService;
@Mock
ShippingMapper shippingMapper;
@Test
public void testSaveAddress(){
PowerMockito.when(shippingMapper.insert(Mockito.any())).thenReturn(1);
Map map = addressService.saveAddress(new Shipping(), 53);
Assert.assertEquals(1,map.get("shippingId"));
}
}
测试结果:测试的方法全覆盖文章来源:https://www.toymoban.com/news/detail-627458.html
文章来源地址https://www.toymoban.com/news/detail-627458.html
到了这里,关于基于Junit4+Mockito+PowerMock实现Controller+Service的单元测试的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!