首页 > 解决方案 > 如何为函数编写junit测试用例

问题描述

我在一个使用字符串重试机制的类中有一个方法。我的代码是:

@Override
    @Retryable(
            value={RuntimeException.class,IOException.class},
            maxAttempts=3,
            backoff=@Backoff(delay=5000)
            )
    public void sampleService(String payLoad, String type) throws HttpException, IOException
             {
        StringRequestEntity requestEntity = null;
        PostMethod postMethod = new PostMethod();
        HttpClient httpclient = new HttpClient();
        InputStream inputStream = null;
        int statusCode;
        BufferedReader br = null;
        String line;
        StringBuffer eventResponse = new StringBuffer();
        String jsonReceive = null;
        try{
            requestEntity = new StringRequestEntity(payLoad, MEDIA_TYPE, FORMAT);
            if (type.equalsIgnoreCase("item")) {
                postMethod = new PostMethod(baseServiceUrl + apiItemServiceUrl);
            } else if (type.equalsIgnoreCase("itemGroup")) {
                postMethod = new PostMethod(baseServiceUrl
                        + apiItemGroupServiceUrl);
            }
            postMethod.setRequestEntity(requestEntity);
            statusCode = httpclient.executeMethod(postMethod);
            log.info("Status code from item service call: " + statusCode);
            if (statusCode != 200) {
                throw new Exception("Error in service call");

            }
            inputStream = postMethod.getResponseBodyAsStream();
            if (null != inputStream) {
                br = new BufferedReader(new InputStreamReader(inputStream,
                        FORMAT));
                for (line = br.readLine(); line != null; line = br.readLine()) {
                    eventResponse = eventResponse.append(line);
                }
            }
        }
        catch(Exception e){
            log.info("Exception occurs " + e);
            throw new RuntimeException(
                    "Exception occurs " + e);
        }
            jsonReceive = eventResponse.toString();
            log.info("JsonReceive from the Service" + jsonReceive);


    }

我想为上述方法编写Junit测试用例,发生异常时应重试多次。有人可以帮我编写测试用例吗?

标签: javaspring-boot

解决方案


如果您使用的是 JUnit,则可以链接 return 语句以在每次调用时具有不同的行为,例如:

when(httpclient.executeMethod(postMethod))
   .thenReturn(errorCode)
   .thenReturn(anotherErrorCode)
   .thenReturn(200)

推荐阅读