使用PHPUnit在Symfony2中模拟SecurityContext

时间:2016-09-12 19:37:41

标签: php symfony phpunit

这些是我的嘲笑:

#!/bin/bash
# 160912
# match filenames char-cases on target path as in server path
# usage : $0 targetDir serverDir

TARGET_PATH=$1

MAKE_EQUAL()
{
  while read server_name
  do
      new_target_name=$(grep -i ^$server_name\$ targetList.txt)
      if [ ! -z "$new_target_name" ] && [ "$server_name" != "$new_target_name" ] ; then
        echo "  $new_target_name --> $server_name"
        (cd $TARGET_PATH;mv $new_target_name $server_name)
      fi
  done < serverList.txt
}

if [ ! -d "$1" -o ! -d "$2" ] ; then
    echo "Paths not found!"
    exit 0
fi

# Change directories changing depth level until is the last directory level
DIRLEVEL=1 
LASTLEVEL=0
(cd $2;find . -maxdepth $DIRLEVEL -type d) > serverList.txt
while [ "$LASTLEVEL" == "0" ]
  do
    echo "Match directory level $DIRLEVEL:"
    (cd $1;find . -maxdepth $DIRLEVEL -type d) > targetList.txt
    MAKE_EQUAL
    DIRLEVEL=`expr $DIRLEVEL + 1` 
    (cd $2;find . -maxdepth $DIRLEVEL -type d) > nextServerList.txt
    diff nextServerList.txt serverList.txt > /dev/null
    if [ $? -eq 0 ] ; then
      LASTLEVEL=1
    else
      mv nextServerList.txt serverList.txt
    fi
  done

echo "Match files:"

(cd $1;find . -type f) > targetList.txt
(cd $2;find . -type f) > serverList.txt
MAKE_EQUAL

echo "Done!"

这是我正在测试的类的代码:

它抛出错误:

$this->user->method('getCustomerId')
           ->willReturn($this->customerId);
$this->userToken->method('getUser')
                ->willReturn($this->user);
$this->securityContext->method('getToken')
                      ->willReturn($this->userToken);
$this->securityContext->expects($this->once())
                      ->method('isGranted')
                      ->will($this->returnValue(true));

我不知道该做什么,我虽然嘲笑拦截了对方法的调用并返回了我想要的任何内容。但在这种情况下似乎isGranted方法不是模拟

2 个答案:

答案 0 :(得分:0)

尝试使用willReturn代替will并添加with

所以试试这个:

$this->securityContext->expects($this->once())
                      ->method('isGranted')
                      ->with('IS_AUTHENTICATED_FULLY')
                      ->willReturn(true);

而不是:

$this->securityContext->expects($this->once())
                      ->method('isGranted')
                      ->will($this->returnValue(true));

希望这个帮助

答案 1 :(得分:0)

我发现问题是isGranted方法是最终的,因此模拟是不可能的,问题的解决方法是模拟SecurityContext的所有属性,以便在调用方法时它返回我想要的输出,而不是用模拟方法拦截调用。