Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test Cases: Mocking Database using Spring beans

Our application has a service layer and a DAO layer, written as Spring beans.

While testing the Service Layer- I do not want to depend upon a real database so I am mocking that by creating a 'Mock' Impl for the DAO layer

So when I am testing the Service layer- I chain the Service layer beans to the Mock DAO beans And in Production- will chain the Service layer to the 'real' DAO beans

Is that a good idea ? Any alternate suggestion on how to mock the database layer ?

Clarification:This question is about testing the Service Layer and not the DAO layer. While testing the service layer- I assume that either the DAO layer has already been tested or doesn't need testing. The main thing is- how do we test service layer- without being dependent upon the DAO implementation- hence I am mocking the DAO layer

like image 332
RN. Avatar asked Jun 30 '09 16:06

RN.


People also ask

Can database be mocked for unit testing?

Yes, absolutely! Because our code that talks to the real DB is already tested carefully in the previous lecture. So all we need to do is: make sure that the mock DB implements the same interface as the real DB. Then everything will be working just fine when being put together.

What is mocking a database?

A mock is like a stub but the test will also verify that the object under test calls the mock as expected. Part of the test is verifying that the mock was used correctly. To give an example: You can stub a database by implementing a simple in-memory structure for storing records.

How do you write JUnit test cases for JPA repository?

You can create a @DataJpaTest and @Autowire your repository into it. For example: @RunWith(SpringRunner. class) @DataJpaTest public class MyJpaTest { @Autowired private ChartRepository chartRepository; @Test public void myTest() { ... } }


2 Answers

This is a technique we've been using for many years now. Note that when it comes to mocking the DAO interfaces you have some choices:

  • Create mock instances as real Java classes
  • Use a dynamic mocking framework such as jMock (my preference) or EasyMock

Dynamic mocking frameworks allow you to stub out a variety of circumstances (no data, 1 row, many rows, exception throwing) without having to create complex classes to stub out the behavior you wish to test

like image 100
Tim Avatar answered Oct 21 '22 16:10

Tim


That's a great way to use mocking to test the database. I don't think any alternative suggestion is necessary; I think you've got the right technique already!

like image 32
Paul Sonier Avatar answered Oct 21 '22 17:10

Paul Sonier