【问题标题】:How to connect to local running server in springboot testing如何在 Spring Boot 测试中连接到本地运行的服务器
【发布时间】:2022-02-03 07:08:05
【问题描述】:

我的应用程序在本地运行,端口为 8089,我正在尝试进行 Spring Rest Controller 测试。

它运行在 8089 端口。

在 application.yml 中

spring:
  profiles:
    active: sit

在 application-sit.yml 中

server:
  port: 8089
  servlet:
    context-path: /myapp

在我的基本测试用例中:

import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(SpringJUnit4ClassRunner.class)
//@SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
//@WebAppConfiguration
@SpringBootTest(classes = MyApplication.class,
        webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@ActiveProfiles("sit")
public abstract class FullOtpControllerTest {
    protected MockMvc mvc;

    @Autowired
    WebApplicationContext webApplicationContext;

    @Value("${server.port}")
    int serverPort;

    @Test
    public void sendOtpTest() throws Exception {
        String uri = "/sendOtp";
        //{"clientId": "default2","tag": "tag","mobileNumber": "9999988888"}
        SendOTPRequestDTO otpRequest = new SendOTPRequestDTO();
        otpRequest.setClientId("default2");
        otpRequest.setTag("tag");
        otpRequest.setMobileNumber("9321901416");

        String inputJson = mapToJson(otpRequest);
        MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri)
                //.accept(MediaType.APPLICATION_JSON_VALUE)).andReturn()
                .contentType(MediaType.APPLICATION_JSON_VALUE)
                .content(inputJson)).andReturn();

        int status = mvcResult.getResponse().getStatus();
        String content = mvcResult.getResponse().getContentAsString();
        assertEquals(8089,serverPort);
        assertEquals(200, status);

    }
}

但是,第一个断言通过了。但在调试中它显示了不同的端口,如下图所示。

我运行:OtpControllerTest.sendOtpTest,我得到:

java.lang.AssertionError: 
Expected :200
Actual   :404

【问题讨论】:

  • 不能使用 MockMvc 连接真实服务器。这就是TestRestTemplateTestWebClient 的用途。
  • 请帮助我了解更多详情。
  • @SpringBootTest 上的这篇文章可能会有所帮助。使用MockMvc,您可以针对模拟的servlet 环境进行测试(通常在@WebMvcTest 内完成)。在您的测试中,当您在本地端口上启动嵌入式 servlet 容器时,您需要真正的 HTTP 通信。简而言之,删除MockMvc 并注入自动配置的TestRestTemplate 以访问您的本地应用程序。

标签: spring spring-boot spring-test spring-rest


【解决方案1】:

MockMVC 旨在用于不同类型的测试。 它与@WebMvcTest 注释结合使用,并允许测试您的控制器定义:注释、参数等。 在这种情况下,spring 会启动与 WEB 层相关的应用程序的“拼接”,例如,它不会加载带有 @Service@Repository 注释的 bean,但会加载所有 @RestController 注释的类。如果控制器依赖于某个服务,你可以用@MockBean注解模拟它

在任何情况下,它都不需要任何类型的远程应用程序,一切都“就地”运行。

@SpringBootTest 注释用于不同的目的,因此您不应运行使用此注释注释的测试,而应改用 MockMVC: @SpringBootTest 运行整个微服务(加载所有 bean)。或者,有一种“模式”,其中 spring boot 测试仅加载明确定义的上下文配置...

如果您的目的是对远程应用程序的 API 进行黑盒测试——你根本不必使用 spring——你不需要 bean,不需要注入——你只需要一个 Http 客户端某种(甚至不必使用 Java)来实现这种测试。

一个框架(在众多框架中)是Rest Assured,但这里同样有很多选择。

【讨论】:

    猜你喜欢
    • 2017-02-27
    • 2014-05-10
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 2023-03-25
    相关资源
    最近更新 更多