我正在尝试为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 的模拟在内部创建了服务类的新实例。 我的问题是,如何将模拟的数据访问插入到服务的构造函数中???
任何帮助不胜感激!
通过另一篇文章找到了答案(Resteasy 服务器端模拟框架)
使用以下命令允许我创建服务类的实例并设置数据访问权限:
dispatcher.getRegistry().addSingletonResource(svc);
而不是:
dispatcher.getRegistry().addResourceFactory(factory);
<</div>
div class="one_answers"> 或者,您可以使用testfun-JEE在测试中运行轻量级的JAX-RS(基于RESTeasy和TJWS),并使用testfun-JEE的JaxRsServer junit规则来构建REST请求并断言响应。
testfun-JEE 支持将其他 EJB 以及模拟对象注入到 JAX-RS 资源类中。