Typed property App\Http\Livewire\Roles\EditUserRole::$user_model must not be accessed before initialization - laravel-livewire

// Throw an Error While I have Already Initialized? Please need Help
public function mount()
{
$this->user_model = new User();
$this->userData = $this->user_model->displayUsers();
$this->role_model = $role_model ?? new Role();
$this->roleData = $this->role_model->displayRoles();
}

Try to set default values in your property definitions.
class YouLivewireClass extends Component
{
public string $email = "";
public int $number = 0;
public ?User $user = null;
public function mount()
{
// your logic
}
}
mount() method in Livewire is not the same as a __construct method.
It is called very early but the object is already created and some of the general PHP checks are executed. If you define strict types for the properties that can result in error in Livewire, because they can not fallback to null for the initialisation process.
Here a nice explanation from the Livewire forum: https://forum.laravel-livewire.com/t/1-0-3-typed-property-must-not-be-accessed-before-initialization/320
For anyone wondering why: With the typed properties in 7.4 they have a
state of initialized and uninitialized, instead of the expected
behavior of properties defaulting to a null value if there isn’t one
assigned. In “regular” classes, the properties can maintain an
uninitialized state, and this error is only thrown when you try to
actually access it. Which all makes sense because the point of it all
is to have stricter code.
There’s a few reasons why Livewire (and a portion of Laravel for that
matter) is different than a textbook oop object. First, mount() should
not be thought of as __construct(), and should be thought of closer to
Laravel’s boot() method. The object has been built already, and some
behind the scenes work has been done that makes Livewire work, before
the mount() method is called. mount() is just the first method called
in in the code you provide to Livewire.

Related

Extending mail object in a cfc

I use the mail() object in cfscript. I want to extend that object so I can overwrite the setTo() method. Here is the cfc code I have written.
component extends="com.adobe.coldfusion.mail"
{
public void function setTo(String recipients) {
machineName = createObject("java", "java.net.InetAddress").localhost.getCanonicalHostName();
if (FindNoCase("devcomputer", machinename) == 0)
{
super.setTo(arguments.recipients);
}
else
{
super.setTo(this.getFrom());
}
}
}
When this runs however, I get a message saying the setTo() method does not exist at the line calling super.setTo(). Digging further I looked at the super object and it inherits from java.lang.Class, not com.adobe.coldfusion.email.
What is the proper way to extend ColdFusion's mail object so I can override the setTo() method?
The getters/setters in com.adobe.coldfusion.mail are actually not functions, but accessors. Accessors are automatically generated by ColdFusion based on the properties in the component. Properties are inherited, accessors are not!
The accessors in the mail component do nothing but set/get the value of the property. The equivalent of super.setTo(arguments.recipients); thus is variables.to = arguments.recipients;. The equivalent of this.getTo() is variables.to etc.
Note: Using accessors="true" with the component that extends="com.adobe.coldfusion.mail" does not work with inherited properties either.

Laravel Tests pass to model to View

I'm mocking my repository correctly, but in cases like show() it either returns null so the view ends up crashing the test because of calling property on null object.
I'm guessing I'm supposed to mock the eloquent model returned but I find 2 issues:
What's the point of implementing repository pattern if I'm gonna end up mocking eloquent model anyway
How do you mock them correctly? The code below gives me an error.
$this->mockRepository->shouldReceive('find')
->once()
->with(1)
->andReturn(Mockery::mock('MyNamespace\MyModel)
// The view may call $book->title, so I'm guessing I have to mock
// that call and it's returned value, but this doesn't work as it says
// 'Undefined property: Mockery\CompositeExpectation::$title'
->shouldReceive('getAttribute')
->andReturn('')
);
Edit:
I'm trying to test the controller's actions as in:
$this->call('GET', 'books/1'); // will call Controller#show(1)
The thing is, at the end of the controller, it returns a view:
$book = Repo::find(1);
return view('books.show', compact('book'));
So, the the test case also runs view method and if no $book is mocked, it is null and crashes
So you're trying to unit test your controller to make sure that the right methods are called with the expected arguments. The controller-method fetches a model from the repo and passes it to the view. So we have to make sure that
the find()-method is called on the repo
the repo returns a model
the returned model is passed to the view
But first things first:
What's the point of implementing repository pattern if I'm gonna end up mocking eloquent model anyway?
It has many purposes besides (testable) consisten data access rules through different sources, (testable) centralized cache strategies, etc. In this case, you're not testing the repository and you actually don't even care what's returned, you're just interested that certain methods are called. So in combination with the concept of dependency injection you now have a powerful tool: You can just switch the actual instance of the repo with the mock.
So let's say your controller looks like this:
class BookController extends Controller {
protected $repo;
public function __construct(MyNamespace\BookRepository $repo)
{
$this->repo = $repo;
}
public function show()
{
$book = $this->repo->find(1);
return View::make('books.show', compact('book'));
}
}
So now, within your test you just mock the repo and bind it to the container:
public function testShowBook()
{
// no need to mock this, just make sure you pass something
// to the view that is (or acts like) a book
$book = new MyNamespace\Book;
$bookRepoMock = Mockery::mock('MyNamespace\BookRepository');
// make sure the repo is queried with 1
// and you want it to return the book instanciated above
$bookRepoMock->shouldReceive('find')
->once()
->with(1)
->andReturn($book);
// bind your mock to the container, so whenever an instance of
// MyNamespace\BookRepository is needed (like in your controller),
// the mock will be loaded.
$this->app->instance('MyNamespace\BookRepository', $bookRepoMock);
// now trigger the controller method
$response = $this->call('GET', 'books/1');
$this->assertEquals(200, $response->getStatusCode());
// check if the controller passed what was returned from the repo
// to the view
$this->assertViewHas('book', $book);
}
//EDIT in response to the comment:
Now, in the first line of your testShowBook() you instantiate a new Book, which I am assuming is a subclass of Eloquent\Model. Wouldn't that invalidate the whole deal of inversion of control[...]? since if you change ORM, you'd still have to change Book so that it wouldn't be class of Model
Well... yes and no. Yes, I've instantiated the model-class in the test directly, but model in this context doesn't necessarily mean instance of Eloquent\Model but more like the model in model-view-controller. Eloquent is only the ORM and has a class named Model that you inherit from, but the model-class as itself is just an entity of the business logic. It could extend Eloquent, it could extend Doctrine, or it could extend nothing at all.
In the end it's just a class that holds the data that you pull e.g. from a database, from an architecture point of view it is not aware of any ORM, it just contains data. A Book might have an author attribute, maybe even a getAuthor() method, but it doesn't really make sense for a book to have a save() or find() method. But it does if you're using Eloquent. And it's ok, because it's convenient, and in small project there's nothing wrong with accessing it directly. But it's the repository's (or the controller's) job to deal with a specific ORM, not the model's. The actual model is sort of the outcome of an ORM-interaction.
So yes, it might be a little confusing that the model seems so tightly bound to the ORM in Laravel, but, again, it's very convenient and perfectly fine for most projects. In fact, you won't even notice it unless you're using it directly in your application code (e.g. Book::where(...)->get();) and then decide to switch from Eloquent to something like Doctrine - this would obviously break your application. But if this is all encapsulated behind a repository, the rest of your application won't even notice when you switch between databases or even ORMs.
So, you're working with repositories, so only the eloquent-implementation of the repository should actually be aware that Book also extends Eloquent\Model and that it can call a save() method on it. The point is that it doesn't (=shouldn't) matter if Book extends Model or not, it should still be instantiable anywhere in your application, because within your business logic it's just a Book, i.e. a Plain Old PHP Object with some attributes and methods describing a book and not the strategies how to find or persist the object. That's what repositories are for.
But yes, the absolute clean way is to have a BookInterface and then bind it to a specific implementation. So it could all look like this:
Interfaces:
interface BookInterface
{
/**
* Get the ISBN.
*
* #return string
*/
public function getISBN();
}
interface BookRepositoryInterface()
{
/**
* Find a book by the given Id.
*
* #return null|BookInterface
*/
public function find($id);
}
Concrete implementations:
class Book extends Model implements BookInterface
{
public function getISBN()
{
return $this->isbn;
}
}
class EloquentBookRepository implements BookRepositoryInterface
{
protected $book;
public function __construct(Model $book)
{
$this->book = $book;
}
public function find($id)
{
return $this->book->find($id);
}
}
And then bind the interfaces to the desired implementations:
App::bind('BookInterface', function()
{
return new Book;
});
App::bind('BookRepositoryInterface', function()
{
return new EloquentBookRepository(new Book);
});
It doesn't matter if Book extends Model or anything else, as long as it implements the BookInterface, it is a Book. That's why I bravely instantiated a new Book in the test. Because it doesn't matter if you change the ORM, it only matters if you have several implementations of the BookInterface, but that's not very likely (sensible?), I guess. But just to play it safe, now that it's bound to the IoC-Container, you can instantiate it like this in the test:
$book = $this->app->make('BookInterface');
which will return an instance of whatever implementation of Book you're currently using.
So, for better testability
Code to interfaces rather than concrete classes
Use Laravel's IoC-Container to bind interfaces to concrete implementations (including mocks)
Use dependency injection
I hope that makes sense.

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.

Unit Testing, using properties to pass in an interface

Im reading "The art of unit testing" atm and im having some issues with using properties to pass in an interface. The book states the following: "If you want parameters to be optional, use property getters/setters, which is a better way of defining optional parameters than adding different constructors to the class for each dependency."
The code for the property example is as follows:
public class LogAnalyzer
{
private IExtensionManager manager;
public LogAnalyzer ()
{
manager = new FileExtensionManager();
}
public IExtensionManager ExtensionManager
{
get { return manager; }
set { manager = value; }
}
public bool IsValidLogFileName(string fileName)
{
return manager.IsValid(fileName);
}
}
[Test]
Public void
IsValidFileName_NameShorterThan6CharsButSupportedExtension_ReturnsFalse()
{
//set up the stub to use, make sure it returns true
...
//create analyzer and inject stub
LogAnalyzer log = new LogAnalyzer ();
log.ExtensionManager=someFakeManagerCreatedEarlier;
//Assert logic assuming extension is supported
...
}
When/how would i use this feature?? The only scenario i can think of (This is probably wrong!) is if i had two methods in one class,
Method1() retrieves the database connection string from the config file and contains some form of check on the retrieved string.
Method2() then connect to the database and returns some data. The check here could be that that returned data is not null?
In this case, to test Method1() i could declare a stub that implements the IExtensionManager Interface, where the stub has a string which should pass any error checks i have in method1().
For Method2(), i declare a stub which implements the interface, and declare a datatable which contains some data, in the stub class. id then use the properties to assign this to the private manager variable and then call Method2?
The above may be complete BS, so if it is, id appreciate it if someone would let me know and ill remove it.
Thanks
Property injection used to change object's behavior after it was created.
BTW your code is tight coupled to FileExtensionManager, which is concrete implementation of IExtensionManager. How you are going to test LogAnalyzer with default manager? Use constructor injection to provide dependencies to your objects - this will make them testable:
public LogAnalyzer (IExtensionManager manager)
{
this.manager = manager();
}

How to test a protected method?

I have an ASP.NET page that is the base to many more derived pages and it contains the following protected method
protected Change SetupApproval(string changeDescription)
{
Change change = Change.GetInstance();
change.Description = changeDescription;
change.DateOfChange = DateTime.Now;
change.MadeBy = Common.ActiveDirectory.GetUsersFullName(AccessCheck.CurrentUser());
change.Page = PageName;
return change;
}
I want to write the following Unit test
[TestMethod]
public void SetupApproval_SubmitChange_ValidateDescription()
{
var page = new DerivedFromBaseClass();
var messageToTest = "This is a test description";
var change = (page as InternalAppsPage).SetupApproval(messageToTest);
Assert.IsTrue(messageToTest == change.Description);
}
I'm sure there's a lot wrong with this code (so feel free to suggest corrections), but my main goal is to start implementing some tests for this entire project. I decided to start small - one method at a time. I first tried creating a new Test Project, but then I can't access the SetupApproval method because it is protected. My next attempt was to put the TestMethod inside of the base page, but then there's no way to Run Tests.
Lastly, I'm using Visual Studio 2008's default test framework.
Two options:
Assuming DerivedFromBaseClass is a class which solely exists for testing, just give it a new public (or internal) method which just calls SetupApproval and returns the return value.
Make the method protected internal instead, and make sure you have InternalsVisibleTo set up for your test assembly so it has access to internal methods. Document that this is for the sake of testing.
The first option is cleaner, the second is simpler, particularly if you have a lot of protected methods and the base class is non-abstract.