我正在测试一种方法,该方法在将社会保险号保存到数据库之前使用公钥对其进行加密。它看起来像这样:
public function setSsnAttribute($value)
{
// Load the public key
$public = file_get_contents(Config::get('certificates.public'));
// Attempt to encrypt the social security number using the public key
if (!openssl_public_encrypt($value, $crypted, $public))
{
throw new Exception('Could not encrypt data. Nothing was stored.');
}
// The value of $crypted returned by openssl_public_encrypt contains
// binary characters. Rather than storing the data in a BLOB, I'm
// electing to use base64 encoding to convert it to a string that is
// suitable for storage in the database.
$crypted = base64_encode($crypted);
$this->attributes['ssn'] = $crypted;
}
问题是Config::get('certificates.public')
调用。我想确保在加密步骤失败时抛出适当的异常。Config::get('certificates.public')
的值返回配置文件中定义的公共证书的路径。我的想法是,测试异常的最简单方法是为公共证书提供一个坏路径。
我可以在配置文件中定义一个额外的参数。我在想类似certificates.test.public.bad
的东西会返回/dev/null
或类似的东西。
在单元测试期间指定备用配置参数的最佳实践是什么?在setSsnAttribute
方法中加载证书的路径对我来说似乎很可疑。是否有一种更测试友好的方式来加载配置参数?
回到Laravel文档后,我意识到我可以通过简单地从单元测试中调用参数上的Config::set()
来覆盖我需要的任何配置参数。例如:
/**
* @expectedException Exception
*/
public function testSsnDecryptionFailureThrowsException()
{
// Replace the private certificate with
Config::set('certificates.private', '/dev/null');
$application = FactoryMuff::create('Lease317'RentalApplication');
// I must access the attribute in order to trigger the decryption
$application->ssn;
}
按预期工作,现在我在模型上有100%的代码覆盖率。