Boot中进行测试时跳过与mysql的数据库连接

Boot中进行测试时跳过与mysql的数据库连接

本文介绍了在Spring Boot中进行测试时跳过与mysql的数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Spring Boot项目中使用以下依赖项(在gradle中)以使其与mysql一起工作

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}")

并且在下面的我的application.properties文件中提供了数据源设置:-

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

它运行良好.

在Spring Boot中执行测试用例时,我想跳过与mysql创建数据库连接的过程,因为我没有从数据库中得到任何东西,相反,我已经嘲笑(使用模仿),这是正确的方法.

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.

我已经在google和stackoverflow上进行了搜索,但找不到关于如何在执行测试用例时跳过创建数据库连接的方法"的解决方案.

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

我的测试文件:-

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);
  }
}

推荐答案

您应该提供一个测试配置",可以将其放置在测试类中,然后Spring将使用它而不是生产版本:

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);
    }
  }
}

更多信息在这里:检测测试配置

这篇关于在Spring Boot中进行测试时跳过与mysql的数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 20:42