JUnit Web服务测试用例

时间:2017-07-10 06:09:29

标签: java eclipse web-services rest junit

我需要使用JUnit测试用例在Eclipse中测试我的REST Web服务。我该怎么办?它是否与普通的Java类测试用例类似。

服务:

@Path("/regionService")
public class RegionService {

@GET
@Path("getRegions")
@Produces(MediaType.APPLICATION_JSON)
public String getRegions(@QueryParam("parentTenancyID") int parentTenancyID) throws CustomFault{
    String result = null;
    RegionServiceImpl implObj = new RegionServiceImpl();
    if(parentTenancyID!=0){
        try{
            result = implObj.getRegionServiceDetails(parentTenancyID);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    return result;
   }
}

实现:

    public class RegionServiceImpl {
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public String getRegionServiceDetails(int parentTenancyID) {

    String result = null;
    Logger fLogger = FatalLoggerClass.logger;
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();
    String regionQ = "select a.tenancy_id, a.tenancy_name from TenancyEntity a where Parent_Tenancy_ID=" +parentTenancyID+" ";
    Query query = session.createQuery(regionQ);

    try{
        Iterator iterator = query.list().iterator();
        Object[] resultQ = null;
        HashMap<Integer,String> regionMap = new HashMap<Integer,String>();
        JSONObject jsonObj = null;
        JSONArray jsonArray = new JSONArray();
        jsonObj = new JSONObject();
        while(iterator.hasNext()){
            resultQ = (Object[]) iterator.next();
            int tenancyId = (Integer) resultQ[0];
            String TenancyName =  (String) resultQ[1];
            regionMap.put(tenancyId, TenancyName);
        }
        jsonObj.putAll(regionMap);
        jsonArray.add(jsonObj);
        result = jsonArray.toString();

    }catch(Exception e){
        fLogger.fatal("Exception :"+e);
    }finally{
        if(session.getTransaction().isActive()){
            session.getTransaction().commit();
        }if(session.isOpen()){
            session.flush();
            session.close();
        }
    }
    return result;
}
}

我想检查来自服务的JSON响应是否等于预期值。

1 个答案:

答案 0 :(得分:0)

您可以使用JaxRS的WebClient 请参阅以下文档,它将向您展示样品测试

https://cwiki.apache.org/confluence/display/CXF20DOC/JAXRS+Testing