我正在尝试将一些现有的测试用例添加到预先存在的项目中 这是API类
<?php
namespace MyApp\Api;
use MyApp\ApiBase;
use MyApp\Ethereum as Eth;
use PHPUnit\Runner\Exception;
/**
* Class Ethereum
* @package MyApp\Api
*/
class Ethereum extends ApiBase {
/**
* Function to get balances
* @param array $addresses
* @param string $tag
* @return array
*/
public function getBalances(array $addresses, string $tag = 'latest') {
$data = [];
foreach ($addresses as $addr) {
// validate address
if (!Eth::validateAddress($addr)) {
continue;
}
}
return $data;
}
}
服务类
<?php
namespace MyApp;
use MyApp\Ethereum\GethIpc;
use MyApp\Ethereum\GethWebsocket;
use PHPUnit\Runner\Exception;
/**
* Class Ethereum
* @package MyApp
*/
class Ethereum {
public static $subscriptions = [];
/**
* Ethereum constructor.
*/
public function __construct() {
$this->connection = new GethWebsocket();
$connect = $this->connection->connect();
}
/**
* Function to validate an address
* @param string $address
* @return bool
*/
public static function validateAddress(string $address) {
return preg_match("/^(0x)?[0-9a-fA-F]{40}$/", $address) !== 0;
}
}
我的考试班
<?php
declare(strict_types=1);
namespace MyApp\Test;
use MyApp\Api\Ethereum;
use MyApp\Ethereum as Eth;
use PHPUnit\Framework\TestCase;
use PHPUnit\Runner\Exception;
use Mockery;
use Mockery\Adapter\Phpunit\MockeryTestCase;
/**
* @covers MyApp\Api\Ethereum
*/
final class EthereumTest extends MockeryTestCase {
protected $ethereumApi;
protected $ethereum_address;
//Setup method called before every method
protected function setUp(): void {
$this->ethereumApi = new Ethereum();
$this->ethereum_address = '0x0000000000000000000000000000000' . rand(100000000, 999999999);
//Mockery::globalHelpers();
//$mock = mock(MyApp\Ethereum::class);
}
public function testGetBalances_ValidEthereumAddress(): void {
$mockEthereumService = Mockery::mock("Eth");
$mockEthereumService->shouldReceive('validateAddress')->once()->with($this->ethereum_address)->andReturn(true);
//$mockEthereumService->shouldReceive('msg')->once()->with($this->ethereum_address)->andReturn(true);
$addresses = [$this->ethereum_address];
$result = $this->ethereumApi->getBalances($addresses);
$this->assertNotEmpty($result);
}
public function tearDown()
{
Mockery::close();
}
}
每次我运行测试类时 - 模拟都不起作用,并且正在调用实际的服务类方法
有人可以提供有关如何让这个模拟示例正常工作的帮助吗?
答案 0 :(得分:1)
自己没有使用Mockery的经验,但在查看文档后
我假设您需要使用&#34;重载&#34;前缀和完整的类名,并从测试用例中删除MyApp \ Ethereum的use-statement。