我正在尝试为RESTeasy Web服务编写一个JUnit测试用例。我想为此使用RESTeasy MockDispatcherFactory,而不依赖于任何数据访问层。
在我以前的测试用例创作中,我使用Mockito来模拟数据访问,但是我在使用RESTeasy的MockDispatcherFactory时遇到了麻烦......
服务类:
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("")
public class Service {
private StubDao stubDao;
public Service (){
this.stubDao = new StubDao();
}
public Service (StubDao stubDao){
this.stubDao = stubDao;
}
@GET
@Produces(MediaType.TEXT_HTML)
public String get(){
return stubDao.getTheValue();
}
}
数据访问:
public class StubDao {
private String value;
public StubDao(){
}
public String getTheValue(){
//Stubbed Data Access
return value;
}
public void setTheValue(String v){
this.value = v;
}
}
单元测试:
import java.net.URISyntaxException;
import junit.framework.Assert;
import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.mock.MockDispatcherFactory;
import org.jboss.resteasy.mock.MockHttpRequest;
import org.jboss.resteasy.mock.MockHttpResponse;
import org.jboss.resteasy.plugins.server.resourcefactory.POJOResourceFactory;
import org.junit.Test;
public class TestService {
@Test
public void testService() throws URISyntaxException{
POJOResourceFactory factory = new POJOResourceFactory(Service.class);
//I Need to use Mockito to mock the StubDao object!!!
Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
dispatcher.getRegistry().addResourceFactory(factory);
MockHttpRequest request = MockHttpRequest.get("");
MockHttpResponse response = new MockHttpResponse();
//here my exception is thrown
dispatcher.invoke(request, response);
System.out.println(response.getContentAsString());
// but I expect the response to be 404 (which works outside the mock setup
Assert.assertEquals(response.getStatus(), 404);
}
}
通常我会使用Mockito来模拟数据访问,如下所示:
设置模拟
@Before
public void setup() {
StubDao stubDao = new StubDao();
}
定义模拟
when(stubDao.getTheValue()).thenReturn("the mocked value");
然而,RESTeasy的模拟在内部创建了一个新的服务类实例。我的问题是,如何将模拟数据访问插入服务的构造函数???
感谢任何帮助!
答案 0 :(得分:5)
感谢另一篇文章(Resteasy Server-side Mock Framework)
找到了答案使用以下内容允许我创建服务类的实例并设置数据访问:
dispatcher.getRegistry().addSingletonResource(svc);
而不是:
dispatcher.getRegistry().addResourceFactory(factory);
答案 1 :(得分:1)
或者,您可以使用testfun-JEE在测试中运行轻量级JAX-RS(基于RESTeasy和TJWS),并使用testfun-JEE的JaxRsServer junit规则来构建REST请求并声明响应。
testfun-JEE支持将其他EJB以及mockito模拟对象注入到JAX-RS资源类中。