DAY 7
0
DevOps

## Function

``````<?php

{
\$sum = \$x + \$y;

return \$sum;
}
``````

``````<?php

var_dump(\$num); // will see 3
``````

``````<?php
// sum.php

function sum(array \$numbers = [])
{
\$sum = 0;

foreach (\$numbers as \$number) {
\$sum = \$sum + \$number;
}

return \$sum;
}
``````

``````<?php
// sumTest.php

include 'sum.php';

\$arr = [1, 2, 3];

\$sum = sum(\$arr);

var_dump(\$sum); // will see 6
``````

### 什麼是 3A 原則呢？

1. 一定會有明顯執行測試的目標，如 `addTest.php``add(1, 2);``sumTest.php``sum(\$arr);`
2. 一定會有驗證的方法，此兩例都是用 `var_dump()` 取得數值並做人工驗證
3. 可能會有安排初始化輸入值的過程。值得一提的是，雖然上面兩例都有輸入值，但如果直接執行 `sum()` 是會回傳 0 的。因此還需要另外測試這段程式碼：
``````<?php

include 'sum.php';

\$sum = sum();

var_dump(\$sum); // will see 0
``````
而這個測試案例就沒有輸入值

• Arrange: 初始化的過程
• Act: 執行測試的目標，並取得實際結果
• Assert: 驗證結果

``````<?php

// Arrange
\$x = 1;
\$y = 2;
\$excepted = 3;

// Act

// Assert
if (\$actual === \$excepted) {
} else {
}
``````

## Class

``````<?php
// number.php

class Number
{
private \$number;

public function __construct(\$number)
{
\$this->number = \$number;
}

{
}

public function sub(\$subtrahend)
{
return \$this->number - \$subtrahend;
}

public function get()
{
return \$this->number;
}
}
``````

``````<?php
// numberTest.php

include 'number.php';

// Act
\$target = new Number(\$number);
\$actual = \$target->get();
``````

``````<?php
// numberTest.php

include 'number.php';

// Act
\$target = new Number(\$number);
\$actual = \$target->get();

// Assert
if (\$actual === \$number) {
} else {
}
``````

``````<?php
// numberTest.php

include 'number.php';

// Arrange
\$number = 10;
\$excepted = \$number;

// Act
\$target = new Number(\$number);
\$actual = \$target->get();

// Assert
if (\$actual === \$excepted) {
} else {
}
``````

``````<?php
// numberTest.php

include 'number.php';

// Arrange
\$number = 10;
\$excepted = \$number;

\$subtrahend = 5;
\$exceptedSub = 5;

// Act
\$target = new Number(\$number);
\$actual = \$target->get();

// Assert
if (\$actual === \$excepted) {
} else {
}

// Act
\$target = new Number(\$number);

// Assert
} else {
}

// Act
\$target = new Number(\$number);
\$actual = \$target->sub(\$subtrahend);

// Assert
if (\$actual === \$exceptedSub) {
} else {
}
``````

1. 一開始一定會想測一個功能，比方說會員列表 (Act)
2. 再來一定會思考會員列表應該會長什麼樣，應該會是表格一列一列的樣子 (Assert)
3. 打開發現沒有東西，知道是因為資料庫還沒有資料，所以就去新增資料 (Arrange)
4. 最後再打開一次，確認有資料，於是測試就通過了

## 今日回顧

• 3A 原則是測試的 pattern
• 有了 3A 原則，思考如何寫測試程式會比較清楚

CI 從入門到入坑30

53 人訂閱