我最近开始进行单元测试,我想知道我是否应该编写 100% 代码覆盖率的单元测试?
当我最终编写的单元测试代码多于生产代码时,这似乎是徒劳的。
我正在编写一个 PHP Codeigniter 项目,有时我似乎编写了很多代码只是为了测试一个小函数。
例如这个单元测试
public function testLogin(){
//setup
$this->CI->load->library("form_validation");
$this->realFormValidation=new $this->CI->form_validation;
$this->CI->form_validation=$this->getMock("CI_Form_validation");
$this->realAuth=new $this->CI->auth;
$this->CI->auth=$this->getMock("Auth",array("logIn"));
$this->CI->auth->expects($this->once())
->method("logIn")
->will($this->returnValue(TRUE));
//test
$this->CI->form_validation->expects($this->once())
->method("run")
->will($this->returnValue(TRUE));
$_POST["login"]=TRUE;
$this->CI->login();
$out = $this->CI->output->get_headers();
//check new header ends with dashboard
$this->assertStringEndsWith("dashboard",$out[0][0]);
//tear down
$this->CI->form_validation=$this->realFormValidation;
$this->CI->auth=$this->realAuth;
}
public function badLoginProvider(){
return array(
array(FALSE,FALSE),
array(TRUE,FALSE)
);
}
/**
* @dataProvider badLoginProvider
*/
public function testBadLogin($formSubmitted,$validationResult){
//setup
$this->CI->load->library("form_validation");
$this->realFormValidation=new $this->CI->form_validation;
$this->CI->form_validation=$this->getMock("CI_Form_validation");
//test
$this->CI->form_validation->expects($this->any())
->method("run")
->will($this->returnValue($validationResult));
$_POST["login"]=$formSubmitted;
$this->CI->login();
//check it went to the login page
$out …Run Code Online (Sandbox Code Playgroud) 我有一个类似这样的功能:
public function getSomeInfo($id){
$date_start=new DateTime();
$day_of_week=$date_start->format("N");
$date_start=$date_start->sub(new DateInterval("P".$day_of_week."D"));
$date_end=new $date_start;
$date_end=$date_end->add(new DateInterval("P5D"));
$date_start=$date_start->format("Y-m-d");
$date_end=$date_end->format("Y-m-d");
$sql="SELECT * FROM `table`
WHERE `table`.`id`=$id
AND `session`.`date`>'$date_start'
AND `session`.`date`<='$date_end'";
$this->db->query($sql);
}
Run Code Online (Sandbox Code Playgroud)
它返回当前周的数据集,基本上从具有上周一和本周日之间的日期的表中选择记录.
我希望能够对此进行单元测试,但在启动DateTime构造函数时我不知道如何执行此操作.这将是本周但实际上用于测试目的我只想在测试数据集中有一周的数据,所以我真的希望测试DateTime每次都是相同的日期.
基本上我怎么能每次将DateTime("now")设置为相同的模拟日期.我正在使用PHP,Codeigniter和PHPUnit/CIUnit(隐含在标签中).