Testing
Introduction
Masonite testing is very simple. You can test very complex parts of your code with ease by just extending your class with a Masonite unit test class.
You can run tests by running:
Configuration
First, create a new test class in a testing directory. We will use the directory tests/unit
for the purposes of this documentation. In that file we will create a test_unit.py
file and put a simple class in it like so:
We will then inherit the Masonite UnitTest class so we have access to several built in helpers:
That's it! You're ready to start testing.
Your unit test needs to start with Test
in order for pytest to pick it up.
Usage
Setup method
In unit testing, there is something called a setup_method. What this method does is it runs when the test class is first ran. This is good for setting up routes or anything else all your tests need.
If we modify the setup method, we need to call the parent classes setup method. This looks like this:
Notice here we are adding a mock route here that we can do some testing on. You might instead want to test your routes specifically:
Now we are working with the routes in our specific project.
Routes
We have a few options for testing our routes.
Testing If a Route Exists:
Testing If Route Has The Correct Name
Testing If A Route Has The Correct Middleware
Testing If A Route Has The Correct Controller
Testing If A Route Contains A String
This can be used to see if the template returned a specific value
Status Code
You can also check if a route is "ok" or a status 200:
or a shorthand:
JSON
You can also test the result of a JSON response:
Users
We can load users into the route and check if they can view the route. This is good to see if your middleware is acting good against various users.
For example we can check if a user that isn't logged in has access to the dashboard homepage:
Or we can set a value on a mock user and see if that passes:
Last updated