Reputation: 43
I am using below dependency(in gradle) in my spring boot project to get it work with mysql
compile("org.springframework.boot:spring-boot-starter-data-jpa:${springBootCloudVersion}")
And have provided the Datasource setting in my application.properties file below:-
spring.datasource.url=jdbc:mysql://127.0.0.1/test?zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
and it is running good.
While executing Test cases in Spring Boot, I want to skip creating database connection with mysql, as I am not getting anything from database, Instead I have mocked (using mockito) and which is the correct way.
I have searched on google and stackoverflow and I am not able to find the solution about "how can I skip creating database connection while executing test cases".
Can someone help me out about this or guide
My Test File :-
package com.myproject.utility.services.impl;
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test")
public class UserServicesImplTest {
private static final String MOBILE = "123456";
@MockBean
private UserRepository userRepository;
@Autowired
private UserService userService;
@Test
public void verify(){
when(userRepository.findAll().thenReturn(Optional.empty());
userService.verifyDetails(MOBILE);
}
}
Upvotes: 4
Views: 5701
Reputation: 30329
You should provide a 'test configuration' which you can place inside your test class, then Spring will use it instead of production one:
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServicesImplTest {
private static final String MOBILE = "123456";
@MockBean private UserRepository userRepository;
@Autowired private UserService userService;
@Test
public void verify(){
when(userRepository.findAll().thenReturn(Optional.empty());
userService.verifyDetails(MOBILE);
}
@Configuration
@Import(UserService.class)
static class TestConfig {
@Bean
UserRepository userRepository() {
return mock(UserRepository.class);
}
}
}
More info is here: Detecting Test Configuration
Upvotes: 3