gpt4 book ai didi

带有模拟数据层的 JUnit RESTeasy 服务……我该如何模拟它?

转载 作者:行者123 更新时间:2023-12-05 08:35:08 24 4
gpt4 key购买 nike

我正在尝试为 RESTeasy 网络服务编写 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 Server-side Mock Framework ) 找到了答案

使用以下允许我创建服务类的实例并设置数据访问:

dispatcher.getRegistry().addSingletonResource(svc);

代替:

dispatcher.getRegistry().addResourceFactory(factory);

关于带有模拟数据层的 JUnit RESTeasy 服务……我该如何模拟它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10593394/

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