我试图用PhpUnit/Mockery/Laravel围绕单元测试.这并不容易.我一直在阅读几十个教程,但仍然不能在现实生活场景中应用它.
我将介绍一些我想测试的代码.谁能指点我如何测试类SoldProductModifier的方法modifyBasedOnItemCode()?
首先解释几句:我希望用户能够输入产品代码(项目代码)和数量,我希望系统自动更新product_id以及SoldProduct模型的category_id属性.为此我创建了我现在要测试的类.
另请参阅: 我的数据库的简化图(仅与我的问题相关的表)
现在相关代码:
要测试的类
use App\Models\Product;
class SoldProductModifier
{
private $sold_product;
public function __construct(SoldProduct $sold_product)
{
$this->sold_product = $sold_product;
}
public function modifyBasedOnItemCode($item_code)
{
if (! isset($item_code) || $item_code == '')
{
$product = Product::findByItemCode($item_code);
if (isset($product) && $product != false)
{
$this->sold_product->category_id = $product->category->id;
$this->sold_product->product_id = $product->id;
}
}
return $this->sold_product;
}
}
产品型号
...
public static function findByItemCode($item_code) {
return self::where('item_code', $item_code)- …