4

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);
  }
}
1
  • You test looks like very simple, maybe you do not need startup spring context. just create new object for testing and mock required fields. For injecting fields you can calling org.springframework.test.util.ReflectionTestUtils.setField Commented Jul 4, 2018 at 13:22

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.