Spock怎么测试Service中的Mapper

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cg_Amaz1ng/article/details/84873865

之前在博客园上提的一个问题,没有人答复,自己解决了:
在这里插入图片描述

把赋值的语句写到given语句块,如:

given :

def backBill_rel = new BackBill(billNo : "002") 
def list = new ArrayList<BackBill>()
list.add( backBill_rel )       
backBillMapper.selectList( _ as QueryWrapper) >> list

高级用法

对静态对象赋值,比如applicationContext无法自动注入时

@Component
public class ApplicationContextUtils implements ApplicationContextAware {

	private static ApplicationContext applicationContext = null;

	/**
	 * 获取静态变量中的ApplicationContext.
	 */

	public static ApplicationContext getApplicationContext() {

		return applicationContext;

	}

	/**
	 * 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型.
	 */

	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name) {

		return (T) applicationContext.getBean(name);

	}

	/**
	 * 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型.
	 */
	public static <T> T getBean(Class<T> requiredType) {

		return applicationContext.getBean(requiredType);
	}

	/**
	 * 清除SpringContextHolder中的ApplicationContext为Null.
	 */
	public static void clearHolder() {

		applicationContext = null;

	}

	/**
	 * 实现ApplicationContextAware接口, 注入Context到静态变量中.
	 */

	@Override
	public synchronized void setApplicationContext(ApplicationContext applicationContext) {

		ApplicationContextUtils.applicationContext = applicationContext;

	}

}

Spock写法:

given:
ApplicationContextUtils.applicationContext = Mock(ApplicationContext)
ApplicationContextUtils.applicationContext.getBean( _ ) >> Mock(BusinessTransactionRunner)

猜你喜欢

转载自blog.csdn.net/cg_Amaz1ng/article/details/84873865