我在rest服务中有一个小问题来模拟我的jndi连接。我正在使用Jilse1.9为我的测试创建webservice、rest和mockito。
我的测试代码:
//Mock DATA
db = Mockito.mock(Transactions.class);
Comp comp = Mockito.mock(Comp.class);
Mockito.when(db.createConnection()).thenReturn(connection);
Mockito.when(db.getComponent(connection, comp)).thenReturn(new Comp());
Mockito.doNothing().when(connection).commit();
Mockito.doNothing().when(connection).close();
//Get class at the context
configs = ConfigDatabaseTests.getInstance();
configs.setUpClass();
configs.bindNewSubContext("java:/comp/env/rest");
configs.bindNewInstance(new WSCompRest(db), "java:/comp/env/rest/ws");
webService = (WSCompRest) configs.getTheInstance("java:/comp/env/rest/ws");
String jsonComp = "{\n"
+ " \"comp\": {\n"
+ " \"model\": \"XPTOXXX\",\n"
+ " \"id\": \"TTTT\",\n"
+ " \"type\": \"XXXXXX\"\n"
+ " }\n"
+ "}";
//END Mock DATA
webService.createComp(jsonComp);
此时,我没有任何问题,webService调用并可以调试到方法中。
@POST
@Path("/create")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response createComp(String comp) throws AppException {
Response response = null;
RequestHelper rqHelper = new RequestHelper();
Comp com = new Comp();
try {
//Check parameters
if (!rqHelper.validParameters(comp)) {
throw new AppException(Response.Status.BAD_REQUEST.getStatusCode(), "Invalid json!!");
}
...
Connection conn = db.createConnection();
try {
//Get the type
//WHYYYYYYYYY?
comp = db.getComponent(conn, comp);
...
我不明白为什么getComponent(.)方法返回一个空实例..。有人知道解决办法吗?我已经使用这个策略Transaction.class测试了所有的junit方法,但是我喜欢在高级别上测试代码。
如果我使用spring,那么测试这项服务会更容易吗?我对此表示怀疑,因为在春季,可以使用xml文件注入jndi。
谢谢大家,对不起,我的英语很差。
发布于 2015-08-13 10:47:16
它返回null,因为当您设置模拟时,您指定方法只应该返回一个new Comp()
,如果它是用两个特定的对象调用的(connection
和comp
):
Mockito.when(db.getComponent(connection, comp)).thenReturn(new Comp());
您的comp
变量是测试代码中的一个模拟变量,但在非测试代码中,您使用一个真实的Comp
实例调用该方法。我认为你真正想要的是这个方法在任何时候被调用时返回这个值,你应该这样做;
Mockito.when(db.getComponent(any(Connection.class), any(Comp.class)).thenReturn(new Comp());
https://stackoverflow.com/questions/31985688
复制相似问题