我正在尝试为 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 的模拟在内部创建了服务类的新实例。我的问题是,如何将模拟数据访问插入到服务的构造函数中???
任何帮助表示赞赏!