Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/390.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用内存数据库在Spring Boot中进行集成测试_Java_Spring_Spring Boot_Jpa_Junit - Fatal编程技术网

Java 使用内存数据库在Spring Boot中进行集成测试

Java 使用内存数据库在Spring Boot中进行集成测试,java,spring,spring-boot,jpa,junit,Java,Spring,Spring Boot,Jpa,Junit,我正在使用内存数据库h2进行集成测试,这样我就可以用已知值填充存储库,用repo初始化服务实现。这是我的测试课 @RunWith(SpringRunner.class) @TestPropertySource("classpath:application-test.properties") @SpringBootTest public class ManufacturerServiceH2ImplTest { @Autowired private ManufacturerRep

我正在使用内存数据库h2进行集成测试,这样我就可以用已知值填充存储库,用repo初始化服务实现。这是我的测试课

@RunWith(SpringRunner.class)
@TestPropertySource("classpath:application-test.properties")
@SpringBootTest
public class ManufacturerServiceH2ImplTest {

    @Autowired
    private ManufacturerRepository manufacturerRepository;

    @Autowired
    ManufacturerServiceImpl manufacturerServiceImpl;


    @Test
    public void testManufacturerCreate() throws Exception {

        //Create Manufacturer
        Manufacturer manufacturer = new Manufacturer();
        manufacturer.setManufacturerId("SSS");
        manufacturer.setManufacturerName("WWW");

        //Save Manufacturer in Inmemory 
        Manufacturer manufacturerInMemory = manufacturerRepository.save(manufacturer);

        //Service Implementation
        StResponse createManufacturer = manufacturerServiceImpl.createManufacturer(manufacturer);

        //Compare the result

    }

}

服务实现应该使用存储在内存数据库中的数据,并执行少量的业务验证。我在这里面临的问题是,服务实现实际上考虑的是manufacturerRepository实例,它在本例中指向实际的dbpostgres,而不是指向内存中的数据库。关于如何将manufacturerRepository实例注入manufacturerServiceImpl服务实现的任何帮助,该服务实现指出inmemory数据库在运行集成测试时使用Spring配置文件来使用H2,否则将使用另一个DB

将应用程序测试{yml | properties}添加到ressources中,并将@ActiveProfilestest添加到类中

application-test.yml

spring.profiles.active: test

spring:
  jpa:
    database: h2
  datasource:
    url: jdbc:h2:mem:AZ
    driver-class-name: org.h2.Driver
  h2:
    console:
      enabled: true

当integrationtests运行时,使用Spring概要文件使用H2,否则使用另一个DB

将应用程序测试{yml | properties}添加到ressources中,并将@ActiveProfilestest添加到类中

application-test.yml

spring.profiles.active: test

spring:
  jpa:
    database: h2
  datasource:
    url: jdbc:h2:mem:AZ
    driver-class-name: org.h2.Driver
  h2:
    console:
      enabled: true

如果您希望使用首选DB testContainer-Docker进行集成测试,请选中“答案”

如果您希望使用首选DB testContainer-Docker进行集成测试,请选中“答案”

如果您需要一个工作示例,请查看我的项目:Works。不过,我还需要设置ddl auto:createdrop才能工作。但是我也需要设置ddl auto:create drop才能工作。我不是测试方面的专家,但我认为在这种情况下,合适的术语是集成测试,而不是单元测试,因为整个spring引导上下文已经启动。我不是测试方面的专家,但我认为在这种情况下合适的术语是集成测试而不是单元测试,因为整个spring启动上下文已经开始了