如何使用 mockito 来测试 REST 服务?
我是Java单元测试的新手,我听说Mockito框架非常适合测试目的。
我已经开发了一个REST服务器(CRUD方法),现在我想测试它,但我不知道如何?
更重要的是,我不知道这个测试程序应该如何开始。我的服务器应该在localhost上工作,然后在该URL上进行调用(例如localhost:8888)?
以下是我到目前为止尝试过的方法,但我非常确定这不是正确的方法。
@Test
public void testInitialize() {
RESTfulGeneric rest = mock(RESTfulGeneric.class);
ResponseBuilder builder = Response.status(Response.Status.OK);
builder = Response.status(Response.Status.OK).entity(
"Your schema was succesfully created!");
when(rest.initialize(DatabaseSchema)).thenReturn(builder.build());
String result = rest.initialize(DatabaseSchema).getEntity().toString();
System.out.println("Here: " + result);
assertEquals("Your schema was succesfully created!", result);
}
下面是方法的代码。initialize
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("/initialize")
public Response initialize(String DatabaseSchema) {
/** Set the LogLevel to Info, severe, warning and info will be written */
LOGGER.setLevel(Level.INFO);
ResponseBuilder builder = Response.status(Response.Status.OK);
LOGGER.info("POST/initialize - Initialize the " + user.getUserEmail()
+ " namespace with a database schema.");
/** Get a handle on the datastore itself */
DatastoreService datastore = DatastoreServiceFactory
.getDatastoreService();
datastore.put(dbSchema);
builder = Response.status(Response.Status.OK).entity(
"Your schema was succesfully created!");
/** Send response */
return builder.build();
}
在这个测试用例中,我想向服务器(POST)发送一个Json字符串。如果一切顺利,那么服务器应该回复“您的架构已成功创建!
有人可以帮我吗?