0

Совсем недавно начал использовать unit тестирование. С методами GET и POST, которым в явном виде передаю какие параметры вопросов уже не возникает.

@Test
public void GetEmployeesServletTest() throws Exception {
        HttpServletRequest request = mock(HttpServletRequest.class);
        HttpServletResponse response = mock(HttpServletResponse.class);
  when(request.getParameter("jsonData")).thenReturn(jsonData);
        when(request.getParameter("login")).thenReturn(login);
        PrintWriter writer = new PrintWriter("junit_test_POST_somefile.txt");
        when(response.getWriter()).thenReturn(writer);
        new GetEmployees().doPost(request, response);
}

Нj теперь возникла необходимость проверить работу метода POST сервлета, которому я отдаю JSON таким способом

$.ajax({
            type: 'POST',
            url: 'employees',
            data: JSON.stringify(json_result),
            success: function(data) {
                console.log( "Данные зафиксированы успешно.");
                },
            error: function(data) {
                console.log( "Отправка данных завершилась завершилась ошибкой: ");
        },
            contentType: "application/json",
            dataType: 'json'
        });

сам метод обработки POST пока выглядит так

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        StringBuilder sb = new StringBuilder();
        BufferedReader br = request.getReader();
        String str;
        while( (str = br.readLine()) != null ){
            sb.append(str);
        }
        String output = sb.toString().replace("[", "").replace("]", "");
        try {
            JSONObject jObj = new JSONObject(output);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        System.out.println(output);
}

Как правильно составить unit тест, чтобы проверить приемку JSON в методе POST сервлета?

2
  • важный вопрос - что именно вы тестируете? юнит тест проверяет одну небольшую функцию (метод) и делает это изолированно (минимум зависимостей). что вы хотите проверить? 19 июн 2017 в 13:27
  • для начала хотел отдать в doPost какой-нибудь JSON и проверить реакцию метода doPost: корректно ли он его принимает, правильна ли кодировка и т.д. 19 июн 2017 в 14:03

1 ответ 1

0

Рекомендую разделить получение/отправку результата и его обработку. Вот очень примерный вариант

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json; charset=utf-8");
    String output = converter.convertToString(request.getReader());
    final JSONObject jsonObject = employee.doWork(output);
    response.getOutputStream().print(jsonObject.toString());
}

class Employee

public class Employee {
    public Employee() {
    }

    public JSONObject doWork(String output) {
        return new JSONObject(output);
    }
}

class Util

public class Util {
    public String convertToString(BufferedReader br) throws IOException {
        StringBuilder sb = new StringBuilder();
        String str;
        while( (str = br.readLine()) != null ){
            sb.append(str);
        }
        return sb.toString().replace("[", "").replace("]", "");
    }
}

Соответственно тестировать это все можно отдельными тестами.

Проверяем, что вызываем нужные методы

@Test
public void testPost() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    Util util = mock(Util.class);
    Employee employee = mock(Employee.class);
    GetEmployees sut = new GetEmployees(util, employee);

    sut.doPost(request, response);

    verify(util).convertToString(any());
    verify(employee).doWork(any());
    verify(response).setCharacterEncoding("UTF-8");
    verify(request).setCharacterEncoding("UTF-8");
}

Тестируем другие классы

public class UtilTest {
    @Test
    public void testConvertToString() throws Exception {
        Util sut = new Util();
        BufferedReader bufferedReader = mock(BufferedReader.class);
        when(bufferedReader.readLine()).thenReturn("1", "2", null);

        assertThat(sut.convertToString(bufferedReader), is("12"))
    }
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.