PHPUNIT 如何在一种情况下测试不存在值的地方?



我正在学习phpunit测试实现,我的问题是,我不知道如何测试if条件不为true的情况,所以它没有定义$view->something语义数组,那么,我该如何嘲笑通过这个PHPUNIT测试?

我应该在一次测试中测试两种场景吗?或者我应该一分为二。。。文档很简单,但找不到任何类似案例的参考资料。

现在我得到一个错误-#case 2的未定义属性测试#2一直失败,或者它显示了与第一个数组Love语义相比的Love语义值,就好像它们应该匹配以通过测试一样?

// this is the function I'm creating the UT.
protected function _doSomeMagicPlease( $view ) {
if($this->config->DoSomeMagicPlease){
$view->somethingSemantic = array(
"Something else semantic" => $this->lsd(),
"Love semantics" => $this->magic()
);
}
}
// assertion - the view->somethingSemantic does not exist in case 2. 
$this->assertEquals($expected , $view->somethingSemantic);
it seems it is comparing both arrays of the data provider:
// this is my data provider:
public function checkDoSomeMagicPleaseDataProvider()
{
return [
[
'message' => 'Case 1',
'configObject' => (object) array(
'values' => (object) array(
'DoSomeMagicPlease'=> 'true'
)
),
'expected' => array(
"Something else semantic" => "12345",
"Love semantics" => "https://www.someurl.com"
),
],
[
'message' => 'Case 2',
'configObject' => (object) array(
'values' => (object) array(
'DoSomeMagicPlease'=> "false"
)
),
'expected' => array(
"Something else semantic" => "12345",
"Love semantics" => "false"
)
]
];
}

我应该改变我的断言吗?任何提示都将不胜感激!!

处理此问题的一个简单方法是确保始终定义somethingSemanticnull或空数组似乎是一个合理的默认值。

public function checkDoSomeMagicPleaseDataProvider()
{
return [
// ...
[
'message'      => 'Case 2',
'configObject' => (object)array(
'values' => (object)array(
'DoSomeMagicPlease' => 'false'
)
),
'expected'     => null
]
];
}

如果你想保持它的原样,把它分成两个单独的测试。您可以检查view对象上是否存在somethingSemantic属性:

public function test_it_should_create_something_semantic_when_magic_is_enabled()
{
// ...

self::assertEquals(
[
'Something else semantic' => '12345',
'Love semantics'          => 'https://www.someurl.com'
],
$view->somethingSemantic
);
}
public function test_it_should_not_create_something_semantic_when_magic_is_enabled()
{
// ...

self::assertObjectNotHasAttribute('somethingSemantic', $view);
}

相关内容

最新更新