How-to articles, tricks, and solutions about UNIT-TESTING

Best practices to test protected methods with PHPUnit

There are a few ways you can test protected methods using PHPUnit:

Difference between @Mock and @InjectMocks

In the context of testing with the Mockito framework, the @Mock annotation is used to create a mock object of a class or interface, and the @InjectMocks annotation is used to inject the mock objects into a test class.

How do I test a class that has private methods, fields or inner classes?

To test a class that has private methods, fields, or inner classes, you can do the following:

How do you test that a Python function throws an exception?

You can use the pytest.raises function to test that a Python function throws an exception.

How to mock void methods with Mockito

To mock a void method with Mockito, you can use the doAnswer method. Here is an example of how you can use it:

How to reload/refresh model from database in Laravel?

In Laravel, you can use the refresh method on a model instance to reload the model's attributes from the database.

How to run test methods in specific order in JUnit4?

In JUnit 4, you can use the @FixMethodOrder annotation to specify the order in which test methods should be executed.

How to test that no exception is thrown?

To test that no exception is thrown in a Java method, you can use the assertDoesNotThrow method from the org.junit.jupiter.api.Assertions class (part of the JUnit 5 library).

How to verify that a specific method was not called using Mockito?

To verify that a specific method was not called using Mockito, you can use the verifyZeroInteractions method.

Mocking static methods with Mockito

Mockito is a popular mocking framework for Java. It allows you to create mock objects and set up test behavior for them.

Mockito : how to verify method was called on an object created within a method?

To verify that a method was called on an object created within a method using Mockito, you can use the Mockito.verify() method and pass it the object that you want to verify, as well as the method that you want to verify was called.

PHPUnit: assert two arrays are equal, but order of elements not important

You can use the assertEqualsCanonicalizing or assertEqualsIgnoringCase methods to compare two arrays and ignore the order of the elements.

Run a single test method with maven

To run a single test method with Maven, you can use the surefire:test goal and specify the fully-qualified name of the test class and the method name using the test and method properties, respectively.

Running unittest with typical test directory structure

Here is an example of how you can run unittests in Python using the typical test directory structure: