Unit Testing
Unit Tests
To ensure the correct functionality of the code, unit tests are used. These tests help identify errors in the code early, reducing bugs in the game. For each class to be tested, a corresponding test class is created. In these test classes, unit tests are defined to verify the methods by providing expected inputs and comparing the actual outputs with the expected results. The process is demonstrated below with an example:
The function anyPairBodyIsSensor checks if either of the two bodies in a Matter.js collision pair is a sensor and returns true if that is the case.
/**
* Returns true if any body of the pair is a sensor
* @param pair
*/
export function anyPairBodyIsSensor(pair: Phaser.Types.Physics.Matter.MatterCollisionPair): boolean {
return pair.bodyA.isSensor || pair.bodyB.isSensor
}Tests will be organized in a separate test file, in this case named matter.test.ts. The functions to be tested must be imported into this file first.
test("any pair body is sensor", () => {
const pair = {
bodyA: {
isSensor: false,
},
bodyB: {
isSensor: true,
},
} as MatterCollisionPair
expect(anyPairBodyIsSensor(pair)).toBe(true)
})In this test, we define the prerequisites for the anyPairBodyIsSensor function. Specifically, bodyB is set as a sensor. Since the function is designed to return true if either of the two bodies in the collision pair is a sensor, the expected outcome is true, as one of the bodies is indeed a sensor.
After starting the test, it expects the result to be true. If this happens, the test is considered successful.
We apply this testing approach in all relevant areas to thoroughly verify the behavior of the code. By systematically identifying and addressing potential issues at an early stage, we can ensure that the code functions as intended. This proactive method helps prevent malfunctions and reduces the likelihood of bugs appearing in the game during later stages of development. | | | | |