如何在Tricentis Tosca中选取上月的有效工作日?
Tricentis Tosca 生成上月工作日日期解决方案
一、内置函数组合实现(优先方案)
Tricentis Tosca没有直接判断工作日的内置函数,但可以通过DATEADD和DATEPART组合实现需求:
- 先通过
DATEADD获取上月对应日期:DATEADD("M", -1, CURRENT_DATE()) - 用
DATEPART("w", [日期变量])判断星期数(Tosca中DATEPART("w")返回值:1=周日,2=周一,6=周五,7=周六) - 通过嵌套
IIF函数调整日期到最近工作日:
逻辑说明:IIF(DATEPART("w", DATEADD("M", -1, CURRENT_DATE())) = 1, DATEADD("d", -2, DATEADD("M", -1, CURRENT_DATE())), IIF(DATEPART("w", DATEADD("M", -1, CURRENT_DATE())) = 7, DATEADD("d", -1, DATEADD("M", -1, CURRENT_DATE())), DATEADD("M", -1, CURRENT_DATE())))- 若上月日期是周日(返回1),回退2天到周五
- 若上月日期是周六(返回7),回退1天到周五
- 周一至周五则保持原日期
如果嫌表达式过长,可以拆分到多个变量:
- 定义变量
LastMonthRawDate,赋值为DATEADD("M", -1, CURRENT_DATE()) - 定义变量
LastMonthWorkday,赋值为IIF(DATEPART("w", LastMonthRawDate) =1, DATEADD("d",-2,LastMonthRawDate), IIF(DATEPART("w", LastMonthRawDate)=7, DATEADD("d",-1,LastMonthRawDate), LastMonthRawDate))
二、自定义Scriptlet方案(支持复杂场景)
如果需要处理节假日或更灵活的日期逻辑,推荐用Tosca Scriptlet编写C#代码:
- 创建C#类型的Scriptlet,添加以下方法:
public static string GetLastMonthWorkday() { DateTime targetDate = DateTime.Now.AddMonths(-1); // 跳过周末 while (targetDate.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday) { targetDate = targetDate.AddDays(-1); } // 可选:添加节假日判断(自定义节假日列表) // var holidays = new List<DateTime> { new(2024, 1, 1), new(2024, 2, 10) }; // while (holidays.Contains(targetDate)) // { // targetDate = targetDate.AddDays(-1); // } return targetDate.ToString("yyyy-MM-dd"); // 按测试需求调整日期格式 } - 在测试用例中调用该Scriptlet,将返回值绑定到需要输入日期的控件。
内容的提问来源于stack exchange,提问作者Felipe Pouysségur
相关产品推荐
相关产品推荐

