unit-testing - 持久化新对象并生成其 id 的单元测试代码
问题描述
我有一些代码将对象与学说保持一致,然后使用其新生成的 id 将其链接到另一个对象。
但是当我想测试代码时,没有生成id
class Foo extends DefaultDocument
{
/**
* @var int
* @MongoDB\Field(type="int")
* @MongoDB\Id(strategy="INCREMENT")
*/
protected $id
}
class Link
{
/**
* @var int
* @MongoDB\Field(type="int")
*/
private $fooId;
}
class Service
{
public function doesSomething()
{
$foo = new Foo();
$this->documentManager->persist($foo);
$link = new Link();
$link->setFooId($foo->getId());
}
}
class TestService
{
private function createService()
{
return new Service();
}
public function testDoesSomething()
{
$service = $this->createService();
$service->doesSomething();
}
}
启动测试时出现以下错误:
TypeError: 传递给 ...\Link::setFooId() 的参数 1 必须是 int 类型,给定 null
这是我的代码的默认逻辑,还是教义的正常行为?
编辑 :
终于为我的问题找到了正确的主题: Symfony2 : Doctrine : PHPUnit : Set entity Id during flushing with mocked entity manager in unit tests
我使用了他的第一个解决方案
解决方案
因为是单元测试,如果要获取id,就需要flush entity,然后学说填id字段,不过是功能测试,因为要使用数据库。
在单元测试中,您无法测试 ID 分配,只有在功能测试中才有可能
推荐阅读
- csv - Apache Spark 直接查询 Splunk 搜索结果
- git - 通过 git stash apply 覆盖
- android-studio - 居中 TextInputLayout 结束图标
- c - 通用打印 C 的错误字符输出
- java - 道室数据库。如何对所有金额求和并将其视为 TextView?
- azure - 如何创建具有所有者访问权限的用户无法删除其他具有所有者访问权限的用户的 Azure 策略
- unity3d - 我不能统一将精灵拖到动画窗口中
- javascript - 页面重新加载时 NippleJS 角度错误
- angular - 错误:Salesforce 沙箱 Angular 12 部署使用 gulp-jsforce-deploy
- android - Android Studio Gradle Plugin 7.0.1 似乎破坏了 android 权限 lint 检查