How provide embedded DB to used by Mockito?

Viewed 136

Hi I am new Mockito framework and trying to write some unit test for my spring-boot application. I mocked my service so every time Mockito is running , it is using some empty mock db, I want to use some prepared embedded database, Let me explain you the use case. I have one entity let say EntityX.

@Entity
@Table(name = "ENTITYX")
public class EntityX{
   private long id;
   // Some other properties
}

I created its repository, I have one service which define a method process, this method takes in a parameter of entityId and fetch that entity from DB as follows.


@Service
public class MyService{
   @Autowired
   EntityXRepository repository;

   public Object process(long entityId){
      EntityX entity  = repository.findById(entityId).orElseThrow(()-> new RuntimeException("No Entity found with id "+entityId));
      // Does some operation with entity object. 
     ...
     return someObject;
   }

}

Now in my unit test, I am mocking my service using @Mock and calling process(someid); but process method always throwing exception because there is no entity exists for someid in mock db. Inserting into EntityX table is outside the scope of my application, So Is it possible to provide some database file (Some embedded DB file) to Mockito so that it can start with provided database records instead of empty db?

1 Answers

You can create an application-test.properties file and use h2 database for this exact use case if you really want to use a database in your unit tests.

<!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.200</version>
    <scope>test</scope>
</dependency>

And in order to load the test profile in your unit tests you can use this annotation on top of your test classes.

@ActiveProfiles("test")

And in order to have insert scripts you can get more information in the link below, that will solve the problem of loading the database on start of unit test.

H2 in-memory database initialization with data


Also just out of curiosity if you want to avoid database interactions your can mock the EntityXRepository repository; and using mockito mimic the required behaviour.

@SpringBootTest
@ActiveProfiles("test")
class TestService{

@MockBean
EntityXRepository repository;

@Test
void test_somescenario_success(){
  Mockito.when(repository.findById("someId")).thenReturn(someEntityX);
  //other mocks, service call and assertions
}
}
Related