我是laravel的新手,想对laravel 5.6中的控制器进行单元测试 这是我的控制器。
class NewOrdersController extends Controller
{
protected $newOrders;
public function __construct(NewOrderRepositoryInterface $newOrders)
{
$this->newOrders = $newOrders;
}
public function orderList(){
$orders = $this->newOrders->getNewOrders();
if(count($orders) == 0){
return 0;
}
else{
return 1;
}
}
}
我的测试看起来像这样。如何编写控制器的单元测试?
class NewOrderTest extends TestCase
{
public function tearDown()
{
Mockery::close();
}
/** @test */
public function testMock(){
$neworders = Mockery::mock('NewOrderRepositoryInterface');
$neworders->shouldReceive('getNewOrders')
->once()
->andReturn(0);
$orders = new newOrder($this->neworders);
$this->assertEquals(0,$orders->orderList());
}
}
答案 0 :(得分:0)
模拟是要替换您已经在使用的模拟,您绝对不能断言或测试一种模拟。通常,您只需要制作mockX()
方法,该方法就可以将模拟绑定到您要替换的类。另外,您在接口上有一个有趣的绑定,只需将类路径用作绑定即可,而且更容易,您可以从::class
派生它。将模拟设置为实例后,该模拟将自动加载到类中。
public function mockOrderRepository(){
$neworders = Mockery::mock(NewOrderRepositoryInterface::class);
$neworders->shouldReceive('getNewOrders')
->once()
->andReturn(0);
// bind the mocked class to the dependency injected version.
$this->app->instance(NewOrderRepositoryInterface::class, $neworders);
}
我认为它是一个JsonApi,通常是:)否则模拟您的存储库并调用端点,您可以使用assertJson
来断言数据
/** @test */
public function testOrderList()
{
$this->mockOrderRepository;
$response = $this->json('GET', 'v1/your/api/endpoint');
$response->assertStatus(200);
$response->assertJson(1);
}