1

我有一个Springboot项目,我找到了一种创建和运行简单Junit测试用例的方法,该测试用例查看存储库并获取给定实体的一些数据属性。运行的结果Junit是通过,所以没有问题。

但问题就在这里,我已经看到了很多例子,其中教程展示了Springboot项目,他们可以简单地Junit只使用@Runwith@SpringBootTest 针对特定测试类运行测试。

在我的情况下,我必须添加 3 个注释,@SpringBootTest以及@RunWith直到@ContextConfiguation(with parameters)我能够运行测试用例。

所以我的问题是我如何才能尽可能简约地运行它,(我见过的一些练习对于他们的 springboot 测试类只有一个注释)

我的Springboot测试类如下所示:

我的 Junit 课程的屏幕截图

我的目录结构如下所示:

我的项目目录结构截图

我的application.properties样子是这样的:

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=none
spring.jpa.hibernate.show-sql=true
spring.datasource.url=jdbc:postgresql://localhost:5432/erfan
spring.datasource.username=erfan
spring.datasource.password=

#Some additional properties is trying to be set by Spring framework so this must be set
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true

spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true


#spring.datasource.initialization-mode=always
#spring.datasource.initialize=true
#spring.datasource.schema=classpath:/schema.sql
#spring.datasource.continue-on-error=true 

#HikariCP is a ConnectionPool manager, related to DB stuff



#Below is the property key you need to set to * as value to expose all kind of monitoring related information
#about your web application 

#management.endpoints.web.exposure.include=*

还有我的pom.xml文件:

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
    </parent>
    <groupId>com.sample</groupId>
    <artifactId>postgres</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>postgres</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>



    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>



        </plugins>






    </build>
</project>

那么我是否缺少 application.properties 文件中的某些内容?为了能够在我的测试类中删除“样板”注释,我应该包含哪些内容?

4

3 回答 3

1

取决于你想要做什么。基本上,spring 具有自定义注释,可将 spring 上下文配置为仅包含相关的 bean。这就是所谓的test slices

但是我总是尝试遵循一些“规则”:

  • @SpringBootTest除非您正在进行集成测试或手动设置要使用的类,否则请避免使用@SpringBootTest(classes = {MyService1.class, MyService2.class}
  • 如果您正在测试spring jpa,您可以使用@DataJpaTest注释,例如here
  • 如果您正在测试控制器,您可以使用此处@WebMvcTest的示例
  • 如果您正在测试其他服务,您始终可以使用@ContextConfiguration相应地配置 spring 上下文。

因此,例如,对于您的测试,我会以以下两种方式之一编写它:

@RunWith(SpringRunner.class)
@DataJpaTest
@Import(AnotherConfig.class)
class MyTest {
   // test stuff here
}
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {AnotherConfig.class})
// NOTE, if you have a JpaConfig class where you @EnableJpaRepositories
// you can instead add this config class to the @ContextConfiguration classes
@EnableJpaRepositories
class MyTest {
   // test stuff here
}

基本上,不要担心在测试之上有多少注释,而要担心哪些 bean/服务正在被自动装配。例如,这@SpringBootTest是一个单一的注解,但在 spring 上下文中自动装配所有的 bean。

于 2020-02-07T12:22:29.557 回答
0

我强烈建议不要在单元测试中使用一堆 spring 注释。单元测试应该只测试一段代码,而不是与外部或其他层相关,所以Mockito应该足够了。

例子:

@RunWith(MockitoJUnitRunner.class)
public class FooTest {
   @InjectMocks
   private FooService service;

   @Mock
   private FooRepository repository;

   @Test
   public void whenHappyPath_shouldReturnTrue(){
      doReturn(Optional.empty()).when(repository).findById(anyLong());
      assertTrue(service.isFoo(1L));
   }
}

您正在阻止您的单元测试到达存储库层,因此您不需要使用嵌入式数据库或任何其他东西创建上下文。

如果您用于集成测试,那么它是不同的,您将需要不同的策略。为此,我建议在测试中使用嵌入式数据库(如果您有 h2 依赖项,则默认情况下会使用该数据库):

<dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <scope>runtime</scope>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
</dependency>

并且还使用一个integrationtest弹簧配置文件:

@ActiveProfile("test") // or integration, you choose
public class FooIntegrationTest{
   ...
}

或强制其他配置文件指向另一个配置

@TestPropertySource(properties = { "spring.config.location=classpath:application-test.yml" })

应用程序-test.properties

spring.datasource.url=jdbc:h2:mem:test
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=sa
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create-drop
于 2020-02-07T13:11:41.933 回答
0

二凡,这完全取决于你的测试场景。

第一个场景:完整测试(集成测试)

如果你想测试整个应用程序,比如测试Service层、Repository层和Controller层,你需要一个真正的spring-context,所以你必须使用all @SpringBootTestand @RunWith...来初始化spring context来测试整个层。(这称为集成测试)

单元测试与集成测试:有什么区别

如何使用 java 集成测试

第二个场景:单元测试

如果您只想测试一段代码,就像您只想测试服务层和其他层(如存储库)在您的场景中并不重要,在这种情况下,您必须使用一些新的框架,如Mockito, 来模拟这些片段你不想测试它们,在这些场景中你不需要 **spring-context 初始化 ** 所以你不需要使用@SpringBootTest或其他注释。

模拟样本

因此,根据您的场景,您可以使用这些注释。


我强烈建议您阅读以下链接,以获取有关 Java 测试最佳实践的更多信息。

Java 测试的现代最佳实践

于 2020-02-07T13:36:31.100 回答