Welcome to the Mockito Mocks lesson! Today, we'll learn how to write testable code using Mockito, a popular mocking framework for the Java programming language. Let's dive in! 🐟
Mocks are stand-in objects that mimic the behavior of real objects in your application. They are used during testing to replace real objects, allowing you to isolate and test individual components of your code.
Mockito simplifies the process of creating mocks, making your tests cleaner, more efficient, and easier to understand. It offers a fluent API, easy setup, and versatile matching logic.
To use Mockito in your project, you'll first need to add it as a dependency. For Maven, include the following in your pom.xml:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>4.3.1</version>
<scope>test</scope>
</dependency>For Gradle, add this to your build.gradle:
testImplementation 'org.mockito:mockito-core:4.3.1'Now, let's create a simple mock example. Suppose we have a Person class with a getName() method:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}To create a mock of Person, use Mockito's mock() function:
import static org.mockito.Mockito.*;
import org.junit.Test;
public class PersonTest {
@Test
public void testGetName() {
// Create a mock Person
Person mockPerson = mock(Person.class);
// When the getName() method is called
when(mockPerson.getName()).thenReturn("John Doe");
// Assert that the getName() method returns the expected value
assertEquals("John Doe", mockPerson.getName());
}
}In this example, we create a mock Person and use Mockito's when() function to specify that when getName() is called, it should return "John Doe."
Mockito allows you to mock both instance methods and static methods. For instance methods, use the mock() function as shown earlier. For static methods, use mockStatic():
import static org.mockito.Mockito.*;
import org.junit.Test;
public class MathTest {
@Test
public void testAddition() {
// Mock the Math class
mockStatic(Math.class);
// When the add() method is called
when(Math.addExact(2, 3)).thenReturn(5);
// Assert that the addition works as expected
assertEquals(5, Math.addExact(2, 3));
}
}In this example, we mock the Math class, which has a static addExact() method. We then use Mockito's when() function to specify that when addExact(2, 3) is called, it should return 5.
What is the purpose of Mockito in testing?
Keep learning, and happy coding! 🌟