模拟jndi连接

时间:2015-08-13 10:30:00

标签: rest junit jersey mockito

我在休息服务时模拟我的jndi连接有点问题。我使用jersey 1.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(...)返回一个null实例...任何人都知道这个的解决方案? 我已使用此策略https://blogs.oracle.com/randystuph/entry/injecting_jndi_datasources_for_junit测试了所有Transaction.class方法,但我喜欢在高级别测试代码。

如果我使用弹簧,那么球衣更容易测试服务吗?我对此提出质疑,因为在春天可以使用xml文件注入jndi。

谢谢大家,抱歉我的英文不好:( 此致

1 个答案:

答案 0 :(得分:1)

它返回null,因为在设置模拟时,您指定该方法只应返回new Comp(),如果使用2个特定对象(connectioncomp)调用它: / p>

Mockito.when(db.getComponent(connection, comp)).thenReturn(new Comp());

您的comp变量是测试代码中的模拟,但在非测试代码中,您使用真实的Comp实例调用该方法。我认为你真正想要的是方法在调用时返回这个值,你应该做这样的事情;

Mockito.when(db.getComponent(any(Connection.class), any(Comp.class)).thenReturn(new Comp());