【发布时间】:2017-10-26 01:04:59
【问题描述】:
我需要一些帮助我想编写一个关于控制器方法的单元测试,我已经搜索了示例并测试了很多方法,但它们都没有奏效:
这是我的控制器:
class ComputerController extends Controller
{
/**
* @Route("/list-computers.html", name="back_computer_list")
* @return RedirectResponse|Response
*/
function listComputerAction()
{
$ad = $this->get("ldap_service");
$computers = $ad->getAllComputer();
return $this->render('BackBundle:Computer:list.html.twig', array(
"computers" => $computers,
));
}
我试过用这样的模拟来测试它:
class ComputerController extends Controller
{
/**
* @var EngineInterface
*/
private $templating;
public function setTemplating($templating)
{
$this->templating = $templating;
}
and i have created a test method:
class ComputerControllerTest extends TestCase {
public function testlistComputerAction(){
$templating = $this->getMockBuilder('BackBundle\Controller\ComputerController')->getMock();
$computers = [1,2];
$templating->expects($this->once())
->method('render')
->with('BackBundle:Computer:list.html.twig', array(
"computers" => $computers))
->will($this->returnValue( $computers));
$controller = new ComputerController();
$controller->setTemplating($templating);
$this->assertEquals('success', $controller->listComputerAction());
}
当我开始执行 phpunit 时,我有这个警告“尝试配置无法配置的方法“渲染”,因为它不存在、尚未指定、是最终的或静态的”
如果有人对此有任何想法,我将不胜感激
【问题讨论】:
-
您找不到太多关于单元测试控制器操作的信息的原因是,通常不需要对控制器操作进行单元测试。为您的 ldap 服务编写单元测试。如果您真的有测试控制器接线的冲动,请根据文档编写功能测试。
-
感谢您的回复,我一开始也是这么想的,因为我没有找到太多关于此的信息,所以知道我会尝试测试 ldapservice 方法,即使我认为没有关于这方面的很多信息,但我会尝试
-
请记住,您的 ldap 服务可能使用某种 ldap 库,并且不需要测试该库。您只想测试您自己的 ldap 服务代码是否调用了正确的东西。
-
请提出另一个问题,例如我无法测试的 ldap 库是什么意思ldap 函数,那么我该如何测试它们呢?
-
@cerad,请在控制器中测试哪些方法有用,因为我有(以下方法:addaction、edit、remove,我不知道是否有实用程序来测试它们或者我该怎么做?)