private void testCreateTestIdentity(final PrincipalKeyCredential PrincipalKeyCredential, Boolean manageIdentities) throws Exception {
    KerberosHelper kerberosHelper = injector.getInstance(KerberosHelper.class);
    KerberosKeytabPrincipalDAO kerberosKeytabPrincipalDAO = injector.getInstance(KerberosKeytabPrincipalDAO.class);
    KerberosKeytabPrincipalEntity kkp = createNiceMock(KerberosKeytabPrincipalEntity.class);
    KeytabPrincipalFindOrCreateResult result = new KeytabPrincipalFindOrCreateResult();
    result.created = true;
    result.kkp = kkp;

    expect(kerberosKeytabPrincipalDAO.findOrCreate(anyObject(), anyObject(), anyObject(), anyObject())).andReturn(result).anyTimes();
    boolean managingIdentities = !Boolean.FALSE.equals(manageIdentities);

    final Map<String, String> kerberosEnvProperties = new HashMap<>();
    kerberosEnvProperties.put(KerberosHelper.KDC_TYPE, "mit-kdc");
    kerberosEnvProperties.put(KerberosHelper.DEFAULT_REALM, "FOOBAR.COM");
    kerberosEnvProperties.put("manage_identities",
        (manageIdentities == null)
            ? null
            : ((manageIdentities) ? "true" : "false"));

    final Config kerberosEnvConfig = createMock(Config.class);
    expect(kerberosEnvConfig.getProperties()).andReturn(kerberosEnvProperties).anyTimes();

    final Map<String, String> krb5ConfProperties = new HashMap<>();

    final Config krb5ConfConfig = createMock(Config.class);
    expect(krb5ConfConfig.getProperties()).andReturn(krb5ConfProperties).anyTimes();

    final Map<String, Object> attributeMap = new HashMap<>();

    final Cluster cluster = createNiceMock(Cluster.class);
    expect(cluster.getDesiredConfigByType("krb5-conf")).andReturn(krb5ConfConfig).anyTimes();
    expect(cluster.getDesiredConfigByType("kerberos-env")).andReturn(kerberosEnvConfig).anyTimes();
    expect(cluster.getDesiredStackVersion()).andReturn(new StackId("HDP-2.2")).anyTimes();

    // This is a STRICT mock to help ensure that the end result is what we want.
    final RequestStageContainer requestStageContainer = createStrictMock(RequestStageContainer.class);

    if (managingIdentities) {
      final Host host = createMockHost("host1");

      expect(host.getHostId()).andReturn(1l).anyTimes();

      expect(cluster.getHosts()).andReturn(Collections.singleton(host)).anyTimes();

      final ServiceComponentHost schKerberosClient = createMock(ServiceComponentHost.class);
      expect(schKerberosClient.getServiceName()).andReturn(Service.Type.KERBEROS.name()).anyTimes();
      expect(schKerberosClient.getServiceComponentName()).andReturn(Role.KERBEROS_CLIENT.name()).anyTimes();
      expect(schKerberosClient.getHostName()).andReturn("host1").anyTimes();
      expect(schKerberosClient.getState()).andReturn(State.INSTALLED).anyTimes();
      expect(schKerberosClient.getHost()).andReturn(host).anyTimes();

      final ServiceComponent serviceComponentKerberosClient = createNiceMock(ServiceComponent.class);
      expect(serviceComponentKerberosClient.getName()).andReturn(Role.KERBEROS_CLIENT.name()).anyTimes();
      expect(serviceComponentKerberosClient.getServiceComponentHosts()).andReturn(Collections.singletonMap("host1", schKerberosClient)).anyTimes();

      final Service serviceKerberos = createNiceMock(Service.class);
      expect(serviceKerberos.getDesiredStackId()).andReturn(new StackId("HDP-2.2")).anyTimes();
      expect(serviceKerberos.getName()).andReturn(Service.Type.KERBEROS.name()).anyTimes();
      expect(serviceKerberos.getServiceComponents())
          .andReturn(Collections.singletonMap(Role.KERBEROS_CLIENT.name(), serviceComponentKerberosClient))
          .anyTimes();

      final Service service1 = createNiceMock(Service.class);
      expect(service1.getDesiredStackId()).andReturn(new StackId("HDP-2.2")).anyTimes();
      expect(service1.getName()).andReturn("SERVICE1").anyTimes();
      expect(service1.getServiceComponents())
          .andReturn(Collections.emptyMap())
          .anyTimes();

      final Service service2 = createNiceMock(Service.class);
      expect(service2.getDesiredStackId()).andReturn(new StackId("HDP-2.2")).anyTimes();
      expect(service2.getName()).andReturn("SERVICE2").anyTimes();
      expect(service2.getServiceComponents())
          .andReturn(Collections.emptyMap())
          .anyTimes();


      expect(cluster.getClusterName()).andReturn("c1").anyTimes();
      expect(cluster.getServices())
          .andReturn(new HashMap<String, Service>() {
            {
              put(Service.Type.KERBEROS.name(), serviceKerberos);
              put("SERVICE1", service1);
              put("SERVICE2", service2);
            }
          })
          .anyTimes();
      expect(cluster.getServiceComponentHosts(Service.Type.KERBEROS.name(), Role.KERBEROS_CLIENT.name()))
          .andReturn(new ArrayList<ServiceComponentHost>() {
            {
              add(schKerberosClient);
            }
          })
          .anyTimes();
      expect(cluster.getCurrentStackVersion())
          .andReturn(new StackId("HDP", "2.2"))
          .anyTimes();
      expect(cluster.getSessionAttributes()).andReturn(attributeMap).anyTimes();

      cluster.setSessionAttribute(anyObject(String.class), anyObject());
      expectLastCall().andAnswer(new IAnswer<Object>() {
        @Override
        public Object answer() throws Throwable {
          Object[] args = getCurrentArguments();
          attributeMap.put((String) args[0], args[1]);
          return null;
        }
      }).anyTimes();

      final Clusters clusters = injector.getInstance(Clusters.class);
      expect(clusters.getHost("host1"))
          .andReturn(host)
          .anyTimes();

      final AmbariManagementController ambariManagementController = injector.getInstance(AmbariManagementController.class);
      expect(ambariManagementController.findConfigurationTagsWithOverrides(cluster, null, null))
          .andReturn(Collections.emptyMap())
          .once();
      expect(ambariManagementController.getRoleCommandOrder(cluster))
          .andReturn(createMock(RoleCommandOrder.class))
          .once();

      final ConfigHelper configHelper = injector.getInstance(ConfigHelper.class);
      expect(configHelper.calculateExistingConfigurations(eq(ambariManagementController), anyObject(Cluster.class), anyObject(), anyObject()))
          .andReturn(new HashMap<String, Map<String, String>>() {
            {
              put("cluster-env", new HashMap<String, String>() {{
                put("kerberos_domain", "FOOBAR.COM");
              }});
            }
          })
          .times(1);

      final KerberosDescriptor kerberosDescriptor = createStrictMock(KerberosDescriptor.class);
      expect(kerberosDescriptor.getProperties()).andReturn(null).once();

      setupKerberosDescriptor(kerberosDescriptor);
      setupStageFactory();

      // Preparation Stage
      expect(requestStageContainer.getLastStageId()).andReturn(-1L).anyTimes();
      expect(requestStageContainer.getId()).andReturn(1L).once();
      requestStageContainer.addStages(EasyMock.anyObject());
      expectLastCall().once();
      // Getting missing keytabs
      expect(requestStageContainer.getLastStageId()).andReturn(-1L).anyTimes();
      expect(requestStageContainer.getId()).andReturn(1L).once();
      requestStageContainer.addStages(EasyMock.anyObject());
      expectLastCall().once();
      // Create Principals Stage
      expect(requestStageContainer.getLastStageId()).andReturn(-1L).anyTimes();
      expect(requestStageContainer.getId()).andReturn(1L).once();

      requestStageContainer.addStages(EasyMock.anyObject());
      expectLastCall().once();
      // Create Keytabs Stage
      expect(requestStageContainer.getLastStageId()).andReturn(-1L).anyTimes();
      expect(requestStageContainer.getId()).andReturn(1L).once();
      requestStageContainer.addStages(EasyMock.anyObject());
      expectLastCall().once();
      // Distribute Keytabs Stage
      expect(requestStageContainer.getLastStageId()).andReturn(-1L).anyTimes();
      expect(requestStageContainer.getId()).andReturn(1L).once();
      requestStageContainer.addStages(EasyMock.anyObject());
      expectLastCall().once();
      // Clean-up/Finalize Stage
      expect(requestStageContainer.getLastStageId()).andReturn(-1L).anyTimes();
      expect(requestStageContainer.getId()).andReturn(1L).once();
      requestStageContainer.addStages(EasyMock.anyObject());
      expectLastCall().once();
    }

    replayAll();

    // Needed by infrastructure
    injector.getInstance(AmbariMetaInfo.class).init();

    Map<String, String> commandParamsStage = new HashMap<>();
    CredentialStoreService credentialStoreService = injector.getInstance(CredentialStoreService.class);
    credentialStoreService.setCredential(cluster.getClusterName(), KerberosHelper.KDC_ADMINISTRATOR_CREDENTIAL_ALIAS,
        PrincipalKeyCredential, CredentialStoreType.TEMPORARY);
    kerberosHelper.createTestIdentity(cluster, commandParamsStage, requestStageContainer);

    verifyAll();

    if (managingIdentities) {
      Assert.assertTrue(commandParamsStage.containsKey("principal_name"));
      Assert.assertEquals("${kerberos-env/service_check_principal_name}@${realm}", commandParamsStage.get("principal_name"));

      Assert.assertTrue(commandParamsStage.containsKey("keytab_file"));
      Assert.assertEquals("${keytab_dir}/kerberos.service_check." + new SimpleDateFormat("MMddyy").format(new Date()) + ".keytab",
          commandParamsStage.get("keytab_file"));
    }
  }
Test that a Kerberos Descriptor that contains a Service with 0 Components does not raise any exceptions.
ambari-server/src/test/java/org/apache/ambari/server/controller/KerberosHelperTest.java