I have a unit test that is failing and I know why but I'm not sure how I should be handling it. I have the following unit test:
new PersistenceSpecification<OrderLine>(session)
.CheckProperty(x => x.Line, "1")
.VerifyTheMappings();
It is failing with the following error:
Test method CanCorrectlyMapOrderLine threw exception:
System.ApplicationException: For property 'Line' expected '1' of type 'System.String' but got '1 ' of type 'System.String'
The reason it's doing this is because x.Line points to a fixed length character field in the database (nchar(10) to be exact) and when it inserts the data it pads it with spaces. Should I be specifying "1" with 9 spaces at the end in my unit tests or should I be trimming this somehow when I read it in? Is there another way to handle this?
I ended up just doing the following with this:
new PersistenceSpecification<OrderLine>(session)
.CheckProperty(x => x.Line, "1".PadRight(10, ' '))
.VerifyTheMappings();
Related
I´m writing automation test for Api Rest.
In the body response to return:
"New Current Account"
I do the follow validation:
Assert.AreEqual("New Current Account", response.Content);
But it doesn´t work the Nunit return failed beacuse:
Message:
Expected string length 19 but was 21. Strings differ at index 0.
Expected: "New Current Account"
But was: ""New Current Account""
-----------^
Can someone help me?
Apparently, the string being returned actually contains quotes.
The proper way to reference this is by escaping the quotes that are part of the data in the string you use for an expected value.
Assert.AreEqual("\"New Current Account\"", response.Content);
This is preferable to using logic to trim off the quotes, because you are comparing actual to expected data without modifying either.
I resolved with follow alternative.
Assert.AreEqual("New Current Account", response.Content.Trim('"'));
I am writing phpUnit tests for our application, So for this I wrote a model factory, after that when I try to run the unit test then I am getting an error like " InvalidArgumentException: Unknown formatter 'publicId' ". I have declared table's all column names in my Model factory. Is it required to mention all columns in the factory?
ModelFactory.php
$factory->define(App\Campaign::class, function (Faker\Generator $faker) {
return [
'public_id' => $faker->publicId,
'client_id' => $faker->clientID,
'name' => $faker->name,
'criteria_age' => $faker->criteriaAge,
'criteria_state' => $faker->criteriaState,
'criteria_postcode' => $faker->criteriaPostcode,
'dncr_required' => $faker->dncrRequired,
'criteria_state' => $faker->criteriaState,
'active' => $faker->active,
'method' => $faker->method,
'server_parameters' => $faker->serverParameters,
'parameter_mapping' => $faker->parameterMapping,
];
});
\tests\Unit\Campaign\CampaignTest.php
namespace Tests\Unit\Campaign;
use App\Campaign;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class CampaignTest extends TestCase
{
use DatabaseTransactions;
public function testCampaignCreation()
{
factory(\App\Campaign::class)->create(['name' => 'tinku']);
$this->seeInDatabase('campaigns', ['name' => 'tinku']);
}
}
after running "phpunit tests/Unit/Campaign/CampaignTest.php" I got this error "InvalidArgumentException: Unknown formatter 'publicId'". I am new to Laravel I know there is a procedure to create factories but I couldn't figure out. Hope someone helps. Thanks.
The formatter is from Faker not Laravel and you can only use Faker formatters Faker ships with.
The error message just tells you that there is no such formatter named publicId. For a list of all Faker formatters please see: https://github.com/fzaninotto/Faker#formatters
If you compare that list with the formatters you've used in your example it becomes more and more obvious that you confused the formatters with some database properties, most likely a translation failure from an existing example? But I think you will know better and this hopefully gives you the information you need to continue setting up your test-case.
I am trying to test a method with PhpUnit and Mockery. In the process of specifying a method should be called with arguments my test fails.
TEST:
$this->eventRepo = \Mockery::mock('Path\To\EventRepository');
$start = Carbon::createFromFormat('Ymd-H-i-s', '20141211-09-21-00');
$end = Carbon::createFromFormat('Ymd-H-i-s', '20141211-09-19-00');
$this->eventRepo
->shouldReceive('findEvent')
->withArgs([
$start,
$end,
'1',
'1234567891'
])
->andReturn($callEvent);
REAL CODE:
$start = Carbon::createFromFormat('Ymd-H-i-s', '20141211-09-20-00');
$end = Carbon::createFromFormat('Ymd-H-i-s', '20141211-09-20-00');
$event = $this->eventRepo->findEvent(
$start->subSeconds(60),
$end->addSeconds(60),
$id,
$number
);
ERROR FROM TEST:
Mockery\Exception\NoMatchingExpectationException: No matching handler found for EventRepo::findEvent(object(Carbon\Carbon), object(Carbon\Carbon), "1", "1234567891"). Either the method was unexpected or its arguments matched no expected argument list for this method
$this->eventRepo is a mocked in the test. The real code runs correctly. After the error displays, it, I guess var_dump()'s a instance of Carbon.
I have no idea what could be causing this. I tried googling it but not knowing what to google made that pretty worthless. Has anyone run into this before?
When using an object in with() or withArgs(), phpunit performs an === check. This means that it'll look for the exact same instance of the class, not just any instance of Carbon.
In this case, it means that findEvent() is receiving an instance of Carbon, but not the exact same instance that you have in the actual code.
I am using CakePHP to develop a website and currently struggling with cookie.
The problem is that when I write cookie with multiple dots,like,
$this->Cookie->write("Figure.1.id",$figureId);
$this->Cookie->write("Figure.1.name",$figureName);`
and then read, cakePHP doesn't return nested array but it returns,
array(
'1.id' => '82',
'1.name' => '1'
)
I expected something like
array(
(int) 1 => array(
'id'=>'82',
'name'=>'1'
)
)
Actually I didn't see the result for the first time when I read after I write them. But from second time, result was like that. Do you know what is going on?
I'm afraid it doesn't look as if multiple dots are supported. If you look at the read() method of the CookieComponent (http://api.cakephp.org/2.4/source-class-CookieComponent.html#256-289), you see this:
277: if (strpos($key, '.') !== false) {
278: $names = explode('.', $key, 2);
279: $key = $names[0];
280: }
and that explode() method is being told to explode the name of your cookie into a maximum of two parts around the dot.
You might be best serializing the data you want to store before saving and then deserializing after reading as shown here: http://abakalidis.blogspot.co.uk/2011/11/cakephp-storing-multi-dimentional.html
I am tring to write test cases for my controller in cakephp, so far i have managed to mock the controller and include the auth component which is used in my controller function. the problem is it seems that i can call staticExpects only once, which means that i can define a return value for only one function call, i don't want that, i need to call staticExpects more than once within the same test case.
Here is a part of my code.
$this->TasksController = $this->generate('Tasks', array(
'components' => array('Session','Auth' => array('User'), ) ));
$this->TasksController->Auth->staticExpects($this->any())
->method('User')
->with('userID')
->will($this->returnValue(224));
$this->TasksController->Auth->staticExpects($this->any())
->method('User')
->with('accID')
->will($this->returnValue('some ID here'));
whenever i do this and run the test it gives me this error
Expectation failed for method name is equal to when invoked zero or more times
Parameter 0 for invocation AuthComponent::user('userID') does not match expected value.
Failed asserting that two strings are equal.
Please help :)
You have to specify when the static methods are called using $this->at(index).
$this->TasksController->Auth->staticExpects($this->at(1))
->method('user')
->with('userID')
->will($this->returnValue(224));
$this->TasksController->Auth->staticExpects($this->at(2))
->method('user')
->with('accID')
->will($this->returnValue('some ID here'));
If you're not sure when they are called try each expectation one by one until the error messages will give you what is called
--- Expected
+++ Actual
## ##
-'userID'
+'accID'
One last thing, the correct method name is "user" and not "User"