标签: spring-boot-test

基于Spring Boot的测试中的上下文层次结构

我的Spring Boot应用程序启动如下:

new SpringApplicationBuilder()
  .sources(ParentCtxConfig.class)
  .child(ChildFirstCtxConfig.class)
  .sibling(ChildSecondCtxConfig.class)
  .run(args);
Run Code Online (Sandbox Code Playgroud)

配置类使用注释@SpringBootApplication.因此,我有一个根上下文和两个子Web上下文.

我想编写集成测试,我希望在那里有相同的上下文层次结构.我希望至少ChildFirstCtxConfig.class用他的父上下文(ParentCtxConfig.class)测试第一个子上下文(配置).我怎样才能做到这一点?

目前我ApplicationContext在我的测试中自动装配,所以我可以检查它.我在测试中有这个类注释:

@RunWith(SpringRunner.class)    
@SpringBootTest(classes = { ParentCtxConfig.class, ChildFirstCtxConfig.class }, webEnvironment = WebEnvironment.RANDOM_PORT)
Run Code Online (Sandbox Code Playgroud)

但这将产生单个上下文,我想要父子层次结构.我假设我应该用@ContextHierarchy注释来注释我的测试.

将我的测试注释更改为这似乎与前面的示例完全相同:

@RunWith(SpringRunner.class)    
@ContextConfiguration(classes = { ParentCtxConfig.class, ChildFirstCtxConfig.class })
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
Run Code Online (Sandbox Code Playgroud)

但是,如果我想介绍@ContextHierarchy并有这样的事情:

@RunWith(SpringRunner.class)
@ContextHierarchy({
        @ContextConfiguration(name = "root", classes = ParentCtxConfig.class),
        @ContextConfiguration(name = "child", classes = ChildFirstCtxConfig.class)
})
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
Run Code Online (Sandbox Code Playgroud)

由于在父上下文中定义的bean无法在子上下文中找到/自动装配,因此未启动上下文.设置loader = SpringBootContextLoader.class没有帮助.

示例代码:GitHub

java spring spring-test spring-boot spring-boot-test

8
推荐指数
1
解决办法
3445
查看次数

@SpringBootTest不会自动装配JavaMailSender并抛出错误

我在这做错了什么?我的理解是Spring应该以自动装配EventRepository的方式自动装配JavaMailSender.任何指导?

application.properties和application-test.properties

mail.host='smtp.gmail.com' -
mail.port=587
mail.username=username
mail.password=password
mail.properties.mail.smtp.starttls.enable=true
Run Code Online (Sandbox Code Playgroud)

我的实现类:如果我运行我的应用程序,这可以正常工作

      @Service
            public class EventService {
             private EventRepository eventRepository;
             private JavaMailSender javaMailSender;

                public EventService(EventRepository eventRepository, JavaMailSender   javaMailSender) {
                    this.eventRepository = eventRepository;
                    this.javaMailSender = javaMailSender;
                }

                public Event send(Event event) {
                   SimpleMailMessage message = new SimpleMailMessage();
                    message.setText("");
                    message.setSubject("");
                    message.setTo("");
                    message.setFrom("");
                    javaMailSender.send(message);
                    return eventRepository.save(event);
                }

            }
Run Code Online (Sandbox Code Playgroud)

我的集成测试类:能够自动装配EventRepository但不能使用JavaMailSender.

       @RunWith(SpringRunner.class)
        @SpringBootTest
        public class ApplicationIntegrationTests {
            @Autowired
            private EventService eventService;

         @Test
            public void test() throws Exception {
                eventService.save(new Event());
        }

        }
Run Code Online (Sandbox Code Playgroud)

错误:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No …
Run Code Online (Sandbox Code Playgroud)

jakarta-mail spring-boot spring-boot-test

8
推荐指数
1
解决办法
3960
查看次数

使用spring-boot-starter-test和cassandra进行单元测试

我的spring boot Web应用程序通过Datastax客户端使用Cassandra DB,连接如下:

public CassandraManager(@Autowired CassandraConfig cassandraConfig) {
  config = cassandraConfig;
  cluster = Cluster.builder()
      .addContactPoint(config.getHost())
      .build();
  session = cluster.connect(config.getKeyspace());
}
Run Code Online (Sandbox Code Playgroud)

当我运行单元测试时,spring boot应用程序尝试加载CassandraManager Bean并连接到Cassandra DB,而不是单元测试,因为我不需要它.我收到以下错误:[localhost/127.0.0.1:9042] Cannot connect)

有没有办法避免加载这个Cassandra Manager Bean来运行我的UT,因为他们不需要连接到数据库?这样做是一种好习惯吗?

unit-testing cassandra datastax spring-boot-test

8
推荐指数
1
解决办法
509
查看次数

8
推荐指数
1
解决办法
5369
查看次数

使用@RestClientTest对rest客户端进行Spring启动测试

我正在使用spring boot 1.5.8并想测试我的客户端:

@Component
public class RestClientBean implements RestClient {
  private Map<String, RestTemplate> restTemplates = new HashMap<>();

  @Autowired
  public RestClientBean(RestTemplateBuilder builder, SomeConfig conf) {
    restTemplates.put("first", builder.rootUri("first").build();
    restTemplates.put("second", builder.rootUri("second").build();
  }
}
Run Code Online (Sandbox Code Playgroud)

通过以下测试:

@RunWith(SpringRunner.class)
@RestClientTest(RestClient.class)
public class RestClientTest {
  @Autowired
  private RestClient client;

  @Autowired
  private MockRestServiceServer server;

  @TestConfiguration
  static class SomeConfigFooBarBuzz {
    @Bean
    public SomeConfig provideConfig() {
        return new SomeConfig(); // btw. not sure why this works, 
                                 // but this is the only way 
                                 // I got rid of the "unable to …
Run Code Online (Sandbox Code Playgroud)

java resttemplate spring-boot-test mockrestserviceserver

8
推荐指数
1
解决办法
5059
查看次数

Spring Boot Junit Testcases 中 contextLoads 方法的用途是什么?

这个方法在我所有的 JUnit 测试用例中都是空的。这个方法有什么用?

Sonarqube 抱怨
“添加嵌套注释,解释为什么此方法为空,抛出 UnsupportedOperationException 或完成实现。”

我可以通过添加一些评论来绕过这个,但我只想知道为什么有必要。

java junit testcase spring-boot spring-boot-test

8
推荐指数
2
解决办法
1万
查看次数

如何在使用 DataJpaTest 的 Spring Boot 2.0 测试中访问 H2 控制台

使用@DataJpaTest 时,如何配置测试类以使用处理 H2 控制台的 http 请求所需的位运行?

我正在运行使用 H2 的 Spring Boot 2.0 测试。我想在测试中设置断点并查看 H2 中表的内容。但是,当测试在断点处停止并且我将浏览器指向http://localhost:8080/h2-console 时,结果是一个空白页面,文本为“localhost 未发送任何数据”。因此,看起来要么测试运行时没有处理 H2 控制台的 http 请求所需的位,要么我使用的 URL 是错误的。

注意:当我运行测试时,控制台显示嵌入式 H2 数据库已成功启动,因此我确信 H2 确实在运行。

这是我的测试类注释:

@ExtendWith(SpringExtension.class)

@DataJpaTest

@TestInstance(TestInstance.Lifecycle.PER_CLASS)

我读了一篇文章,建议在我的 pom 中包含 devtools,但这并没有解决我的问题。

编辑:我的问题的症结似乎是我无法弄清楚如何配置测试以包含嵌入式测试数据库和正在运行的 servlet。如果我同时使用@DataJpaTest和注释测试类@SpringBootTest(webEnvironment = ...),则测试会由于缺少 ServletWebServerFactory bean 而崩溃。删除@DataJpaTest修复了缺少 bean 的问题,但我不再有嵌入式测试数据库。使用 only@DataJpaTest无法启动 servlet

h2 spring-data-jpa spring-boot-test

8
推荐指数
1
解决办法
2075
查看次数

Spring Boot WebFlux 测试未找到 MockMvc

问题

我正在尝试运行一个简单的 spring 启动测试,但我收到的错误表明它在运行时不能 MockMvc。文档表明我使用了正确的注释,并且我使用 start.spring.io 创建了我的 pom.xml。不知道为什么它有问题。

错误:

 No qualifying bean of type 'org.springframework.test.web.servlet.MockMvc'
Run Code Online (Sandbox Code Playgroud)

测试代码

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class MyWebApplicationTests {

    @Autowired
    MockMvc mockMvc;

    @Test
    public void Can_Do_Something() throws Exception {
        mockMvc.perform(get("/hello-world")).andDo(print()).andExpect(status().isOk())
                .andExpect(content().string(containsString("Hello World")));
    }

}
Run Code Online (Sandbox Code Playgroud)

文档:

我使用这个文档作为参考 - > https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-应用程序测试与模拟环境

POM文件

<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mywebapp</groupId>
    <artifactId>webapp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>my-webapp</name>
    <description>Backend application</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.M1</version>
        <relativePath/> <!-- …
Run Code Online (Sandbox Code Playgroud)

spring spring-mvc spring-boot spring-boot-test spring-webflux

8
推荐指数
2
解决办法
6599
查看次数

使用构造函数注入模式对 springboot 进行集成测试

我正在尝试使用构造函数注入依赖模式

我想知道在集成测试类上注入 JPA 存储库的正确方法是什么:

我有我的源代码:

回购类

@Repository
public interface MyClassRepo extends JpaRepository<MyClass, Long> {
... methods ...
}
Run Code Online (Sandbox Code Playgroud)

构造函数注入后的服务

public class MyClassService {

  private final MyClassRepo myClassRepo;

  public DeviceServiceImpl(final MyClassRepo myClassRepo) {
    this.myClassRepo = myClassRepo;
  }

  public boolean myMethodToTest() {
    ... whatever...
  }
}
Run Code Online (Sandbox Code Playgroud)

测试一下:(这是我的问题)

SpringRunner 类选项 1:构造函数注入

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = MyTestConfigClass.class) // With necessary imports
@SpringBootTest
public class MyClassTester {
  private final MyClassService myClassService;
  private final MyClassRepository myClassRepository;

  public MyClassTester (final MyClassRepository deviceRepository) {
    this.myClassRepository = myClassRepository; …
Run Code Online (Sandbox Code Playgroud)

java spring spring-test spring-boot spring-boot-test

8
推荐指数
1
解决办法
4032
查看次数

Spring Boot 中的单元测试或集成测试

我在网上查看了与测试相关的各种教程,Spring Boot并对测试的引用方式感到困惑。

有些文章将使用@WebMvcTest注释的控制器测试称为 as,Unit Test而有些则将其称为Integration Test. 不确定哪一个是正确的。

同样的问题适用于使用@DataJpaTest.

我在我的应用程序中编写了以下两个测试,一个用于控制器,另一个用于存储库。

在底部,我对两者都有一些疑问。请指导。

用户控制器测试.java

@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
public class UserControllerTest {

    @Autowired
    private MockMvc mockMvc;
    @MockBean
    private UserRepository userRepository;

    @Test
    public void signUp() throws Exception {
        this.mockMvc.perform(get("/signup")).andExpect(status().isOk());
    }

}
Run Code Online (Sandbox Code Playgroud)

UserRepositoryTest.java

@RunWith(SpringRunner.class)
@DataJpaTest
public class UserRepositoryTest {

    @Autowired
    private TestEntityManager entityManager;
    @Autowired
    private UserRepository userRepository;

    @Test
    public void whenFindByName_thenReturnEmployee() {
        // given
        User u = new User();
        u.setName("ab");
        u.setEmail("ab@cd.com");
        entityManager.persistAndFlush(u);
        // when
        Optional<User> user = …
Run Code Online (Sandbox Code Playgroud)

java integration-testing unit-testing spring-boot spring-boot-test

8
推荐指数
2
解决办法
4827
查看次数