来自数据库的 return 值的单元测试函数
Unit test function that return value from database
目前我想创建单元测试来覆盖我开发的功能中的某些功能,但是当我面对这种功能时遇到问题,当功能的目的是从数据库中检索结果时。
public function saveMessage($request)
{
$validation = $this->validate($request);
if($validation['status']) {
$input = $validation['detail'];
$data = [
'id' => $input['id'],
'note' => $input['message'],
'create_by' => $input['create_by'],
'status' => $input['status'],
'create_date' => DATETIME,
];
$result = $this->fooService->insert($data);
return [
'success' => true
];
}
return $validation;
}
是否可以在不接触数据库的情况下涵盖这种功能?
对于单元测试,您应该模拟方法的整个依赖关系,否则它将成为集成测试。
我曾经用 Prophecy 来模拟(很快从 phpunit 10 开始弃用)但是你可以使用 MockBuilder 它是相同的原则,如果你想模拟 $this->fooService
:
protected function setUp(): void
{
$this->fooService = $this->prophesize(FooService::class);
$this->classOfMethodToTest = new ClassOfMethodToTest(
$this->fooService->reveal()
); // mock FooService dependency
}
public function testSaveMessage(): void
{
$this->fooService
->insert(Argument::type('array')) // or an real array
->shouldBeCalledOnce() // apparently it is called only once
->willReturn(true) // for example i don't know real logic
;
$this->classOfMethodToTest->saveMessage($fakeData);
}
目前我想创建单元测试来覆盖我开发的功能中的某些功能,但是当我面对这种功能时遇到问题,当功能的目的是从数据库中检索结果时。
public function saveMessage($request)
{
$validation = $this->validate($request);
if($validation['status']) {
$input = $validation['detail'];
$data = [
'id' => $input['id'],
'note' => $input['message'],
'create_by' => $input['create_by'],
'status' => $input['status'],
'create_date' => DATETIME,
];
$result = $this->fooService->insert($data);
return [
'success' => true
];
}
return $validation;
}
是否可以在不接触数据库的情况下涵盖这种功能?
对于单元测试,您应该模拟方法的整个依赖关系,否则它将成为集成测试。
我曾经用 Prophecy 来模拟(很快从 phpunit 10 开始弃用)但是你可以使用 MockBuilder 它是相同的原则,如果你想模拟 $this->fooService
:
protected function setUp(): void
{
$this->fooService = $this->prophesize(FooService::class);
$this->classOfMethodToTest = new ClassOfMethodToTest(
$this->fooService->reveal()
); // mock FooService dependency
}
public function testSaveMessage(): void
{
$this->fooService
->insert(Argument::type('array')) // or an real array
->shouldBeCalledOnce() // apparently it is called only once
->willReturn(true) // for example i don't know real logic
;
$this->classOfMethodToTest->saveMessage($fakeData);
}