Mockito BDDMockito given() Method Example

1. Introduction

Behavior-Driven Development (BDD) emphasizes collaboration and clear understanding between all parties involved in software development. Mockito, a popular Java mocking framework, has a BDD-flavored API called BDDMockito. One of its main methods is given(), which is used to describe a precondition or setup for the mock. In BDD terms, it's used to set up the "Given" state.

2. Example Steps

1. Define a simple service that we will mock in our test.

2. Set up a JUnit test class.

3. Use BDDMockito's given() method to specify mock behaviors.

4. Run the test and observe the output.

3. Mockito BDDMockito given() Method Example

// Step 1: Define a simple service
class UserService {
    String getUserRole(String username) {
        return "DefaultRole";  // A stub implementation

// Step 2: Set up a JUnit test class
import org.junit.jupiter.api.Test;
import static org.mockito.BDDMockito.*;

public class UserServiceTest {

    public void testGetUserRole() {
        // Mock the UserService using BDDMockito
        UserService mockService = mock(UserService.class);

        // Step 3: Use BDDMockito's given() method

        // Calling the mocked methods
        String adminRole = mockService.getUserRole("admin");
        String guestRole = mockService.getUserRole("guest");

        // Print the results
        System.out.println("Admin's role: " + adminRole);
        System.out.println("Guest's role: " + guestRole);


Admin's role: AdminRole
Guest's role: GuestRole

4. Step By Step Explanation

1. We started with a UserService that has a method getUserRole() which, in this stub, simply returns "DefaultRole".

2. In our test class UserServiceTest, we create a mock of UserService using BDDMockito.

3. The core of this example is BDDMockito's given() method. With this method, we describe the precondition of our mock, i.e., when certain methods with specific arguments are called, what should they return. In this case, when getUserRole("admin") is called, it should return "AdminRole", and when getUserRole("guest") is called, it should return "GuestRole".

4. The printed output, as expected, aligns with our mock setup, showcasing the utility of the given() method in BDD-style testing.