简体   繁体   English

使用 Spock 和 groovy,SpringBoot 测试我基于注解的 myBatis 映射器

[英]Testing my annotation based myBatis mapper, using Spock and groovy, SpringBoot

I created myBatis mapper based on annotations as this changed code example:我创建了基于注释的myBatis映射器作为这个更改的代码示例:

import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface MyTableMapper {

    @Insert("INSERT INTO MY_TABLE(" +
                "Column_1, " +
                "Column_2 " +
            ") VALUES (" +
                "#{myTableModel.columnOne}, " +
                "#{myTableModel.columnTwo} " +
            ")")
    int insert(MyTableModel myTableModel);


    @Select("SELECT * FROM MY_TABLE")
    @Results(value = {
            @Result(id = true, property = "columnOne", column = "Column_1"),
            @Result(property = "columnTwo", column = "Column_2")
    })
    List<MyTableModel> findAll();


    @ResultType(Integer.class)
    @Select("SELECT COUNT(*) FROM MY_TABLE " +
            "WHERE Column_1 = #{columnOne} AND Column_2 = #{columnTwo}")
    int countByColumnOneAndColumnTwo(@Param("columnOne") String columnOne, @Param("columnTwo") String columnTwo);


    @Update("UPDATE MY_TABLE SET " +
            "Column_3 = #{myTableModel.columnThree}, "
            "Column_4 = #{myTableModel.columnFour} " +
            "WHERE Column_1 = #{myTableModel.columnOne} AND Column_2 = #{myTableModel.columnTwo}")
    int updateByColumnOneAndColumnTwo(@Param("myTableModel") MyTableModel myTableModel);


    @Delete("DELETE FROM MY_TABLE " +
            "WHERE Column_1 = #{myTableModel.columnOne} AND Column_2 = #{myTableModel.columnTwo}")
    void deleteByColumnOneAndColumnTwo(@Param("myTableModel") MyTableModel myTableModel);

}

CONSIDERATIONS!注意事项! I'm using Spring Cloud Config and Hashicorp Vault .我正在使用Spring Cloud ConfigHashicorp Vault

spring:
  datasource:
    url: jdbc:sqlserver://172.xx.yy.zzz:1433;databaseName=myDatabase;encrypt=true;trustServerCertificate=true;
    driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
    testWhileIdle: true
    testOnBorrow: true
    hikari:
      connection-test-query: SELECT 1
      ....

Some yaml config file一些yaml配置文件

  #Hashicorp Vault
spring.cloud.vault:
  scheme: ${VAULT_SCHEME:http}
  host: ${VAULT_HOST:localhost}
  port: ${VAULT_PORT:8xyz0}
  ...
  application-name: my-microservice-name

#Config Server
spring.cloud.config:
  ...
  uri: ${SPRING_CLOUD_CONFIG_URI:http://localhost:8xx8}

The credentials are stored in vault ( To create SqlSession , and other things in XML file are not option )凭据存储在保险库中(创建SqlSession ,XML 文件中的其他内容不是选项

Now I would like to test my mapper.现在我想测试我的映射器。 I found this documentation Using @MybatisTest part.我找到了这个文档Using @MybatisTest部分。

My Test Spock File!我的测试Spock文件!

import org.springframework.beans.factory.annotation.Autowired
import spock.lang.Specification

class MyTableMapperSpec extends Specification {

    @Autowired
    private MyTableMapper myTableMapper
    private MyTableModel myTableModel

    void setup() {
        def myTableModelId = MyTableModelId.builder()
              //.someFields
                .build()
        myTableModel = MyTableModel.builder()
              //.someFields
                .build()
        myTableMapper.deleteByColumnOneAndColumnTwo(myTableModel)
        myTableMapper.insert(myTableModel)
    }

    def "FindAll"() {
        when:
        List<MyTableModel> listMyTableModel = myTableMapper.findAll()
        then:
        !listMyTableModel.isEmpty()
    }

    void cleanup() {
        //myTableMapper.deleteByColumnOneAndColumnTwo(myTableMapper)
    }
}

When I like to test this line: myTableMapper.deleteByColumnOneAndColumnTwo(myTableModel) I noted that my myTableMapper is null !当我想测试这一行时: myTableMapper.deleteByColumnOneAndColumnTwo(myTableModel)我注意到我的myTableMappernull Maybe the @Autowired annotation is not suitable in my code!也许@Autowired注解不适合我的代码!

How solve this (Obtain an implementation of my mapper)?如何解决这个问题(获取我的映射器的实现)?

Well, you then need actually annotate your Spock specification with @MybatisTest .那么,您实际上需要使用@MybatisTest注释您的 Spock 规范。 You also need the spock-spring dependency in addition to the spock-core dependency.除了spock-core依赖项之外,您还需要spock-spring依赖项。

The documentation has:该文件有:

import org.mybatis.spring.boot.test.autoconfigure.MybatisTest

@RunWith(SpringRunner.class)
@MybatisTest
public class CityMapperTest {

    @Autowired
    private CityMapper cityMapper;

    @Test
    public void findByStateTest() {
        City city = cityMapper.findByState("CA");
    }

}

The build.gradle build.gradle

implementation group: 'org.mybatis.spring.boot', name: 'mybatis-spring-boot-test-autoconfigure', version: 'x.y.z'

But, @MybatisTest will fail because you don't have dataSource , sqlSessionFactory or something!但是, @MybatisTest会失败,因为你没有dataSourcesqlSessionFactory或其他东西!

Try with: @SpringBootTest尝试: @SpringBootTest

@SpringBootTest(classes = YourApplication.class) /* your annotated class with @SpringBootApplication */
class MyTableMapperSpec extends Specification {
 ...
}

or或者

@SpringBootTest
class MyTableMapperSpec extends Specification {
 ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 测试 SpringBoot web 应用程序时,如何在 groovy spock 的“设置”中定义获取值? - How the get values defined in "setup" in groovy spock when testing SpringBoot web app? 用于测试的SpringBoot @IntegrationTest注释 - SpringBoot @IntegrationTest annotation for testing 使用Spock Testing Framework和Spring Boot来测试我的REST控制器 - Using Spock Testing Framework with Spring Boot to test my REST Controller 使用基于注释的SpringBoot ThreadPoolTask​​Executor时如何防止队列超载? - How to prevent overloading the queue when using annotation based SpringBoot ThreadPoolTaskExecutor? 无法在 spock 中使用注解 @Autowired 注入 JpaRepository - Cannot inject JpaRepository using annotation @Autowired in spock 如何使用RESTFUL API和SpringBoot-MyBatis-MySQL对MySQL数据库进行基本的SELECT FROM调用? - How to Make a Basic SELECT FROM call to my MySQL database using RESTFUL API with SpringBoot-MyBatis-MySQL? 如何在Springboot中测试mybatis功能时修复“ibatis绑定异常”? - How to fix 'ibatis binding exception' when testing mybatis functionality in Springboot? 为什么我的Spring Boot @Autowired MyBatis静态映射器为null? - Why is my Spring Boot @Autowired MyBatis static mapper null? 如何将 Spock 添加到我的 Springboot 项目中? - How do I add Spock to my Springboot project? MyBatis @Mapper声明 - MyBatis @Mapper declaration
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM