0
在PHP中,我有這樣的功能,其中它使用$this
關鍵字調用另一個函數searchDateOperator()
在同一類中。如何爲此編寫單元測試?
public static function segmetDateRangeFilter($searchField, $startDate, $endDate, $dateRange)
{
$filter = [];
if ($startDate && !$endDate) {
$filter = [
'range' => [
$this->searchDateOperator($searchField) => [
'gte' => strtotime($startDate),
]
]
];
}
if ($endDate && !$startDate) {
$filter = [
'range' => [
$this->searchDateOperator($searchField) => [
'lte' => strtotime($endDate)
]
]
];
}
if ($startDate && $endDate) {
$filter = [
'range' => [
$this->searchDateOperator($searchField) => [
'gte' => strtotime($startDate),
'lte' => strtotime($endDate)
]
]
];
}
if ($dateRange !== '') {
// $endTime upto current Time
$endTime = Carbon::now()->timestamp;
// Start Time . substract the date range days. and in timestamp
$startTime = Carbon::now()->subDays($dateRange)->timestamp;
$filter = [
'range' => [
$this->searchDateOperator($searchField) => [
'gte' => $startTime,
'lte' => $endTime
]
]
];
}
if ($filter) {
return $filter;
}
}
就像通常一樣 - 測試給定的$ searchField集合,$ startDate,$ endDate,$ dateRange是否與預期相同。或者還有其他什麼使得這不可能? – xmike
它具有函數searchDateOperator被調用,這是功能需要測試....在測試函數中,我只是調用這個函數,它會引發錯誤錯誤:使用$ this,而不是在對象上下文....但如果改變使用範圍解析運算符的調用它工作正常...問題是我想調用的函數使用$ this –
是另一個函數的引用是的,我錯過了'segmetDateRangeFilter'是靜態的,所以你把它稱爲靜態。這就強制searchDateOperator也是靜態的(否則就沒有意義)。所以將'$ this-> searchDateOperator($ searchField)'改爲'self :: searchDateOperator($ searchField)'應該這樣做。 – xmike