简体   繁体   中英

Spring boot Unit tests by mocking all Data Base compenents

I want to Unit test a Service A which uses several JpaRepositories . I know that I can use @MockBean annotation to mock my repositories, however, all unit tests fails because Spring requires to have data base connection to start.

I have first try to mock DataSource and EntityManagerFactory beans but it does not work because there is another bean which calls the DataSource bean to connect to the data base and the mocked DataSource returns null .

My alternative is to use a H2 database only to fool Spring start but the H2 database is never really used because I mock all repositories that I need (and I don't want to test my Jpa Repositories). I don't like this solution because I consider it heavy (because of the initialisation of the H2 DB at each @SpringBootTest ) and in addition to this, the H2 DB is not really used for what it is made for.

Someone have a correct solution to unit test services which depend on JpaRepositories which themselves depends on SQL DB connection?

After reflection, my real problem is how I consider what is a UT.

In my case, my Service A received its dependencies with its constructor. I only want unit test the Service A , therefore I don't need a Spring context to do it. I only need to mock unecessary dependencies for my UTs (in a setup method with @BeforeEach for example) and DON'T use the @SpringBootTest annotation because Spring context is really not justify for this type of tests (UTs in my cases).

I think @SpringBootTest is usefull for Integration tests and not Unit tests .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM