需求
接口测试中,有时候需要使用到日期格式的字段值,不仅是当前时间,还需要带偏移量的时间。
实现
1.编写构造函数和成员变量
private String timeZone;
private TimeUtil timeUtil;
public TimeFixture(String format) {
timeUtil = new TimeUtil(format);
}
2.实现方法(关键字)
public String getCurrentTime() {//获取当前时间,格式是yyyyMMddHHmmss
return timeUtil.getTime(Calendar.SECOND, "0", this.timeZone);
}
public String getDay(String count) {//获取当前或偏移天数
String time = null;
try {
time = timeUtil.getTime(Calendar.DAY_OF_MONTH, count, this.timeZone);
} catch (NumberFormatException e) {
time = "NumberFormatException";
logger.debug("NumberFormatException:", e);
}
logger.info("time: {}", time);
return time;
}
public class TimeUtil {
private String format = "yyyyMMddHHmmss";
public TimeUtil() {
}
public TimeUtil(String format) {
this.format = format;
}
public String getTime(int calendar, String count ,String timeZone) throws NumberFormatException {
int i_count = Integer.parseInt(count);
SimpleDateFormat format = new SimpleDateFormat(this.format);
if(timeZone!=null){
format.setTimeZone(TimeZone.getTimeZone(timeZone));
}
String time = format.format(getDate(calendar, i_count));
return time;
}
private Date getDate(int calendar, int count) {
Calendar calendarNew = Calendar.getInstance();
calendarNew.add(calendar, count);
return calendarNew.getTime();
}
}
使用
1.引入类对应package
|import |
|own.slim.time|
2.编写脚本
|script|time fixture|yyyyMMddHHmmss|
|show |getCurrentTime |
|show |getDay |0 |
|show |getDay |3 |
|show |getDay |-3 |
3.测试
总结
上面例子中,只给出了按天偏移的方法。同理还可以编写按照秒、月、年的方法。