单元测试适用于此吗?

Is Unit Test Applicable Here?

 public function addPic($loggedInId,$PicId){

        $chatCoverPhotoObj = new COVER_PHOTO();
        $out = $chatCoverPhotoObj->add($loggedInId,$PicId);

        if($out)
            return true;
        return false;
    }

以上示例代码写在php中,简单的添加记录在table中 COVER_PHOTO 记录:"picId" 对应于由 "loggedInId" 标识的登录用户。

我想知道我应该在这个函数的单元测试中写些什么。 或者这样的功能我们不应该写单元测试。

请推荐?

首先,如果您 System-/Class Under Test is using anything that is infrastructural concern -which in your case is the database- that tends to be an integration test.

单元测试在完全隔离的情况下进行,每个可能的依赖项都已排除 mocked/stubbed。

我在您的代码中看到的第一个问题是您 new() 建立了函数的依赖项。这样你就不能真正轻松地测试你的代码。

我建议你最好 invert this dependency and have an interface in the constructor of your class, which can receive the concrete implementation of that interface. Once this is done, you can mock 在你的测试中去掉数据库部分。但是,通过查看您在问题中共享的代码,我不太确定您要在此处测试的 behaviour 是什么。

始终确定您要测试的内容,在本例中是持久性规范或映射配置(当然是在您使用某种 OR/M 的情况下)。仅检查持久性操作的 return 值(即成功或失败标志)并不会增加太多商业价值来进行测试。