Back to Repositories

Testing Exception Handling for REST Controllers in conductor-oss

This test suite validates the exception handling and error mapping functionality in Conductor’s REST API layer. It focuses on testing the ApplicationExceptionMapper class which handles HTTP request exceptions and error responses.

Test Coverage Overview

The test suite provides comprehensive coverage of exception handling in the QueueAdminResource REST controller.

Key areas tested include:
  • Server error (5xx) response generation
  • Exception logging behavior
  • REST endpoint error handling for queue updates
  • Error message formatting and propagation

Implementation Analysis

The testing approach uses Spring’s MockMvc framework to simulate HTTP requests and validate error responses. The implementation leverages Mockito for mocking dependencies and verifying logging behavior, with particular attention to exception handling patterns specific to Spring REST controllers.

Notable patterns include:
  • MockMvc standalone setup with ExceptionMapper advice
  • Static mocking of LoggerFactory
  • Request/response content type validation

Technical Details

Testing tools and configuration:
  • JUnit 4 test framework
  • Spring Test MockMvc for REST endpoint testing
  • Mockito for mocking and verification
  • Jackson ObjectMapper for JSON serialization
  • SLF4J logging framework

Best Practices Demonstrated

The test suite exemplifies several testing best practices for exception handling validation.

Notable practices include:
  • Proper test setup and teardown with @Before and @After
  • Isolated testing of exception mapping logic
  • Verification of both HTTP status codes and logging behavior
  • Clean separation of test infrastructure and test logic
  • Comprehensive mock configuration and verification

conductor-oss/conductor

rest/src/test/java/com/netflix/conductor/rest/controllers/ApplicationExceptionMapperTest.java

            
/*
 * Copyright 2024 Conductor Authors.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */
package com.netflix.conductor.rest.controllers;

import java.util.Collections;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import com.netflix.conductor.model.TaskModel;

import com.fasterxml.jackson.databind.ObjectMapper;

import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

public class ApplicationExceptionMapperTest {

    private QueueAdminResource queueAdminResource;

    private MockMvc mockMvc;

    private static MockedStatic<LoggerFactory> mockLoggerFactory;
    private static final Logger logger = mock(Logger.class);

    @Before
    public void before() {
        mockLoggerFactory = Mockito.mockStatic(LoggerFactory.class);
        when(LoggerFactory.getLogger(ApplicationExceptionMapper.class)).thenReturn(logger);

        this.queueAdminResource = mock(QueueAdminResource.class);
        this.mockMvc =
                MockMvcBuilders.standaloneSetup(this.queueAdminResource)
                        .setControllerAdvice(new ApplicationExceptionMapper())
                        .build();
    }

    @After
    public void after() {
        mockLoggerFactory.close();
    }

    @Test
    public void testException() throws Exception {
        var exception = new Exception();
        // pick a method that raises a generic exception
        doThrow(exception).when(this.queueAdminResource).update(any(), any(), any(), any());

        // verify we do send an error response
        this.mockMvc
                .perform(
                        MockMvcRequestBuilders.post(
                                        "/api/queue/update/workflowId/taskRefName/{status}",
                                        TaskModel.Status.SKIPPED)
                                .contentType(MediaType.APPLICATION_JSON)
                                .content(
                                        new ObjectMapper()
                                                .writeValueAsString(Collections.emptyMap())))
                .andDo(print())
                .andExpect(status().is5xxServerError());
        // verify the error was logged
        verify(logger)
                .error(
                        "Error {} url: '{}'",
                        "Exception",
                        "/api/queue/update/workflowId/taskRefName/SKIPPED",
                        exception);
        verifyNoMoreInteractions(logger);
    }
}