关于Java:使用Mockito注入自动装配的bean并在模拟上设置一些属性
demo
/** * @author lfy * @Description 支付上下文引用支付策略; 这个上下文也是模板类;定义好算法步骤 * @create 2022-12-28 22:46 */ @Service @Slf4j //模板类 public class PayServiceImpl implements PayService { @Autowired private List<PayStrategy> payStrategies; //注入支付策略 /** * 生成收银台页面 * @param type * @param orderId * @return */ @Override public String payPage(String type, Long orderId) { //1、查询数据库订单 OrderInfo orderInfo = getOrderInfo(orderId); //2、生成支付页 for (PayStrategy strategy : payStrategies) { if(strategy.supports(type)){ //获取收银台页面 return strategy.cashierPage(orderInfo); } } //3、如果以上都不支持,打印错误 return "不支持这种支付方式"; } public OrderInfo getOrderInfo(Long orderId){ log.info("查询数据库订单:{}",orderId); OrderInfo orderInfo = new OrderInfo(); orderInfo.setId(orderId); orderInfo.setTitle("尚品汇-商城-订单"); orderInfo.setComment("快点发货"); orderInfo.setDesc("买了一堆商品"); orderInfo.setPrice(new BigDecimal("9098.00")); orderInfo.setExpireTime(new Date(System.currentTimeMillis()+30*60*1000)); return orderInfo; } }
添加gav
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>1.8.5</version> <scope>test</scope> </dependency>
测试类
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>1.8.5</version> <scope>test</scope> </dependency>