Is a Cache mock called more than once when browser-testing? - unit-testing

I'm trying to cover the following:
I'm using the following test code:
public function test_it_deletes_a_patient()
{
// ...
$cacheKey = vsprintf('%s.%s', [$this->doctorUser->id, 'backoffice.stats.patientsTotalCount']);
Cache::shouldReceive('has')->with($cacheKey)->once()->andReturn(false);
Cache::shouldReceive('increment')->with($cacheKey, -1)->once()->andReturn(true);
$response = $this->json('DELETE', route('patients.destroy', $this->patient), ['confirmation' => 'ELIMINAR']);
// ...
}
That triggers the following controller code:
public function destroy(Patient $patient, Request $request)
{
$this->authorize('delete', $patient);
$confirmation = $request->get('confirmation');
if ($confirmation != 'ELIMINAR') {
return response()->json(['success' => false]);
}
logger()->info("Deleting Patient Profile PATIENT_ID:[{$patient->id}]");
$patient->delete();
$this->updatePatientsCount(-1);
return response()->json(['success' => true]);
}
protected function updatePatientsCount($amount = 1)
{
$key = vsprintf('%s.%s', [auth()->user()->id, 'backoffice.stats.patientsTotalCount']);
if (Cache::has($key)) { // I want to mock for testing this
Cache::increment($key, $amount); // I want to mock for testing this
}
}
After test run I get:
alariva#trinsic:~/fimedi$ t --filter=test_it_deletes_a_patient
PHPUnit 7.3.1 by Sebastian Bergmann and contributors.
F 1 / 1 (100%)
Time: 6.53 seconds, Memory: 26.00MB
There was 1 failure:
1) Tests\Browser\Backoffice\PatientsTest::test_it_deletes_a_patient
Unable to find JSON fragment
["success":true]
within
[{"exception":"Mockery\\Exception\\NoMatchingExpectationException","file":"\/home\/alariva\/fimedi\/vendor\/mockery\/mockery\/library\/Mockery\/ExpectationDirector.php","line":92,"message":"No matching handler found for Mockery_0_Illuminate_Cache_CacheManager::has('2056e535e689ab723b3f44831b488f05f7fb8b90'). Either the method was unexpected or its arguments matched no expected argument list for this method\n\n","trace":[{"class":"App\\Http\\Middleware\\Language","file":"\/home\/alariva\/fimedi\/vendor\/laravel\/framework\/src\/Illuminate\/Pipeline\/Pipeline.php","function":"handle","line":151,"type":"->"},{"class":"Barryvdh\\Debugbar\\Middleware\\InjectDebugbar","file":"\/home\/alariva\/fimedi\/vendor\/laravel\/framework\/src\/Illuminate\/Pipeline\/Pipeline.php","function":"handle","line":151,"type":"->"},{"class":"Illuminate\\Auth\\Middleware\\Authenticate","file":"\/home\/alariva\/fimedi\/vendor\/laravel\/framework\/src\/Illuminate\/Pipeline\/Pipeline.php","function":"handle","line":151,"type":"->"},{"class":"Illuminate\\Cookie\\Middleware\\AddQueuedCookiesToResponse","file":"\/home\/alariva\/fimedi\/vendor\/laravel\/framework\/src\/Illuminate\/Pipeline\/Pipeline.php","function":"handle","line":151,"type":"->"},{"class":"Illuminate\\Cookie\\Middleware\\EncryptCookies","file":"\/home\/alariva\/fimedi\/vendor\/laravel\/framework\/src\/Illuminate\/Pipeline\/Pipeline.php","function":"handle","line":151,"type":"->"},{"class":"Il
What I interpret after a couple of tests, is that it looks like once I mock Cache it is being called by some middlewares before reaching the tested block, so since those called methods are not mocked, the test fails because it does not know what to answer for those middleware calls.
Imagine I could successfully mock all the calls before getting to the tested codeblock, I would be able to make it reach. But that's not the way to go over it.
How can I mock Cache and avoid failure due to previous Cache calls that I'm not testing?
EDIT: I realized after getting to a solution that this is a misleading question. My actual need was:
How can I successfully cover those lines?
Sidenote: if I try to disable middlewares ($this->withoutMiddleware();) I get an AccessDeniedHttpException
alariva#trinsic:~/fimedi$ t --filter=test_it_deletes_a_patient
PHPUnit 7.3.1 by Sebastian Bergmann and contributors.
F 1 / 1 (100%)
Time: 12.95 seconds, Memory: 24.00MB
There was 1 failure:
1) Tests\Browser\Backoffice\PatientsTest::test_it_deletes_a_patient
Unable to find JSON fragment
["success":true]
within
[{"exception":"Symfony\\Component\\HttpKernel\\Exception\\AccessDeniedHttpException","file":"\/home\/alariva\/fimedi\/vendor\/laravel\/framework\/src\/Illuminate\/Foundation\/Exceptions\/Handler.php","line":201,"message":"This action is unauthorized.","trace":[{"class":"App\\Exceptions\\Handler","file":"\/home\/alariva\/fimedi\/vendor\/laravel\/framework\/src\/Illuminate\/Routing\/Pipeline.php","function":"render","line":83,"type":"->"},{"class":"Illuminate\\Foundation\\Exceptions\\Handler","file":"\/home\/alariva\/fimedi\/app\/Exceptions\/Handler.php","function":"render","line":65,"type":"->"},{"class":"Illuminate\\Foundation\\Exceptions\\Handler","file":
Maybe I can cherry-pick middlewares to disable?

I managed to cover the controller's method by encapsulating the custom Cache operation into a macro, so as to get the benefits of spliting into code units.
I moved my code into a macro (in the boot() of a service provider):
Cache::macro('incrementExisting', function($key, $amount) {
if (Cache::has($key)) {
Cache::increment($key, $amount);
}
return $this;
});
I refactored to use the macro
protected function updatePatientsCount($amount = 1)
{
$key = vsprintf('%s.%s', [auth()->user()->id, 'backoffice.stats.patientsTotalCount']);
Cache::incrementExisting($key, $amount);
}
I could get the desired coverage while I can still test the refactored code with unit testing.
Update I
Regarding the concern of handling many calls that are not mocked, I just learned from Adam Wathan that there exists shouldIgnoreMissing() and that would allow to use the Mocking approach for this case.
Update II
Write your tests first. When doing so it gets easier to avoid hard-to-test code.

Related

How to make a unit test in meteor that adds a document to a collection? Mocking userId

Thank you for your help-
I'd like to know if my app successfully adds a document to the database using a unit test in Meteor. I'm using practicalmeteor:mocha and chai. The issue I'm running into is that I don't know how to mock a this.userId, it keeps telling me I'm not logged in.
it('inserts the draft agenda document into the collection', function() {
// TODO: mock document to insert into collection
// TODO: mock userId and Agenda.insert
this.userId = "Not an empty string";
console.log("before spec, changing this.userId: " + this.userId) //is "Not an empty string"
Meteor.call('createAgenda', mockAgenda, function(res) {
console.log("callback with response: " + res); //You're not logged-in. [not-logged-in]
console.log("this.userId: " + this.userId) //is undefined
}
}
see https://docs.meteor.com/api/methods.html#DDPCommon-MethodInvocation-userId for more info on user id
test runner fails to import files in client directory
MochaRunner.runServerTests: failures: 1 when meteor methods are called
I have to call the server side meteor methods that have been declared in the testing context as if I am on the client, but I can't import the client files or operate as if I'm a client
MochaRunner.runServerTests: Starting server side tests with run id R7ocZh3Qva3rExTL9 runs basically every time
This seems useful but hasn't worked for me yet https://forums.meteor.com/t/testing-methods-which-use-this-userid/2292/8
Thank you for your help, any code examples would be great.
Remarks
I wanted to post a comment but do not have enough reputation. So here are some remarks. Since you are testing on the server, you can call a Meteor method without a callback. This will result in a synchronous execution and simplify your test. Otherwise you will have to let the test know it is finished by calling the done function in your callback, see mocha docs.
Using mdg:validated-method
You can call a valited method and provide the context in which they execute using the _execute function. Below is an example taken from the todos sample project. For more examples you can take a look at their Lists and Todos tests.
it('makes a list private and updates the todos', function() {
// Check initial state is public
assert.isFalse(Lists.findOne(listId).isPrivate());
// Set up method arguments and context
const methodInvocation = {
userId
};
const args = {
listId
};
// Making the list private adds userId to the todo
makePrivate._execute(methodInvocation, args);
assertListAndTodoArePrivate();
// Making the list public removes it
makePublic._execute(methodInvocation, args);
assert.isUndefined(Todos.findOne(todoId).userId);
assert.isTrue(Todos.findOne(todoId).editableBy(userId));
});
Using standard methods
Another possiblity would be to bind the standard call function to the correct context. Note that this is just a thought and not tested.
var methodInvocation = {
userId: "some user id"
};
Meteor.call.bind(methodInvocation)('createAgenda', mockAgenda);

Grails : Spock : Unit testing GORM domain class hooks

Usually I was ending up writing test cases for a Domain by writing them for constraints and any custom methods(created by us in application) as we know we shouldn't test obvious.
But the time we started using coverage plugin, we found that our domains line of code is not fully covered which was due to gorm hooks(onInsert, beforeUpdate) that we never wrote test cases for.
Is there a way we can test these. One possible way that seems obvious but not suitable is to call another method(containing all code which was earlier in hooks) within these hooks and test that method only and be carefree for hooks.
Any solutions...
Edit
Sample code in domain that I want to unit-test:
class TestDomain{
String activationDate
def beforeInsert() {
this.activationDate = (this.activationDate) ?: new Date()//first login date would come here though
encodePassword()
}
}
How can I unit-test beforeInsert or I would end up writing integration test case?
Perhaps a unit test like:
import grails.test.mixin.TestFor
#TestFor(TestDomain)
class TestDomainSpec extends Specification {
def "test beforeSave"() {
given:
mockForConstraintsTests(TestDomain)
when:
def testDomain = new TestDomain().save(flush:true)
then:
testDomain.activationDate != null
}
}

Laravel 5 Cannot Mock View

I'm trying to write a really basic test for one of my controllers
/**
* THIS IS MY CONTROLLER. $this->badge is a repository
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('badges.index')->with([
'badges' => $badges = $this->badge->all()
]);
}
I'm using repositories which return Eloquent collections. My basic test is as follows:
public function testItShowsAllBadges()
{
// Arrange
//DISABLE AUTH MIDDLEWARE ON THIS ROUTE
$this->withoutMiddleware();
// MOCK THE REPO
$this->badge->shouldReceive('all')->andReturn(new Illuminate\Support\Collection);
// Act
$response = $this->action('GET', 'BadgeController#index');
// Assert
$this->assertResponseOk();
$this->assertInstanceOf('Illuminate\Support\Collection', $response->original->getData()['badges']);
$this->assertViewHas('badges');
}
This test fails with a message 'trying to get property of non-object'. This is because I do Auth::user()->something in the view.
So I need to mock the view but I don't know how. Can someone advise?
Other SO answers do not seem to work and just result in Exceptions being thrown in the test about methods not existing on the Mock. I have tried for example:
View::shouldReceive('make')
->once()
->andReturn(\Mockery::self())
Adding this before I call the route results in a 500 error 'Method Mockery_1_Illuminate_View_Factory::with() does not exist on this mock object'. I tried adding in
->shouldReceive('with')
->once()
->andReturn(\Mockery::self());
However this results in an Exception stating that getData() does not exist on this Mock Object. Even removing that assertion, assertViewHas('badges') fails saying the response was not a view.
Also I haven't understood if View::shouldReceive... is part of Arrange or Assert phase of the test?My understanding it is part of the arrange and should go before the $this->action(....)

How to mock a CakePHP behavior for unit testing

I've just started with unit testing in CakePHP (yay!) and ran into the following challenge. Hope somebody can help me :-)
Situation
My model uses a Behavior to send changes to an API after saving it locally. I would like to fake all calls made to the API during the test (those will be tested seperately) to save load on the API server, and more important, not actually save the changes :-)
I'm using CakePHP 2.4.1.
What I've tried
Read the docs. The manual shows how to do this for Components and Helpers but not for Behaviors.
Google. What I've found:
A Google Group post which says it simply "isn't possible". I don't take no for an answer.
An article explaining how to mock an object. Comes pretty close.
The code from the article reads:
$provider = $this->getMock('OurProvider', array('getInfo'));
$provider->expects($this->any())
->method('getInfo')
->will($this->returnValue('200'));
It might be the wrong direction, but I think that might be a good start.
What I want
Effectively: A snippet of code to demo how to mock a behavior in a CakePHP Model for unit testing purposes.
Maybe this question will result in an addition of the CakePHP manual too as an added bonus, since I feel it's missing in there.
Thanks in advance for the effort!
Update (2013-11-07)
I've found this related question, which should answer this question (partly). No need to mock up the API, instead I can create a Behavior test that the model will use.
I'm trying to figure out what that BehaviorTest should look like.
Use the class registry
As with many classes, behaviors are added to the class registry using the class name as the key, and for subsequent requests for the same object loaded from the classregistry. Therefore, the way to mock a behavior is simply to put it in the class registry before using it.
Full Example:
<?php
App::uses('AppModel', 'Model');
class Example extends AppModel {
}
class TestBehavior extends ModelBehavior {
public function foo() {
throw new \Exception('Real method called');
}
}
class BehaviorExampleTest extends CakeTestCase {
/**
* testNormalBehavior
*
* #expectedException Exception
* #expectedExceptionMessage Real method called
* #return void
*/
public function testNormalBehavior() {
$model = ClassRegistry::init('Example');
$model->Behaviors->attach('Test');
$this->assertInstanceOf('TestBehavior', $model->Behaviors->Test);
$this->assertSame('TestBehavior', get_class($model->Behaviors->Test));
$this->assertSame(['foo' => ['Test', 'foo']], $model->Behaviors->methods());
$model->foo();
}
public function testMockedBehavior() {
$mockedBehavior = $this->getMock('TestBehavior', ['foo', 'bar']);
ClassRegistry::addObject('TestBehavior', $mockedBehavior);
$model = ClassRegistry::init('Example');
$model->Behaviors->attach('Test');
$this->assertInstanceOf('TestBehavior', $model->Behaviors->Test);
$this->assertNotSame('TestBehavior', get_class($model->Behaviors->Test));
$expected = [
'foo' => ['Test', 'foo'],
'bar' => ['Test', 'bar'],
'expects' => ['Test', 'expects'], // noise, due to being a mock
'staticExpects' => ['Test', 'staticExpects'], // noise, due to being a mock
];
$this->assertSame($expected, $model->Behaviors->methods());
$model->foo(); // no exception thrown
$mockedBehavior
->expects($this->once())
->method('bar')
->will($this->returnValue('something special'));
$return = $model->bar();
$this->assertSame('something special', $return);
}
}

Grails 1.3.7 to Grails 2.2 upgrade, Unit tests now fail with missing GORM methods

I am in the middle of upgrading an app from Grails 1.3.7 to 2.2
So far, its been relatively painless and straight forward.
Until we started running the unit tests.
Under 1.3.7, all the tests passed.
Under 2.2, about half are now failing. The tests haven't changed, they are still the old style mockDomain...
What is most concerning to me is that basic gorm features are missing on some of the domain classes.
Things like .list and .get
Failure: testList_NoMaxSpecified_10Shown(com.litle.bldvwr.StreamControllerTests)
| groovy.lang.MissingMethodException: No signature of method: >com.litle.bldvwr.Stream.list() is applicable for argument types: () values: []
Possible solutions: list(), list(), list(), list(java.lang.Object), list(java.util.Map), >list(java.lang.Object)
and
Failure: >testAddFailureOutputToHappyPathWithIntegrationFailure(com.litle.bldvwr.LogParserServiceTests)
| groovy.lang.MissingMethodException: No signature of method: >com.litle.bldvwr.Result.get() is applicable for argument types: () values: []
Possible solutions: get(java.io.Serializable), get(java.lang.Object), >get(java.io.Serializable), getId(), grep(), grep(java.lang.Object)
The general pattern of for this type of failure is:
mockDomain(Phase, [new Phase(id:1, name: 'xxx')])
mockDomain(Result, [new Result(id:1, phase: Phase.get(1), failureOutput:"")])
logParserService.addFailureOutputTo(Result.get(1))
And it is that last get that is causing the no signature error.
While we intend to start using the new Unit Test functionality, I was hoping to avoid having to rewrite the 500+ current tests.
Thoughts, ideas?
-Clark
Using the new #Mock() annotation in your test for the domain objects will inject all the expected mock GORM methods, and you can even just save() your domain objects instead of providing the list in mockDomain() call.
#Mock([Result, Nightly])
class MyTests {
void testSomething() {
def night = new Nightly( name:'nightly1')
night.id=1
night.save(validate: false)
assert Nightly.get(1).name == 'nightly1'
assert Result.count() == 0
new Result(status: Constants.SUCCESS, type: Constants.INTEGRATION,
nightly: Nightly.get(1)).save(validate: false)
assert Result.count() == 1
assert Result.findByStatus(Constants.SUCCESS) != null // yay dynamic finders!
}
}
http://grails.org/doc/latest/guide/testing.html#unitTestingDomains
You'll have to update all your tests to the new ways, but it's much nicer that the old 1.3 ways.
So here is what we found.
With 1.3, you could do:
{
mockDomain(Nightly, [new Nightly(id: 7)])
mockDomain(Result, [
new Result(status: Constants.SUCCESS,
type: Constants.INTEGRATION, nightly: Nightly.get(7))
])
service.callSomething(results, Nightly.get(7))
assert result==Nightly.get(7).property
And it would work just fine. You whoul have a Mock domain object with and id of 7, and the get would work just fine.
Since then, something changed, and you can no longer set the id has part of the create.
What you need to do is this:
night = new Nightly( name:'nightly1')
night.id=1
mockDomain(Nightly, [night])
mockDomain(Result, [
new Result(status: Constants.SUCCESS, type: Constants.INTEGRATION, nightly: Nightly.get(1))
])
and that mostly sets up the mocks correctly.
The issue we ran into next was that outside of the mockDomain call, Nightly.get() would not work.
So now we need to save the "mocked" domains in local variables in order to do post action comparison and checks.
Not a completely horrible solution, but less elegant than we were hoping for.