1、
在方法体内Mock一个对象,这个对象在出了这个方法体后消失,变为null…想不消失的话,只能return对象
2、
关于什么时候用def,什么时候用具体类型
这里说明一下,def是动态的类型,当你不知道类型具有什么样的泛型时,使用def
例如:def defaultValueOperations = Mock(DefaultValueOperations)
如果使用DefaultValueOperations defaultValueOperations = Mock()这种构造方式,则有可能出错,因为
class DefaultValueOperations<K, V>是需要具体泛型的
3、
char和string都会被统一转成string,比如有以下代码:
public class NumberTools {
/**
* 将整数转为字符,左补
*/
public static String lPad(int sSeqNo,int iDigit,char sFillChar) throws Exception {
String sTempSeqNo="";
for(int i=0;i<iDigit;i++){
sTempSeqNo=sFillChar+sTempSeqNo;
}
DecimalFormat df = new DecimalFormat(sTempSeqNo);
return df.format(sSeqNo);
}
}
测试方法为:
@Unroll
def "lPadIntIntChar"()
{
when: "将整数转为字符,左补"
def result = NumberTools.lPad( sSeqNo, iDigit, sFillChar )
then:
noExceptionThrown()
result.equals( res )
where:
sSeqNo|iDigit|sFillChar|res
1 |8 |'0' |"00000001"
1234 |8 |'*' |"****1234"
1234 |4 |'0' |"1234"
1234 |3 |'*' |"123"
}
运行这个单元测试,会报找不到方法的错误:
Expected no exception to be thrown, but got ‘groovy.lang.MissingMethodException’
at spock.lang.Specification.noExceptionThrown(Specification.java:118)
at com.dashuf.caes.account.util.NumberToolsTest.lPadIntIntChar(NumberToolsTest.groovy:23)
Caused by: groovy.lang.MissingMethodException: No signature of method: static com.dashuf.caes.account.util.NumberTools.lPad() is applicable for argument types: (java.lang.Integer, java.lang.Integer, java.lang.String) values: [1, 8, 0]
Possible solutions: lPad(int, int, char), lPad(double, int, char), rPad(int, int, char), find(), wait(), grep()
at com.dashuf.caes.account.util.NumberToolsTest.lPadIntIntChar(NumberToolsTest.groovy:20)
这是因为,groovy把sFillChar这个字段的值当成string了。 解决办法:
def result = NumberTools.lPad( sSeqNo, iDigit, sFillChar )
改成
def result = NumberTools.lPad( sSeqNo as int, iDigit as int , sFillChar as char )
4、Groovy给私有属性赋值的两种方式:
1)第一种比较常见,初始化赋值
eg:
Demo demo = new Demo(
name:name,
age:age,
address:address
)
2)第二种,可以满足特殊情况下的赋值
假设有类:SystemConfig.java
@Component
public class SystemConfig {
private static SystemConfig systemConfig;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@PostConstruct
public void init() {
systemConfig = this;
systemConfig.stringRedisTemplate = this.stringRedisTemplate;
}
public static LocalDate getBusinessDate()
{
String businessDate = systemConfig.stringRedisTemplate.boundValueOps("BUSINESSDATE").get();
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
return LocalDate.parse( businessDate, df );
}
}
由于外部调用getBusinessDate()方法通常是静态调用:SystemConfig.getBusinessDate()
因此我们无法简单得使用第一种方案,我们可以使用如下两种结合:
SystemConfig systemConfig = new SystemConfig(
stringRedisTemplate:stringRedisTemplate
)
SystemConfig."systemConfig" = systemConfig