gpt4 book ai didi

java - 使用 Jersey2.0 访问 JerseyTest 中的 springbean

转载 作者:太空宇宙 更新时间:2023-11-04 11:58:23 26 4
gpt4 key购买 nike

我有 Spring 的 Jersey 项目。现在我的测试是从 JerseyTest 派生的。当我尝试做时

@AutoWired 
RestTemplate restTemplate;

看起来 Spring 在 Jersey 测试中不起作用。我做了一些研究,发现了一些链接,例如 spring_jersey但它不起作用,因为我使用的是 jersey2.0。

我的代码看起来像

 //AbstractTest 
package com.test;


import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Application;

import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.filter.LoggingFilter;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.server.ServerProperties;
import org.glassfish.jersey.server.validation.ValidationFeature;

public abstract class AbstractTest extends JerseyTest
{
protected WebTarget getRootTarget(final String rootResource)
{
return client().target(getBaseUri()).path(rootResource);
}

@Override
protected final Application configure()
{
final ResourceConfig application = configureApplication();

// needed for json serialization
application.register(JacksonFeature.class);

// bean validation
application.register(ValidationFeature.class);

// configure spring context
application.property("contextConfigLocation", "classpath:/META-INF/applicationContext.xml");

// disable bean validation for tests
application.property(ServerProperties.BV_FEATURE_DISABLE, "true");

return application;
}

protected abstract ResourceConfig configureApplication();

@Override
protected void configureClient(final ClientConfig config)
{
// needed for json serialization
config.register(JacksonFeature.class);

config.register(new LoggingFilter(java.util.logging.Logger.getLogger(AbstractResourceTest.class.getName()), false));

super.configureClient(config);
}
}



package com.test;

import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;

//MyTest
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;

import org.apache.commons.io.IOUtils;
import org.glassfish.jersey.server.ResourceConfig;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.test.web.client.match.MockRestRequestMatchers;
import org.springframework.web.client.RestTemplate;

import junit.framework.Assert;

public final class MyTest extends AbstractTest
{

private static final String ROOT_RESOURCE_PATH = "/testUrl";

@AutoWired
private RestTemplate restTemplate;
private MockRestServiceServer mockServer;


@Before
public void setup(){
this.restTemplate = new RestTemplate();
this.mockServer = MockRestServiceServer.createServer(restTemplate);
}

@Test
public void testPostWithString() {

WebTarget target = getRootTarget(ROOT_RESOURCE_PATH).path("");
String entityBody = new String();
entityBody = " My test data";


final javax.ws.rs.client.Entity<String> entity = javax.ws.rs.client.Entity.entity(entityBody, "text/plain");


mockServer.expect(MockRestRequestMatchers.requestTo(ROOT_RESOURCE_PATH)).andExpect(method(HttpMethod.POST)).andExpect(content().string(entityBody))
.andRespond(withSuccess("resultSuccess", MediaType.TEXT_PLAIN));


final Response response = target.request().post(entity);
Assert.assertNotNull("Response must not be null", response.getEntity());
Assert.assertEquals("Response does not have expected response code", 200, response.getStatus());

System.out.println("Response = " + response.getEntity());

String data = response.readEntity(String.class);

System.out.println("Response = " + data);
if(response.ok() != null)
{
System.out.println("Ok");
}
}
}

更新:

public class SimpleJerseyTest extends ApplicationContextAwareJerseyTest {
private static final String ROOT_RESOURCE_PATH = "/test";

@Override
public void configureApplication(ResourceConfig config) {
config.register(MyApp.class);
config.register(new LoggingFilter(Logger.getAnonymousLogger(), true));
}

@Before
public void setUp() {
try{
((ConfigurableApplicationContext)this.applicationContext).refresh();
super.setUp();
}catch(Exception e){

}
this.mockServer = MockRestServiceServer.createServer(restTemplate);
}

@Autowired
private RestTemplate restTemplate;

private MockRestServiceServer mockServer;

@Test
public void doitOnce() {
WebTarget target = target(ROOT_RESOURCE_PATH);

String entityBody = new String();

final javax.ws.rs.client.Entity<String> entity = javax.ws.rs.client.Entity.entity(entityBody, "text/plain");


mockServer.expect(MockRestRequestMatchers.requestTo(ROOT_RESOURCE_PATH)).andExpect(method(HttpMethod.POST)).andExpect(content().string(entityBody))
.andRespond(withSuccess("resultSuccess", MediaType.TEXT_PLAIN));


final Response response = target.request().post(entity);


System.out.println("Response = " + response.getEntity());

String data = response.readEntity(String.class);

System.out.println("Response = " + data);
if(response.ok() != null)
{
System.out.println("Ok");
}
}
}

我已经添加了bean

src/test/resources/META-INF/applicationContext.xml

<!-- Our REST Web Service client -->
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>

我添加了相同的bean

src/main/resources/META-INF/applicationContext.xml

!-- Our REST Web Service client -->
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>

最佳答案

而不是像这样配置Spring

application.property("contextConfigLocation", "classpath:/META-INF/applicationContext.xml");

您可以使用

application.property("contextConfig", <ApplicationContext>);

这样您就可以拥有 ApplicationContext 的实例,您可以在其中获取 AutowireCapableBeanFactory 。这样,您只需调用 acbf.autowireBean(this) 即可注入(inject)测试类。

这就是我的意思。我测试了它,它适用于简单的情况。但是,如果您尝试注入(inject)的 Bean 不是单例,则效果不会很好,因为将为测试以及您尝试在应用程序代码中注入(inject)的其他位置创建新的单例。

public abstract class ApplicationContextAwareJerseyTest extends JerseyTest {

protected ApplicationContext applicationContext;

@Override
protected final ResourceConfig configure() {
final ResourceConfig config = new ResourceConfig();
configureApplication(config);

this.applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
config.property("contextConfig", this.applicationContext);
final AutowireCapableBeanFactory bf = this.applicationContext.getAutowireCapableBeanFactory();
bf.autowireBean(this);
return config;
}

public final ApplicationContext getApplicationContext() {
return this.applicationContext;
}

protected void configureApplication(ResourceConfig resourceConfig) {};
}

我不确定的一件事是重置将如何进行。我尝试添加

@Before
public void setUp() throws Exception {
((ConfigurableApplicationContext)this.applicationContext).refresh();
super.setUp();
}

进入抽象类,但这似乎没有按预期工作。我使用的测试如下

public class SimpleJerseyTest extends ApplicationContextAwareJerseyTest {


@Path("test")
public static class SimpleResource {
@Autowired
private MessageService service;

@GET
public String getMessage() {
return this.service.getMessage();
}
}

@Override
public void configureApplication(ResourceConfig config) {
config.register(SimpleResource.class);
config.register(new LoggingFilter(Logger.getAnonymousLogger(), true));
}

@Before
public void before() {
assertEquals("Hello World", messageService.getMessage());
}

@Autowired
private MessageService messageService;

@Test
public void doitOnce() {
messageService.setMessage("BOOYAH");
final Response response = target("test").request().get();
assertEquals("BOOYAH", response.readEntity(String.class));
}

@Test
public void doitTwice() {
messageService.setMessage("BOOYAH");
final Response response = target("test").request().get();
assertEquals("BOOYAH", response.readEntity(String.class));
}
}

第二个测试得到的结果是,服务消息的值是默认消息“Hello World”,即使我将消息设置为“BOOYAH”。这告诉我应用程序中存在陈旧的服务,该服务与注入(inject)测试中的服务不同。不过,第一个测试效果很好。如果不重置,第二个测试也可以正常工作,但是每个测试中都会留下修改后的服务,这使得测试不是独立的。

关于java - 使用 Jersey2.0 访问 JerseyTest 中的 springbean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41154225/

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