Error when trying to mock CakePHP 3 component - unit-testing

I am trying to mock a CakePHP 3 component which checks if the user is allowed to view the page or not.
I tried this:
$authComponent = $this->getMockBuilder(App\Controller\Component\AuthorizationComponent::class)
->getMock();
$authComponent
->method('isAuthorized')
->willReturn($this->returnValue(true));
However, when running the test, it says:
Trying to configure method "isAuthorized" which cannot be configured because it does not exist, has not been specified, is final, or is static
Most probably I wrongly created the mock. Can anyone tell me how to do it correctly?

Specify mocked methods with setMethods() before getMock():
$authComponent = $this
->getMockBuilder(App\Controller\Component\AuthorizationComponent::class)
->setMethods(['isAuthorized'])
->getMock();

Related

How to mock parameterized method in codeception framework

I have one parameterized method which accept string parameter and returns data upon passed param. I am using codeception framework for writing unit testing for php-zend project.
Method: getDataByView($view) $view can be default, all.
So I want mock this method such way it behave & return result based on passed params. I didnt get way in codeception framework so used phpunit code for that. But getting problems in that.
$map = array(
array('default', $default),
array('all', $all)
);
$mock = $this->getMockBuilder('ViewTable')
->setMethods(['getDataByView'])
->disableOriginalConstructor()
->getMock();
$mock->expects($this->any())
->method('getDataByView')
->will($this->returnValueMap($map));
Actually this code work as per my expectation. Since I am using setMethods() it calls the ViewTable class constructor. If I dont use setMethods then It doesn't call constructor.
Problems:
I want to mock only one method of class, so I have used
setMethods() but it calls mock class constructor. I dont want that.
How can it be solved in phpunit.
How to mock parameterized method in codeception framework.

How to access a service in an ember acceptance test

Running ember 1.13.6 and ember-cli
I have an ember component which I am trying to acceptance test. It's state is very closely tied to the state of a service within my app and so I would like to directly access that service and change its properties from within my acceptance test.
I have been trying things along the lines of
this.application.__container__.lookup['service:side-bar'])
and
this.application.__container__.cache['service:side-bar'])
but I cannot seem to get the actual active service singleton which my app is using and which I could call get() and set() on.
if I try to use Ember.inject.service i get an obscure error Uncaught TypeError: Object.defineProperty called on non-object(…) which sort of sounds like a bug
I'm successfully getting at a service in 1.13.x by doing something like this:
let myService;
module("Acceptance | xxxxx", {
beforeEach() {
this.application = startApp()
myService = this.application.__container__.lookup('service:my-service');
}
});
Your problem might be that you're trying to use array notation (lookup['my-service']) rather than method invocation (lookup('my-service')).
Hope this helps!

how to mock a service method inside a controller for unit testing in grails using JUnit and when to use mockController

Help me understand how to mock a service method inside a controller for unit testing in grails using JUnit
I was trying to write a unit test case for my controller "add".
void testAdd_UT_03(){
......declaring and assigning prerequisites
controller.add() // This is the controller i want to unit test
.... asserting
}
//Controller
def add{
def a =someService.method()
}
Inside controller, some service methods are getting called which in turn is using HQL statements. Since i could not find a way to deal with HQL statements in unit testing, i want to mock the service method itself. ( i want the service method to return the predefined output).
Could someone please explain how to achieve this?
Could you also explain when to use mockController? what we really achieve by mocking something? ( i dint get the real picture as i am entirely new to this)
Thanks in advance,
BK
you can add the following code in the setUp method of your test to mock the service method and when you call the method "add" method on your controller it will call the mocked service method.
def predifinedOutput
void setUp(){
def mockControl = mockFor(YourService)
//params are the parameters passed to the service method
mockControl.demand.yourServiceMethod(0..10) { params->
predifnedOutput = "predifinedOutput"
return "predefined output"
}
controller.yourService = mockControl.createMock()
}

Creating Mock Auth Object in CakePHP Controller Test

Just begun creating some unit tests for my controllers within my CakePHP application however I am completely flummoxed on how I should create a mock for the Auth Component, I have read the CookBook and thought I had it right, but keep getting thrown this error.
Error: Call to a member function allow() on a non-object
Within the controller I am testing there is a beforeFilter function with the following code:
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('create');
}
Within my test I have included the following:
$Leagues = $this->generate('Leagues', array(
'components' => array(
'Auth'
)
));
I have played around with staticExpects() also but it doesn't seem to have much affect (I am also unsure what I need to put in to staticExpects()).
What do you mean by mock? Just stuffing an object with data that you set? The error you're getting is because you need to use
$this->Auth->allow(array('create'))
Found the issue - I have included the Auth component within AppController.php, and not specifically within the controller I was trying to test. By including it with my controller specifically the errors have gone away.

How do I access overloaded properties on a PHPUnit mock object?

When mocking an object with PHPUnit, how do I access properties of the object which are normally accessed via overloading, i.e. via __get()?
For example, in the code below I am testing a Post object. Each Post has an author, which of type Role. Each Role has a Signature property.
$author = $this->getMockBuilder('App_Model_Domain_Role')
->disableOriginalConstructor()
->getMock();
$author->expects($this->any())
->method('__get')
->will($this->returnValue('authorname'));
As you can see I mock the Role object, then configure it to return a string ('authorname') when __get() is called. The Post object which I am testing refers to $this->author->signature. I am expecting it to return 'authorname', but instead the test errors out saying that $signature is an undefined property.
I tried configuring the mock as above but without the method() call (thinking that the expects() and will() calls would then apply to all the mock's methods) but still no success.
Any ideas?
Also, if you know of a good tutorial on PHPUnit mocks I'd be keen to see it - the manual seems to assume prior testing knowledge in this particular area.
I tried the same code as you and it is working for me. My PHPUnit version is 3.7.12. Which version are you using? If you are running a older version you could try upgrading.
public function testMockingMagicGetter()
{
$myMock = $this->getMockBuilder('MyClass')
->disableOriginalConstructor()
->getMock();
$myMock
->expects($this->any())
->method('__get')
->will($this->returnValue('authorname'));
var_dump($myMock->signature);
var_dump($myMock->dummy);
var_dump($myMock->someprop);
}
Results in:
string(10) "authorname"
string(10) "authorname"
string(10) "authorname"