java - 如何在 Spring 上下文初始化之前模拟 REST 服务器?

标签 java spring unit-testing junit

我有一个 Spring Bean,它使用 RestTemplateBuilder 在其构造函数内发送请求,以便发送请求:

@Service
class MyService {

  MySettingsFromRemote settings;

  MyService(RestTemplateBuilder builder, @Value("${my-url}") String url){
    var rt = builder.build();
    setting = rt.getForEntity(url, MySettingsFromRemote.class);
  }
  
  ...
}

在测试期间,我想使用MockRestServiceServer(或者可能模拟用于发送请求的RestTemplateBuilder)和一些预定义的数据来模拟响应,以便应用程序上下文加载。该地址写入application.properties文件中。

我尝试这样做:

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.autoconfigure.web.client.AutoConfigureMockRestServiceServer;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.test.web.client.match.MockRestRequestMatchers;

import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;

@RunWith(SpringRunner.class)
@AutoConfigureMockRestServiceServer
@SpringBootTest
public class CollectorApplicationTest {
    
    @Autowired
    MockRestServiceServer server;
    
    @Value("${components.web-admin-portal.rest.schemas}")
    String webAdminPortal;
    
    @Before
    public void init() {
        
        server.expect(MockRestRequestMatchers.requestTo(webAdminPortal))
              .andRespond(withSuccess("{}", MediaType.APPLICATION_JSON));
    }
    
    @Test
    public void contextLoads() {
        
    }
}

但是上下文在执行 @Before 方法之前加载,并失败并显示一条消息,指出 MockRestServiceServer 未预期该请求。

然后我尝试使用ApplicationContextInitializer:

import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.test.web.client.match.MockRestRequestMatchers;

import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;

public class AppInit implements ApplicationContextInitializer<ConfigurableApplicationContext> {
    
    @Override
    public void initialize(final ConfigurableApplicationContext context) {
        
        context.refresh();
        MockRestServiceServer server         = context.getBean(MockRestServiceServer.class);
        String                webAdminPortal = context.getEnvironment()
                                                      .getProperty("components.web-admin-portal.rest.schemas");
        
        server.expect(MockRestRequestMatchers.requestTo(webAdminPortal))
              .andRespond(withSuccess("{}", MediaType.APPLICATION_JSON));
    }
}

但随后它提示 MockServerRestTemplateCustomizer 尚未绑定(bind)到 RestTemplate。我认为这个问题可以通过在测试类上使用 @RestClientTest 注释来解决,因为它会禁用 RestTemplateBuilder 的自动配置并启用 MockRestServiceServer 的确认>:

@RunWith(SpringRunner.class)
@SpringBootTest
@RestClientTest
@ContextConfiguration(initializers = AppInit.class)
public class CollectorApplicationTest {

但这并没有改变任何东西。

提前致谢。

最佳答案

这个设置对我有用:

@Service
public class MyService implements ApplicationListener<ContextRefreshedEvent> {

    private final RestTemplate restTemplate;

    public MyService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        //make your call here
        restTemplate.getForEntity("http://www.localhost:9090", String.class);
    }

}

当且仅当 spring 上下文完全初始化时才会进行调用

在测试类中:

@TestConfiguration
public class MockServiceCallConfiguration {

    @Autowired
    private RestTemplate restTemplate;

    @Bean
    public MockRestServiceServer mockRestServiceServer() {
        MockRestServiceServer server = MockRestServiceServer.createServer(restTemplate);

        server.expect(MockRestRequestMatchers.requestTo("http://www.localhost:9090"))
                .andRespond(withSuccess("{}", MediaType.APPLICATION_JSON));

        return server;
    }
}

@SpringBootTest(classes = {MockServiceCallConfiguration.class})
@RunWith(SpringRunner.class)
public class MyServiceTest {


    @Test
    public void test() {

    }

}

这是相当乏味的,如果你能重构你的代码并避免在初始化设置期间调用休息服务,而是在某些业务事件上,那肯定会更好

关于java - 如何在 Spring 上下文初始化之前模拟 REST 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49670934/

相关文章:

java - 在 Java RMI 中,客户端如何知道其服务器已死亡?

html - spring mvc 向收件人发送时尚且格式化的电子邮件

java - 线程“main”中的Maven项目异常java.lang.NoClassDefFoundError:org/springframework/core/DefaultParameterNameDiscoverer

c# - 为什么单元测试在 Visual Studio 2015 for SQL Server 项目中变灰?

java - JDK java 可执行文件与 JRE 可执行文件

java - 获取 Java Scanner 类错误

java - Hibernate 命名策略更改表名

php - HTML 输出的单元测试?

python - 如何以比应用程序更高的粒度在 Django 中对单元测试进行分组?

java - 从命令行使用 JAR 保持 JVM 运行