我正在测试我使用Jersey设置的RESTful api.我想用JUnit测试它,同时用Grizzly运行它以提供Http容器.
使用服务器的一般测试工作正常,即发送请求和接收响应等.
api被称为CMSApi,它有一个名为skyService的依赖项,我想模拟出来,所以我只测试了api.所以问题是我如何使用Mockito创建的mockSkyService对象注入CMSApi?相关代码如下:
Grizzly Server启动:
public static HttpServer startServer() {
final ResourceConfig rc = new ResourceConfig().packages("com.sky");
rc.property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);
return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
Run Code Online (Sandbox Code Playgroud)
}
我的JUnit调用上面的start方法:
@Before
public void setUpServer() throws Exception {
// start the server and create the client
server = Main.startServer();
Client client = ClientBuilder.newClient();
target = client.target(Main.BASE_URI);
}
Run Code Online (Sandbox Code Playgroud)
我用的是运行测试@RunWith(MockitoJUnitRunner.class).
以下是测试中的相关对象:
//System Under Test
private CMSApi cmsApi;
//Mock
@Mock private static SkyService mockSkyService;
Run Code Online (Sandbox Code Playgroud)
这是调用的测试方法:
@Test
public void testSaveTile() {
//given
final Invocation.Builder invocationBuilder = target.path(PATH_TILE).request(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON);
Tile tile …Run Code Online (Sandbox Code Playgroud)