Back to Repositories

Validating Server Configuration Controller Operations in Apollo Config

This test suite validates the ServerConfigController functionality in Apollo’s portal component, focusing on configuration management and validation logic. It ensures proper handling of server configurations through both successful and error scenarios.

Test Coverage Overview

The test suite provides comprehensive coverage of ServerConfigController operations.

Key areas tested include:
  • Portal DB configuration validation
  • Parameter validation for config entries
  • Empty configuration handling
  • Error response validation
Integration points cover REST endpoint testing and database interactions through SQL scripts.

Implementation Analysis

The testing approach utilizes JUnit with Spring Test context and Mockito for service layer isolation. The implementation employs AbstractIntegrationTest as a base class and uses @ActiveProfiles for authorization control.

Notable patterns include:
  • REST template usage for HTTP endpoint testing
  • Mock injection for service layer
  • SQL script execution for test cleanup
  • Exception handling validation

Technical Details

Testing tools and configuration:
  • JUnit 4 test framework
  • Spring Test Context framework
  • Mockito for mocking
  • SQL scripts for database cleanup
  • RestTemplate for HTTP requests
  • Custom AbstractIntegrationTest base class
  • @ActiveProfiles annotation for test configuration

Best Practices Demonstrated

The test suite exemplifies several testing best practices for enterprise applications.

Notable practices include:
  • Proper test isolation using mocks
  • Systematic cleanup after tests
  • Comprehensive error scenario coverage
  • Clear test method naming
  • Effective assertion usage
  • Integration test separation

apolloconfig/apollo

apollo-portal/src/test/java/com/ctrip/framework/apollo/portal/controller/ServerConfigControllerTest.java

            
/*
 * Copyright 2024 Apollo Authors
 *
 * 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
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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.ctrip.framework.apollo.portal.controller;

import com.ctrip.framework.apollo.portal.AbstractIntegrationTest;
import com.ctrip.framework.apollo.portal.entity.po.ServerConfig;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.portal.service.ServerConfigService;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.web.client.HttpClientErrorException;

import java.util.*;

import static org.hamcrest.core.StringContains.containsString;
import static org.junit.Assert.assertEquals;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.when;

/**
 * Created by kezhenxu at 2019/1/14 13:24.
 *
 * @author kezhenxu (kezhenxu at lizhi dot fm)
 */
@ActiveProfiles("skipAuthorization")
public class ServerConfigControllerTest extends AbstractIntegrationTest {
  @Mock
  private ServerConfigService serverConfigService;

  @InjectMocks
  private ServerConfigController serverConfigController;

  @Test
  @Sql(scripts = "/sql/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
  public void shouldSuccessWhenParameterValidForPortalDBConfig() {
    ServerConfig serverConfig = new ServerConfig();
    serverConfig.setKey("validKey");
    serverConfig.setValue("validValue");
    ResponseEntity<ServerConfig> responseEntity = restTemplate.postForEntity(
        url("/server/portal-db/config"), serverConfig, ServerConfig.class
    );
    assertEquals(responseEntity.getBody().getKey(), serverConfig.getKey());
    assertEquals(responseEntity.getBody().getValue(), serverConfig.getValue());
  }

  @Test
  public void shouldFailWhenParameterInvalidForPortalDBConfig() {
    ServerConfig serverConfig = new ServerConfig();
    serverConfig.setKey("  ");
    serverConfig.setValue("valid");
    try {
      restTemplate.postForEntity(
          url("/server/portal-db/config"), serverConfig, ServerConfig.class
      );
      Assert.fail("Should throw");
    } catch (final HttpClientErrorException e) {
      assertThat(
          new String(e.getResponseBodyAsByteArray()),
          containsString("ServerConfig.Key cannot be blank")
      );
    }
    serverConfig.setKey("valid");
    serverConfig.setValue("   ");
    try {
      restTemplate.postForEntity(
          url("/server/portal-db/config"), serverConfig, ServerConfig.class
      );
      Assert.fail("Should throw");
    } catch (final HttpClientErrorException e) {
      assertThat(
          new String(e.getResponseBodyAsByteArray()),
          containsString("ServerConfig.Value cannot be blank")
      );
    }
  }

  @Test
  public void testFindEmpty() {
    when(serverConfigService.findAllPortalDBConfig()).thenReturn(new ArrayList<>());
    when(serverConfigService.findAllConfigDBConfig(Env.DEV)).thenReturn(new ArrayList<>());

    List<ServerConfig> serverConfigList = serverConfigController.findAllPortalDBServerConfig();
    Assert.assertNotNull(serverConfigList);
    Assert.assertEquals(0, serverConfigList.size());

    serverConfigList = serverConfigController.findAllConfigDBServerConfig(Env.DEV.getName());
    Assert.assertNotNull(serverConfigList);
    Assert.assertEquals(0, serverConfigList.size());

  }
}