Is it okay to send Laravel Request object to other functions as parameter? - laravel-5.5

Is it okay to send Request $request object between the functions?
My Request $request object consists of around 20 inputs. At first in 'store' function, I save about 10 inputs. Then I pass this $request object to another function where I save remaining inputs. The purpose behind second function is so that I can use this function for another route if only next 10 fields are to be stored.
I know that the $request object is very large, consuming so much memory. So it is good to send the $request object function to function when considered space complexity and time complexity?
//My Controller
class MyController extends Controller{
public function store(Request $request){
//save 10 inputs
$this->saveTasks($request);
}
public function saveTasks(Request $request){
//save remaining 10 inputs
}
}
// routes/web.php
Route::post('store', 'MyController#store');
Route::post('store_tasks', 'MyController#saveTasks');
Thanks in advance :)

Related

PHPUnit: How to Test a single Function in an Helper file

I would like to test a new function in a helper file.
function isProductionSite() {
return !(bool) preg_match('/admin|development/', request()->getHttpHost());
}
When I call this function in my test function I get my local address. Therefore I tried to mock the request()->getHttpHost.
public function testIsProductionSiteExpectFalse(): void
{
$request = Mockery::mock(Request::class);
$request->shouldReceive('getHttpHost')->once()->andReturn('admin.mydomain.de');
$this->assertFalse(isProductionSite());
}
In the Tets Function $request->getHttpHost() would now output admin.mydomain.de. But getHttpHost() from the function to be tested (isProductionSite()) gives me the correct host.
How can I set the HttpHost in the testcase so that the helper function outputs the manipulated host?
You're mocking an instance of $request but the instance being used by the function under test is not the mock, but presumably a global variable.
Dependencies should always be passed to the helper function. Just add $request as a parameter of isProductionSite.

jest-fetch-mock with classes that perform api query

All the examples of jest and jest-fetch-mock I have come across use functions that perform an API query and return a payload directly from the function call.
In my case, I have a different setup. I have a class that has a property called 'data'. In the class there is a method called "get" which pulls data using fetch API and stores it in the data property. When the method is called, it simply returns true or false based on promise resolve or reject.
I am trying to figure out how to write unit tests for this in this case. My function doesn't return the data fetched; only a boolean value.
So if I use jestSpyOn to mock the class method, how would I set the data property, and then retrieve the result?
In my code, I do something like this (NOT in testing, but in the actual app):
contactStore = new ContactListStore();
// 'all' is a sample param passed
contactStore.get('all').then(res => {
if(res){
...perform action
}
});
As you can see the res argument is only boolean, and if true, then contactStore.data will contain the information retrieved from the server.
So to run a unit test on it, I need to call a mock get, and set a mock data property.
Any ideas how this would be done?
In your mock method, you just need return true.

Symfony2 get service or get container service

i have just implemented my first service in Symfony2.
I noticed that, within a controller method, whether i call the service so
$this->container->get('main.service');
or so
$this->get('main.service');
there is no difference.
I get the service equally with both.
Where are the differences?
There's no difference if you're extending the Base Controller provided by Symfony.
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class YourController extends Controller
If you take a deeper look at the implementation of the Symfony\Bundle\FrameworkBundle\Controller\Controller, you may notice that it provides a get() helper which do exactly the same call as what you did first (getting your service through the container).
So, then,
There's no difference as $this->get('something') simply sencapsulates a call to $this->container->get('something').
Here's the implementation of the get() method you're calling when doing $this->get('main.service');
/**
* Gets a service by id.
*
* #param string $id The service id
*
* #return object The service
*/
public function get($id)
{
return $this->container->get($id);
}

How to unit test if function has been called? Dependency injection?

I'm creating a simple RESTful API in PHP for practice. I'm trying to write as testable code as possible. After reading many tutorials and watching a few videos, I still feel at a loss on how to design this.
Basically, I have set up a Router class. It is responsible for mapping url paths to controller methods.
It's easy to test the router's state after adding a route.
But, how do I test if the proper class->function(params) has been called in respond()?
I'm using PHPUnit, and I've been reading about mocks. I don't know how to use them in this context.
Currently, respond() parses a given path and request method, and calls the mapped method.
Here is my current design:
private $routes;
public function __construct() {
$routes = array();
}
/**
* Gets all current routes
*/
public function getRoutes();
/**
* Sets all routes
*/
public function setRoutes($routes);
/**
* Routes GET request
*/
public function get();
/**
* Routes POST request
*/
public function post();
/**
* Routes PUT request
*/
public function put();
/**
* Routes DELETE request
*/
public function delete();
/**
* Sets up default paths for a given resource
*/
public function resource();
/**
* Respond to request
* #return mixed JSON of resource data
*/
public function respond($req_method, $request);
/**
* Returns mapped call info from request method and path
* #return mixed An array of the call and params
*/
private function parse($req_method, $request);
As the comments have indicated, this would be a good use of a spy or mocking system. PHPunit has some ability to create and test for mocks, but I prefer to use a different library - Mockery.
This code will create a class and test that that when you call average(), it's called three times, and then also returns a given value.
Your code would call respond(), after setting up a mock that shouldReceive('get')->once() (for example). The m::close in the teardown will verify that get() was called, just one time, and would fail the test if it was not.
<?php
use \Mockery as m;
class TemperatureTest extends PHPUnit_Framework_TestCase
{
public function tearDown()
{
m::close();
}
public function testGetsAverageTemperatureFromThreeServiceReadings()
{
$service = m::mock('service');
$service->shouldReceive('readTemp')->times(3)->andReturn(10, 12, 14);
$temperature = new Temperature($service);
$this->assertEquals(12, $temperature->average());
}
}
Since you would be calling a real class to do work in respond(), you will need a 'partial mock'
$restful= m::mock('RestfulController[get]');
$restful->shouldReceive('get')->once();

moq- why can't operate function with default parameter

I am trying to make a unit test on a very simple interface.
my interface is:
public interface Interface1
{
string retStr(string dd);
string retStr2(string dd,string fff);
}
this is the mock:
var myMoq = new Mock<Interface1>();
myMoq.Setup(d => d.retStr("David")).Returns("retStr");
Console.WriteLine(myMoq.Object.retStr("fdf").ToString());
I GOT runtime error: Object reference not set to an instance of an object.
and another error on implementation:
myMoq.Setup(d => d.retStr2(It.Is<string>(e=>e=="qqq"), It.IsAny<string>())).Returns("2 parameters");
Console.WriteLine(myMoq.Object.retStr2("fdf","wewew").ToString());
Why is it?
In your setup, you are setting the expectation that a specific string will be passed in (for example "David").
You are telling Moq, "Pass back "retStr" if the method invoked with the string "David", otherwise return a default value (for string, null). Because of this, when you do a .ToString() on the result of the method, the object is null.
The same thing applies to the second example.
In order to make a more general return value, use It.IsAny<string>() when setting up a method. Or, do as you expect in the test and send in "David" when you call the method.