package com.ctrip.framework.apollo.adminservice.controller;

import com.google.gson.Gson;

import com.ctrip.framework.apollo.biz.service.AdminService;
import com.ctrip.framework.apollo.biz.service.AppService;
import com.ctrip.framework.apollo.common.dto.AppDTO;
import com.ctrip.framework.apollo.common.entity.App;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.Sql.ExecutionPhase;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.client.HttpStatusCodeException;

import java.util.Map;

import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;

public class ControllerIntegrationExceptionTest extends AbstractControllerTest {

  @Autowired
  AppController appController;

  @Mock
  AdminService adminService;

  @Autowired
  AppService appService;

  Gson gson = new Gson();

  @Before
  public void setUp() {
    MockitoAnnotations.initMocks(this);
    ReflectionTestUtils.setField(appController, "adminService", adminService);
  }

  private String getBaseAppUrl() {
    return "http://localhost:" + port + "/apps/";
  }

  @Test
  @Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
  public void testCreateFailed() {
    AppDTO dto = generateSampleDTOData();

    when(adminService.createNewApp(any(App.class))).thenThrow(new RuntimeException("save failed"));

    try {
      restTemplate.postForEntity(getBaseAppUrl(), dto, AppDTO.class);
    } catch (HttpStatusCodeException e) {
      @SuppressWarnings("unchecked")
      Map<String, String> attr = gson.fromJson(e.getResponseBodyAsString(), Map.class);
      Assert.assertEquals("save failed", attr.get("message"));
    }
    App savedApp = appService.findOne(dto.getAppId());
    Assert.assertNull(savedApp);
  }

  private AppDTO generateSampleDTOData() {
    AppDTO dto = new AppDTO();
    dto.setAppId("someAppId");
    dto.setName("someName");
    dto.setOwnerName("someOwner");
    dto.setOwnerEmail("someOwner@ctrip.com");
    return dto;
  }
}

@@ -305,24 +305,48 @@
 ntity.App;%0A%0A
+import org.junit.After;%0A
 import org.j
@@ -1039,16 +1039,52 @@
 rvice;%0A%0A
+  private Object realAdminService;%0A%0A
   @Autow
@@ -1084,24 +1084,24 @@
  @Autowired%0A
-
   AppService
@@ -1219,73 +1219,300 @@
 s);%0A
-    ReflectionTestUtils.setField(appController, %22adminService%22, a
+%0A    realAdminService = ReflectionTestUtils.getField(appController, %22adminService%22);%0A%0A    ReflectionTestUtils.setField(appController, %22adminService%22, adminService);%0A  %7D%0A%0A  @After%0A  public void tearDown() throws Exception %7B%0A    ReflectionTestUtils.setField(appController, %22adminService%22, realA
 dmin

fix legacy mock issue