REST API的Junit测试用例

时间:2019-07-01 10:48:11

标签: rest api testing junit jersey

我需要为REST API编写一个junit测试用例.Junit测试用例的新手可以帮助我理解和编写具有大量EJB注入的REST API的测试用例。

  1. 编写测试用例时是否需要调用实际的api端点?还是可以模拟服务器以实现API的junit测试用例。
  2. junit测试用例必须显示代码覆盖率,我们如何实现这一目标。

注意:REST应用程序不是基于弹簧的应用程序。

@Path("/watchlistService")
public class sample {

    private static final MCPLogger LOGGER =
            MCPLoggerFactory.getLogger(WatchlistServiceAPI.class);
    @Inject
    private Config configModel;
    @Inject
    private UIConfig configUIModel;

    @EJB
    private CaseDatabaseBean caseDatabase;

    @EJB
    IDBAccess dbAccess;

    @EJB
    WatchlistServiceBean watchlistService;

    @EJB
    private IWatchlistSecurity watchlistSecurity;

    @EJB
    private TrackBean trackBean;
    @EJB
    IWatchlistAccess watchlistAccess;

    @EJB
    private DBModelValidationBean modelValidation;

    @EJB
    private IMVIAuditLogger mviAuditLogger;
    ThreadLocal<Integer> threadLocalValue = new ThreadLocal<>();
    private String getRequestUserName( @Context HttpServletRequest req )
    {
        return req.getUserPrincipal() == null ? "null" :
                req.getUserPrincipal().getName();
    }
    @GET
    @Path("/personattributes")
    @Produces("application/json;charset=utf-8")
    public Response getWatchlistPersonAttributes(@Context HttpServletRequest req) {
        try {
            JSONObject jsonPAttr = new JSONObject();
            JSONArray jsonAttributes = new JSONArray();
            for(WatchlistPersonAttribute attribute :
                    watchlistAccess.getPersonAttributes()) {
                JSONObject jsonAttribute = new JSONObject();
                jsonAttribute.put("name", attribute.name);
                jsonAttribute.put("type", attribute.type.toString());
                jsonAttribute.put("required", attribute.required);
                jsonAttributes.put(jsonAttribute);
            }
            jsonPAttr.put("attributes", jsonAttributes);
            WatchlistPersonDescriptor descriptor =
                    watchlistAccess.getPersonDescriptor();
            jsonPAttr.put("descriptor", descriptor.descriptor);
            JSONArray jsonDescriptorArguments = new JSONArray();
            for(int i = 0; i < descriptor.arguments.length; ++i) {
                jsonDescriptorArguments.put(descriptor.arguments[i]);
            }
            jsonPAttr.put("descriptorArguments", jsonDescriptorArguments);
            return Response.status(200).entity(jsonPAttr.toString()).build();
        } catch (Exception e) {
            return getReturnError("Couldn't retrieve watchlist person attributes: " + e.getMessage());
        }
    }
}

0 个答案:

没有答案