[英]Access springbeans in JerseyTest with Jersey2.0
我有弹簧的球衣项目。 现在我的测试来自JerseyTest。 当我尝试做的时候
@AutoWired
RestTemplate restTemplate;
看起来弹簧在球衣测试中不起作用。 我做了一些研究,发现了像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");
}
}
}
我加入了豆子
SRC /测试/资源/ META-INF / applicationContext.xml中
<!-- Our REST Web Service client -->
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>
我添加了相同的bean
SRC /主/资源/ 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)
来注入测试类。
这就是我的意思。 我测试了它,它可以找到简单的情况。 如果您尝试注入的bean 不是单例,那么将无法正常工作,因为将为测试创建新的bean以及您尝试在应用程序代码中注入的其他地方
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"
。 这告诉我应用程序中存在过时服务,这与注入测试的服务不同。 第一次测试工作正常。 如果没有重置,第二次测试也可以正常工作,但是每次测试都会留下修改后的服务,这使得测试不是自包含的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.