Search code examples
javajunitmockito

Junit test is failing with Mockito


I am new to java, junit and mockito. And I have a very simple class BookingManager class

package com.daydreamer.mocka;

import java.util.List;
import java.util.Arrays;

public class BookingManager {

    // Getters
    public List<Integer> getRoomsFromDb() {
        // Suppouse we are fetching data from database
        int[] roomInts = {1,2};
        List<Integer> rooms = Arrays.stream(roomInts).boxed().toList();
        return rooms;
    }

    public boolean getRoom(int ind) {
        List<Integer> rooms = this.getRoomsFromDb();
        return rooms.contains(ind);
    }

    // String represntation
    @Override
    public String toString() {
        String strRepr = "BookingManager {" +
       "}";
        return strRepr;
    }
}

and its corresponding test class BookingManagerTest.

package com.daydreamer.mocka;

import java.util.List;
import java.util.ArrayList;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

import com.daydreamer.mocka.BookingManager;

@DisplayName("Booking Manager Test")
public class BookingManagerTest {

     private BookingManager bm;

    @BeforeEach
    void init() {
        this.bm = Mockito.mock(BookingManager.class);
        List<Integer> rooms = new ArrayList<>();
        rooms.add(1);
        rooms.add(2);
        Mockito.when(this.bm.getRoomsFromDb()).thenReturn(rooms);
    }

    // Why this test is failing, please help !
    @Test
    @DisplayName("postive test")
    void testGetRoomPositive(){
        Assertions.assertTrue(this.bm.getRoom(1));
        Mockito.verify(this.bm, Mockito.times(1)).getRoom(1);
    }

    @Test
    @DisplayName("negative test")
    void testGetRoomNegative(){
        Assertions.assertFalse(this.bm.getRoom(5));
        Mockito.verify(this.bm, Mockito.times(1)).getRoom(5);
    }


}

however, the mock is not working as expected. testGetRoomPositive should return true but returning false. Could someone let me know my mistake.

Cheers.


Solution

  • As mentioned over the comments also, you shouldn't mock your intended class.

    Now since you have mocked your intended class. You can work around for this failing test case by :

    when(bm.getRoom(anyInt())).thenCallRealMethod();  // Real implementation
    

    It will again fail on the database, you can mock your database rather than real call. That also makes sense for this use case.