gpt4 book ai didi

java - 如何初始化 JAX-RS HttpHeader

转载 作者:行者123 更新时间:2023-12-02 03:01:30 24 4
gpt4 key购买 nike

我有一个内部框架,其中有一个类,如下所示:

public abstract class POSEnterpriseResource extends SynchronousResource {
...
@Inject
protected HttpHeaders headers;
...
}

我需要为一个类编写单元测试,将其扩展为使用类似的代码

String acceptMediaType = headers.getHeaderString("Accept");
String acceptVersion = headers.getHeaderString("Accept-Version");

所讨论的 HttpHeaders 类型是 javax.ws.rs.core.HttpHeaders 下的接口(interface),不公开任何初始化方法,仅公开 getter。我无法触及现有代码。

如何在不设置整个 ResponseEntity 的情况下模拟这样的 headers 对象?

最佳答案

你可以只使用像Mockito这样的模拟库。以下是如何设置测试

// set up the runner so Mockito handles all the 
// initialization and injections
@RunWith(MockitoJUnitRunner.class)
public class Testing {

// HttpHeaders is mocked and injected into test
@Mock
private HttpHeaders headers;

// HttpHeaders is injected into the resource class field
@InjectMocks
private TestResource resource;

@Test
public void testHttpHeaders() {
// control what the mock returns when certain methods are called
when(headers.getHeaderString("X-Test")).thenReturn("X-Test-Value");
}
}

下面是一个完整的测试,向您展示使用该库进行测试的一般方法。如果您以前从未使用过该库,我建议您花一些时间阅读文档。学习基础知识非常容易。

import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.HttpHeaders;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;


@RunWith(MockitoJUnitRunner.class)
public class Testing {

@Mock
private HttpHeaders headers;

@InjectMocks
private TestResource resource;

@Test
public void testHttpHeaders() {
when(headers.getHeaderString("X-Test")).thenReturn("X-Test-Value");

String response = resource.get();
assertThat(response).isEqualTo("X-Test-Value");
}


@Path("test")
public static class TestResource {

@Inject
private HttpHeaders headers;

@GET
@Produces("text/plain")
public String get() {
return headers.getHeaderString("X-Test");
}
}
}

关于java - 如何初始化 JAX-RS HttpHeader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59865644/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com