Mock相关
Mock-对象属性赋值
对象代码:
public class WebAgreeService {
@Resource
private SecurityProperties securityProperties;
@Value("${a.new.c:true}")
private boolean newSign;
}
Mock处理:
@Before
public void init() {
MockitoAnnotations.initMocks(this);
ReflectionTestUtils.setField(service, "newSign", true);
ReflectionTestUtils.setField(service, "securityProperties", initSecurityProperties());
}
public SecurityProperties initSecurityProperties(){
SecurityProperties properties = new SecurityProperties();
properties.setSecret("123");
properties.setNativeB2BRedirectUrl("http://localhost:8080/h5/****2");
properties.setYlxGzhRedirectUrl("http://localhost:8080/h5/****2");
properties.setYlxAppRedirectUrl("http://localhost:8080/h5/****2");
properties.setRedirectAgreeH5Url("http://localhost:8080/h5/****2");
properties.setRedirectAgreePcUrl("http://localhost:8080/h5/****2");
properties.setRedirectUrl("http://localhost:8080/h5/****2");
return properties;
}
Mock-私有方法
私有方法
/**
* 获取当前交易信息
* @return 交易具体信息
*/
public TradeVO current() {
TradeJwtVariable variable = TradeJwtVariable.getVariable();
String jwtId = variable.getJwtId();
String tradeId = variable.getTradeId();
String cacheJwtId = jedisCluster.get(TRADE_JWT_ID_PREFIX + tradeId);
if (!jwtId.equals(cacheJwtId)) {
throw InnerErrorCodeEnum.PAGE_FAULTING.toBizException();
}
String tradeModelJson = jedisCluster.get(TRADE_INFO_PREFIX + tradeId);
if (tradeModelJson == null) {
throw InnerErrorCodeEnum.PAGE_FAULTING.toBizException();
}
return JSON.parseObject(tradeModelJson, TradeVO.class);
}
Mock处理
WebTradeService spyWebTradeService = Mockito.spy(webTradeService);
Mockito.doReturn(tradeVO).when(spyWebTradeService).current();
Mock-static方法
先给对象添加注解,并将类放进去。例如:@PrepareForTest({Cat.class})
原始方法:
public class JwtWithHS256 {
public static String build(Claims claims, String key) {
SignatureAlgorithm alg = SignatureAlgorithm.HS256;
return Jwts.builder().setClaims(claims).signWith(alg, key).compact();
}
public static String setJwt(Claims claims, String key) {
SignatureAlgorithm alg = SignatureAlgorithm.HS256;
String jwt = Jwts.builder().setClaims(claims).signWith(alg, key).compact();
}
}
Mock处理:
PowerMockito.mockStatic(JwtWithHS256.class);
PowerMockito.when(JwtWithHS256.build(any(Claims.class), anyString())).thenReturn("1");
Mock-static-void方法
Method method = PowerMockito.method(JwtWithHS256.class, "setJwt", Claims.class, String.class);
PowerMockito.when(JwtWithHS256.class, method).withArguments(Mockito.any(), Mockito.any());
Mock-static方法抛异常
Mock处理:
PowerMockito.mockStatic(JwtWithHS256.class);
PowerMockito.when(JwtWithHS256.build(any(Claims.class), anyString())).thenThrow(new RuntimeException("异常"));