@Before
  public void before() throws KettleException {
    MockitoAnnotations.initMocks(this);

    Mockito.when(parentJob.getLogLevel()).thenReturn(LogLevel.BASIC);
    entry.setParentJob(parentJob);
    entry.setSaveMessage(true);

    Mockito.when(message.getMessageNumber()).thenReturn(1);
    Mockito.when(mailConn.getMessage()).thenReturn(message);

    Mockito.doNothing().when(mailConn).openFolder(Mockito.anyBoolean());
    Mockito.doNothing().when(mailConn).openFolder(Mockito.anyString(), Mockito.anyBoolean());

    Mockito.when(mailConn.getMessagesCount()).thenReturn(1);
  }
  @Test
  @Category(UnitTest.class)
  public void testProcess() throws Exception {
    String params =
        "{\"INPUT1_TYPE\":\"DB\",\"INPUT1\":\"DcGisRoads\",\"INPUT2_TYPE\":\"DB\",\"INPUT2\":\"DcTigerRoads\",";
    params +=
        "\"OUTPUT_NAME\":\"Merged_Roads_e0d\",\"CONFLATION_TYPE\":\"Reference\",\"MATCH_THRESHOLD\":\"0.6\",\"MISS_THRESHOLD\":\"0.6\"}";

    String jobArgs =
        "\"exec\":\"makeconflate\",\"params\":[{\"CONFLATION_TYPE\":\"Reference\"},"
            + "{\"MATCH_THRESHOLD\":\"0.6\"},{\"INPUT1_TYPE\":\"DB\"},{\"MISS_THRESHOLD\":\"0.6\"},"
            + "{\"INPUT2_TYPE\":\"DB\"},{\"INPUT2\":\"DcTigerRoads\"},{\"INPUT1\":\"DcGisRoads\"},"
            + "{\"OUTPUT_NAME\":\"Merged_Roads_e0d\"},{\"IS_BIG\":\"false\"}],\"exectype\":\"make\"},"
            + "{\"class\":\"hoot.services.controllers.job.ReviewResource\",\"method\":\"prepareItemsForReview\",\"params\":"
            + "[{\"isprimitivetype\":\"false\",\"value\":\"Merged_Roads_e0d\",\"paramtype\":\"java.lang.String\"},"
            + "{\"isprimitivetype\":\"true\",\"value\":false,\"paramtype\":\"java.lang.Boolean\"}],\"exectype\":\"reflection\"},"
            + "{\"class\":\"hoot.services.controllers.ingest.RasterToTilesService\",\"method\":\"ingestOSMResourceDirect\",\"params\":"
            + "[{\"isprimitivetype\":\"false\",\"value\":\"Merged_Roads_e0d\",\"paramtype\":\"java.lang.String\"}],\"exectype\":\"reflection\"}]";
    ConflationResource spy = Mockito.spy(new ConflationResource());
    Mockito.doNothing().when((JobControllerBase) spy).postChainJobRquest(anyString(), anyString());
    Response resp = spy.process(params);
    String result = resp.getEntity().toString();
    JSONParser parser = new JSONParser();
    JSONObject o = (JSONObject) parser.parse(result);
    String jobId = o.get("jobid").toString();
    verify(spy).postChainJobRquest(Matchers.matches(jobId), Matchers.endsWith(jobArgs));
  }
 /**
  * Calls {@link #getMockedConnection(Configuration)} and then mocks a few more of the popular
  * {@link ClusterConnection} methods so they do 'normal' operation (see return doc below for
  * list). Be sure to shutdown the connection when done by calling {@link Connection#close()} else
  * it will stick around; this is probably not what you want.
  *
  * @param conf Configuration to use
  * @param admin An AdminProtocol; can be null but is usually itself a mock.
  * @param client A ClientProtocol; can be null but is usually itself a mock.
  * @param sn ServerName to include in the region location returned by this <code>connection</code>
  * @param hri HRegionInfo to include in the location returned when getRegionLocator is called on
  *     the mocked connection
  * @return Mock up a connection that returns a {@link Configuration} when {@link
  *     ClusterConnection#getConfiguration()} is called, a 'location' when {@link
  *     ClusterConnection#getRegionLocation(org.apache.hadoop.hbase.TableName, byte[], boolean)} is
  *     called, and that returns the passed {@link AdminProtos.AdminService.BlockingInterface}
  *     instance when {@link ClusterConnection#getAdmin(ServerName)} is called, returns the passed
  *     {@link ClientProtos.ClientService.BlockingInterface} instance when {@link
  *     ClusterConnection#getClient(ServerName)} is called (Be sure to call {@link
  *     Connection#close()} when done with this mocked Connection.
  * @throws IOException
  */
 public static ClusterConnection getMockedConnectionAndDecorate(
     final Configuration conf,
     final AdminProtos.AdminService.BlockingInterface admin,
     final ClientProtos.ClientService.BlockingInterface client,
     final ServerName sn,
     final HRegionInfo hri)
     throws IOException {
   ConnectionImplementation c = Mockito.mock(ConnectionImplementation.class);
   Mockito.when(c.getConfiguration()).thenReturn(conf);
   Mockito.doNothing().when(c).close();
   // Make it so we return a particular location when asked.
   final HRegionLocation loc = new HRegionLocation(hri, sn);
   Mockito.when(
           c.getRegionLocation(
               (TableName) Mockito.any(), (byte[]) Mockito.any(), Mockito.anyBoolean()))
       .thenReturn(loc);
   Mockito.when(c.locateRegion((TableName) Mockito.any(), (byte[]) Mockito.any())).thenReturn(loc);
   Mockito.when(
           c.locateRegion(
               (TableName) Mockito.any(),
               (byte[]) Mockito.any(),
               Mockito.anyBoolean(),
               Mockito.anyBoolean(),
               Mockito.anyInt()))
       .thenReturn(new RegionLocations(loc));
   if (admin != null) {
     // If a call to getAdmin, return this implementation.
     Mockito.when(c.getAdmin(Mockito.any(ServerName.class))).thenReturn(admin);
   }
   if (client != null) {
     // If a call to getClient, return this client.
     Mockito.when(c.getClient(Mockito.any(ServerName.class))).thenReturn(client);
   }
   NonceGenerator ng = Mockito.mock(NonceGenerator.class);
   Mockito.when(c.getNonceGenerator()).thenReturn(ng);
   Mockito.when(c.getAsyncProcess())
       .thenReturn(
           new AsyncProcess(
               c,
               conf,
               null,
               RpcRetryingCallerFactory.instantiate(conf),
               false,
               RpcControllerFactory.instantiate(conf),
               conf.getInt(HConstants.HBASE_RPC_TIMEOUT_KEY, HConstants.DEFAULT_HBASE_RPC_TIMEOUT),
               conf.getInt(
                   HConstants.HBASE_CLIENT_OPERATION_TIMEOUT,
                   HConstants.DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT)));
   Mockito.when(c.getNewRpcRetryingCallerFactory(conf))
       .thenReturn(
           RpcRetryingCallerFactory.instantiate(
               conf, RetryingCallerInterceptorFactory.NO_OP_INTERCEPTOR, null));
   Mockito.when(c.getRpcControllerFactory()).thenReturn(Mockito.mock(RpcControllerFactory.class));
   Table t = Mockito.mock(Table.class);
   Mockito.when(c.getTable((TableName) Mockito.any())).thenReturn(t);
   ResultScanner rs = Mockito.mock(ResultScanner.class);
   Mockito.when(t.getScanner((Scan) Mockito.any())).thenReturn(rs);
   return c;
 }
 /** Test the draw function */
 @Test
 public void testDraw() {
   SpriteBatch batch = Mockito.mock(SpriteBatch.class);
   Texture texture = null;
   Mockito.doNothing().when(batch).draw(texture, 0, 0);
   cherry.draw(batch);
   verify(batch).draw(texture, 0, 0);
 }
Example #5
0
 @Override
 protected ClusterClient createClient(CommandLineOptions options, String programName)
     throws Exception {
   // mock the returned ClusterClient to disable shutdown and verify shutdown behavior later on
   originalClusterClient = super.createClient(options, programName);
   spiedClusterClient = Mockito.spy(originalClusterClient);
   Mockito.doNothing().when(spiedClusterClient).shutdown();
   return spiedClusterClient;
 }
  @Test
  public final void testDeletePerson() throws Exception {
    Mockito.doNothing().when(peopleServiceMock).deletePerson(Mockito.any(Long.class));

    mockMvc
        .perform(
            MockMvcRequestBuilders.delete("/delPerson/200").contentType(MediaType.APPLICATION_JSON))
        .andDo(MockMvcResultHandlers.print())
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andExpect(MockMvcResultMatchers.content().string(""));
  }
  @Test
  public void testRemove() {
    // arrange
    UserRole userRole = buildUserRole();
    Mockito.doNothing().when(userRoleDao).remove(Matchers.any(UserRole.class));

    // act
    this.userRoleServiceImpl.remove(userRole);

    // assert
    Mockito.verify(userRoleDao).remove(Matchers.any(UserRole.class));
  }
Example #8
0
 @Test
 public void testGetValue() {
   int param = 10;
   int mockedValue = 25;
   // mock void method
   Mockito.doNothing().when(valueRepository).reset();
   // mock method with returning value
   Mockito.when(valueRepository.get(param)).thenReturn(mockedValue);
   int result = showcase.getValue(param);
   assertEquals(mockedValue + 10, result);
   Mockito.verify(valueRepository);
 }
 @Test
 public final void testRemovePersonFromFamily() throws Exception {
   Mockito.doNothing()
       .when(peopleServiceMock)
       .removePersonFromFamily(Mockito.any(Long.class), Mockito.any(Long.class));
   mockMvc
       .perform(
           MockMvcRequestBuilders.get("/del/person/11/family/22")
               .accept(MediaType.APPLICATION_JSON)
               .contentType(MediaType.APPLICATION_JSON))
       .andDo(MockMvcResultHandlers.print())
       .andExpect(MockMvcResultMatchers.status().isOk());
 }
  @Before
  public void setUp() throws Exception {
    this.httpClients = PowerMockito.mock(HttpClients.class);
    this.client = PowerMockito.mock(CloseableHttpClient.class);

    PowerMockito.mockStatic(HttpClients.class);

    PowerMockito.when(HttpClients.createDefault()).thenReturn(client);

    PowerMockito.when(client.execute(any(HttpUriRequest.class))).thenReturn(response);

    Mockito.when(response.getEntity()).thenReturn(null);
    Mockito.doNothing().when(response).close();
  }
  @Test
  public void simulationStatusShouldBeSimulationFinishedAfterInitialising()
      throws DateTimeParseException, FileNotFoundException, IOException {
    // given
    Mockito.doNothing().when(dataProvider).readDataFromFile(Mockito.anyString());
    Mockito.when(dataProvider.getEarliestDate()).thenReturn(LocalDate.parse("2013-12-30"));
    Mockito.when(dataProvider.getLatestDate()).thenReturn(LocalDate.parse("2013-01-02"));

    // when
    stockExchange.initialise("Test");

    // then
    Mockito.verify(dataProvider).readDataFromFile(Mockito.anyString());
    assertEquals(SimulationStatus.SIMULATION_FINISHED, stockExchange.getSimulationStatus());
  }
  @Test
  public void testRemoveById() {
    // arrange
    UUID id = UUID.randomUUID();
    UserRole userRole = buildUserRole();
    userRole.setId(id);
    List<User> users = new ArrayList<User>();
    users.add(userRole.getUser());
    Mockito.when(this.userRoleDao.findById(id)).thenReturn(userRole);
    Mockito.when(this.userService.fetchUsers(Matchers.anyList())).thenReturn(users);
    Mockito.doNothing().when(userRoleDao).remove(Matchers.any(UserRole.class));

    // act
    this.userRoleServiceImpl.removeById(id);

    // assert
    Mockito.verify(userRoleDao).remove(Matchers.any(UserRole.class));
  }
Example #13
0
 /**
  * @param implementation An {@link HRegionInterface} instance; you'll likely want to pass a mocked
  *     HRS; can be null.
  * @return Mock up a connection that returns a {@link org.apache.hadoop.conf.Configuration} when
  *     {@link HConnection#getConfiguration()} is called, a 'location' when {@link
  *     HConnection#getRegionLocation(byte[], byte[], boolean)} is called, and that returns the
  *     passed {@link HRegionInterface} instance when {@link
  *     HConnection#getHRegionConnection(String, int)} is called (Be sure call {@link
  *     HConnectionManager#deleteConnection(org.apache.hadoop.conf.Configuration)} when done with
  *     this mocked Connection.
  * @throws IOException
  */
 private HConnection mockConnection(final HRegionInterface implementation) throws IOException {
   HConnection connection = HConnectionTestingUtility.getMockedConnection(UTIL.getConfiguration());
   Mockito.doNothing().when(connection).close();
   // Make it so we return any old location when asked.
   final HRegionLocation anyLocation =
       new HRegionLocation(HRegionInfo.FIRST_META_REGIONINFO, SN.getHostname(), SN.getPort());
   Mockito.when(
           connection.getRegionLocation(
               (byte[]) Mockito.any(), (byte[]) Mockito.any(), Mockito.anyBoolean()))
       .thenReturn(anyLocation);
   Mockito.when(connection.locateRegion((byte[]) Mockito.any(), (byte[]) Mockito.any()))
       .thenReturn(anyLocation);
   if (implementation != null) {
     // If a call to getHRegionConnection, return this implementation.
     Mockito.when(connection.getHRegionConnection(Mockito.anyString(), Mockito.anyInt()))
         .thenReturn(implementation);
   }
   return connection;
 }
  /**
   * Configures destination node
   *
   * <p>Has mocked layer1, used to confirm packet reception
   */
  private DEECoContainer setupDestinationNode(int id) {
    DEECoContainer node = Mockito.mock(DEECoContainer.class);

    // Configure id for mocked container
    Mockito.when(node.getId()).thenReturn(id);

    // Configure runtime
    Mockito.when(node.getRuntimeFramework()).thenReturn(runtime);

    // Configure Network for mocked container
    Layer1 layer1 =
        Mockito.spy(new Layer1((byte) id, DefaultDataIDSource.getInstance(), scheduler));
    Mockito.doNothing().when(layer1).processL0Packet(Mockito.any(), Mockito.any(), Mockito.any());
    Network network = Mockito.mock(Network.class);
    Mockito.when(network.getL1()).thenReturn(layer1);
    Mockito.when(node.getPluginInstance(Network.class)).thenReturn(network);

    return node;
  }
  @Test
  public void nextDayShouldIncrementDateAndCallGetStockByDate()
      throws DateTimeParseException, FileNotFoundException, IOException {
    // given
    Mockito.doNothing().when(dataProvider).readDataFromFile(Mockito.anyString());
    Mockito.when(dataProvider.getEarliestDate()).thenReturn(LocalDate.parse("2013-01-02"));
    Mockito.when(dataProvider.getLatestDate()).thenReturn(LocalDate.parse("2013-01-07"));
    Mockito.when(dataProvider.getStocksByDate(Mockito.any()))
        .thenReturn(
            Arrays.asList(
                new Stock("TPSA", LocalDate.parse("2013-01-03"), new BigDecimal("12.13"))));
    stockExchange.initialise("Test");

    // when
    stockExchange.nextDay();

    // then
    Mockito.verify(dataProvider).getStocksByDate(LocalDate.parse("2013-01-03"));
    assertEquals(SimulationStatus.SIMULATION_NOT_FINISHED, stockExchange.getSimulationStatus());
  }
 /**
  * Calls {@link #getMockedConnection(Configuration)} and then mocks a few more of the popular
  * {@link HConnection} methods so they do 'normal' operation (see return doc below for list). Be
  * sure to shutdown the connection when done by calling {@link
  * HConnectionManager#deleteConnection(Configuration, boolean)} else it will stick around; this is
  * probably not what you want.
  *
  * @param implementation An {@link HRegionInterface} instance; you'll likely want to pass a mocked
  *     HRS; can be null.
  * @param conf Configuration to use
  * @param implementation An HRegionInterface; can be null but is usually itself a mock.
  * @param sn ServerName to include in the region location returned by this <code>implementation
  *     </code>
  * @param hri HRegionInfo to include in the location returned when getRegionLocation is called on
  *     the mocked connection
  * @return Mock up a connection that returns a {@link Configuration} when {@link
  *     HConnection#getConfiguration()} is called, a 'location' when {@link
  *     HConnection#getRegionLocation(byte[], byte[], boolean)} is called, and that returns the
  *     passed {@link HRegionInterface} instance when {@link
  *     HConnection#getHRegionConnection(String, int)} is called (Be sure call {@link
  *     HConnectionManager#deleteConnection(org.apache.hadoop.conf.Configuration, boolean)} when
  *     done with this mocked Connection.
  * @throws IOException
  */
 public static HConnection getMockedConnectionAndDecorate(
     final Configuration conf,
     final HRegionInterface implementation,
     final ServerName sn,
     final HRegionInfo hri)
     throws IOException {
   HConnection c = HConnectionTestingUtility.getMockedConnection(conf);
   Mockito.doNothing().when(c).close();
   // Make it so we return a particular location when asked.
   final HRegionLocation loc = new HRegionLocation(hri, sn.getHostname(), sn.getPort());
   Mockito.when(
           c.getRegionLocation(
               (byte[]) Mockito.any(), (byte[]) Mockito.any(), Mockito.anyBoolean()))
       .thenReturn(loc);
   Mockito.when(c.locateRegion((byte[]) Mockito.any(), (byte[]) Mockito.any())).thenReturn(loc);
   if (implementation != null) {
     // If a call to getHRegionConnection, return this implementation.
     Mockito.when(c.getHRegionConnection(Mockito.anyString(), Mockito.anyInt()))
         .thenReturn(implementation);
   }
   return c;
 }
Example #17
0
 private void registerServices() throws FalconException {
   mockTimeService = Mockito.mock(AlarmService.class);
   Mockito.when(mockTimeService.getName()).thenReturn("AlarmService");
   Mockito.when(
           mockTimeService.createRequestBuilder(
               Mockito.any(NotificationHandler.class), Mockito.any(ID.class)))
       .thenCallRealMethod();
   mockDataService = Mockito.mock(DataAvailabilityService.class);
   Mockito.when(mockDataService.getName()).thenReturn("DataAvailabilityService");
   Mockito.when(
           mockDataService.createRequestBuilder(
               Mockito.any(NotificationHandler.class), Mockito.any(ID.class)))
       .thenCallRealMethod();
   dagEngine = Mockito.mock(OozieDAGEngine.class);
   Mockito.doNothing().when(dagEngine).resume(Mockito.any(ExecutionInstance.class));
   mockSchedulerService = Mockito.mock(SchedulerService.class);
   Mockito.when(mockSchedulerService.getName()).thenReturn("JobSchedulerService");
   StartupProperties.get().setProperty("dag.engine.impl", MockDAGEngine.class.getName());
   StartupProperties.get()
       .setProperty("execution.service.impl", FalconExecutionService.class.getName());
   dagEngine = Mockito.spy(DAGEngineFactory.getDAGEngine("testCluster"));
   Mockito.when(
           mockSchedulerService.createRequestBuilder(
               Mockito.any(NotificationHandler.class), Mockito.any(ID.class)))
       .thenCallRealMethod();
   mockCompletionService = Mockito.mock(JobCompletionService.class);
   Mockito.when(mockCompletionService.getName()).thenReturn("JobCompletionService");
   Mockito.when(
           mockCompletionService.createRequestBuilder(
               Mockito.any(NotificationHandler.class), Mockito.any(ID.class)))
       .thenCallRealMethod();
   Services.get().register(mockTimeService);
   Services.get().register(mockDataService);
   Services.get().register(mockSchedulerService);
   Services.get().register(mockCompletionService);
 }
Example #18
0
  @Test
  public void testIncluirEventoCorretamente() throws Exception {
    // Arrange
    EventoService mockEventoService = Mockito.mock(EventoService.class);

    EventoCadastroDTO eventoCorreto = new EventoCadastroDTO();
    eventoCorreto.setIdEvento(1L);
    eventoCorreto.setIdUsuario(1L);
    eventoCorreto.setTipoEvento(TipoEvento.DOJO);
    eventoCorreto.setTitulo("TesteMock");
    eventoCorreto.setDescricao("Teste Teste Teste");
    eventoCorreto.setValorEvento(new BigDecimal("13"));
    eventoCorreto.setLocalEvento("CWI São Leopoldo");
    eventoCorreto.setDataInicio("2015/12/30");
    eventoCorreto.setHoraInicio("13:00");
    eventoCorreto.setDataFim("2015/12/30");
    eventoCorreto.setHoraFim("14:00");

    // Act
    // eventoService.incluir(eventoCorreto);

    // Assert
    Mockito.doNothing().when(mockEventoService).incluir(eventoCorreto, null);
  }
  @Test
  public void deliveryAssignmentEmailNotificationTest_Original_Basic() throws MitchellException {
    try {
      APDDeliveryContextDocument aPDDeliveryContextDocument =
          APDDeliveryContextDocument.Factory.parse(
              new File("src/test/resources/APDDeliveryContextDocument.xml"));
      Mockito.doNothing()
          .when(assignmentEmailDeliveryHandler)
          .deliverIAEmail(
              (APDDeliveryContextDocument) Mockito.anyObject(),
              Mockito.anyBoolean(),
              Mockito.anyString());
      asgEmailDelService.deliveryAssignmentEmailNotification(
          aPDDeliveryContextDocument, new ArrayList<String>(), "IA_BASIC_EMAIL_TYPE");
      Mockito.when(cultureDAO.getCultureByCompany(Mockito.anyString())).thenReturn(null);
      Mockito.verify(assignmentEmailDeliveryHandler)
          .deliverIAEmail(aPDDeliveryContextDocument, true, "en-US");

    } catch (XmlException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Example #20
0
 @Before
 public void setUp() throws Exception {
   PowerMockito.mockStatic(DerbyDAOFactory.class);
   Mockito.when(DAOFactory.getInstance()).thenReturn(mockDAO);
   Mockito.doNothing().when(mockReq).setAttribute(Mockito.anyString(), Mockito.anyString());
 }
  @Test
  public void testInitDamage() {
    Princess mockPrincess = Mockito.mock(Princess.class);

    FireControl mockFireControl = Mockito.mock(FireControl.class);
    Mockito.when(mockPrincess.getFireControl()).thenReturn(mockFireControl);

    ToHitData mockToHit = Mockito.mock(ToHitData.class);
    Mockito.when(
            mockFireControl.guessToHitModifierPhysical(
                Mockito.any(Entity.class),
                Mockito.any(EntityState.class),
                Mockito.any(Targetable.class),
                Mockito.any(EntityState.class),
                Mockito.any(PhysicalAttackType.class),
                Mockito.any(IGame.class)))
        .thenReturn(mockToHit);
    Mockito.when(mockToHit.getValue()).thenReturn(7);

    Entity mockShooter = Mockito.mock(BipedMech.class);
    Mockito.when(mockShooter.getId()).thenReturn(1);
    Mockito.when(mockShooter.getWeight()).thenReturn(50.0);

    EntityState mockShooterState = Mockito.mock(EntityState.class);

    Mech mockTarget = Mockito.mock(BipedMech.class);
    Mockito.when(mockTarget.isLocationBad(Mockito.anyInt())).thenReturn(false);
    Mockito.when(mockTarget.getArmor(Mockito.anyInt(), Mockito.eq(false))).thenReturn(10);
    Mockito.when(mockTarget.getArmor(Mockito.anyInt(), Mockito.eq(true))).thenReturn(5);
    Mockito.when(mockTarget.getInternal(Mockito.anyInt())).thenReturn(6);

    EntityState mockTargetState = Mockito.mock(EntityState.class);

    IGame mockGame = Mockito.mock(IGame.class);

    PhysicalInfo testPhysicalInfo = Mockito.spy(new PhysicalInfo(mockPrincess));
    testPhysicalInfo.setShooter(mockShooter);
    testPhysicalInfo.setTarget(mockTarget);
    Mockito.doNothing()
        .when(testPhysicalInfo)
        .setDamageDirection(Mockito.any(EntityState.class), Mockito.any(Coords.class));
    Mockito.doReturn(1).when(testPhysicalInfo).getDamageDirection();

    PhysicalAttackType punch = PhysicalAttackType.LEFT_PUNCH;
    PhysicalAttackType kick = PhysicalAttackType.LEFT_KICK;

    PunchAttackAction punchAction = Mockito.mock(PunchAttackAction.class);
    Mockito.doReturn(punchAction)
        .when(testPhysicalInfo)
        .buildAction(Mockito.eq(punch), Mockito.anyInt(), Mockito.any(Targetable.class));
    Mockito.when(punchAction.toHit(Mockito.any(IGame.class))).thenReturn(mockToHit);

    KickAttackAction kickAction = Mockito.mock(KickAttackAction.class);
    Mockito.doReturn(kickAction)
        .when(testPhysicalInfo)
        .buildAction(Mockito.eq(kick), Mockito.anyInt(), Mockito.any(Targetable.class));
    Mockito.when(kickAction.toHit(Mockito.any(IGame.class))).thenReturn(mockToHit);

    // Test a vanilla punch.
    testPhysicalInfo.setShooter(mockShooter);
    testPhysicalInfo.setAttackType(punch);
    testPhysicalInfo.initDamage(punch, mockShooterState, mockTargetState, true, mockGame);
    Assert.assertEquals(0.583, testPhysicalInfo.getProbabilityToHit(), TOLERANCE);
    Assert.assertEquals(5.0, testPhysicalInfo.getMaxDamage(), TOLERANCE);
    Assert.assertEquals(0.0099, testPhysicalInfo.getExpectedCriticals(), TOLERANCE);
    Assert.assertEquals(0.0, testPhysicalInfo.getKillProbability(), TOLERANCE);
    Assert.assertEquals(5.0, testPhysicalInfo.getExpectedDamageOnHit(), TOLERANCE);

    // Test a vanilla kick.
    testPhysicalInfo.setShooter(mockShooter);
    testPhysicalInfo.setAttackType(kick);
    testPhysicalInfo.initDamage(kick, mockShooterState, mockTargetState, true, mockGame);
    Assert.assertEquals(0.583, testPhysicalInfo.getProbabilityToHit(), TOLERANCE);
    Assert.assertEquals(10.0, testPhysicalInfo.getMaxDamage(), TOLERANCE);
    Assert.assertEquals(0.0099, testPhysicalInfo.getExpectedCriticals(), TOLERANCE);
    Assert.assertEquals(0.0, testPhysicalInfo.getKillProbability(), TOLERANCE);
    Assert.assertEquals(10.0, testPhysicalInfo.getExpectedDamageOnHit(), TOLERANCE);

    // Make the puncher heavier.
    Mockito.when(mockShooter.getWeight()).thenReturn(100.0);
    testPhysicalInfo.setShooter(mockShooter);
    testPhysicalInfo.setAttackType(punch);
    testPhysicalInfo.initDamage(punch, mockShooterState, mockTargetState, true, mockGame);
    Assert.assertEquals(0.583, testPhysicalInfo.getProbabilityToHit(), TOLERANCE);
    Assert.assertEquals(10.0, testPhysicalInfo.getMaxDamage(), TOLERANCE);
    Assert.assertEquals(0.0099, testPhysicalInfo.getExpectedCriticals(), TOLERANCE);
    Assert.assertEquals(0.0, testPhysicalInfo.getKillProbability(), TOLERANCE);
    Assert.assertEquals(10.0, testPhysicalInfo.getExpectedDamageOnHit(), TOLERANCE);

    // Give the target less armor and internals
    Mockito.when(mockTarget.isLocationBad(Mockito.anyInt())).thenReturn(false);
    Mockito.when(mockTarget.getArmor(Mockito.anyInt(), Mockito.eq(false))).thenReturn(6);
    Mockito.when(mockTarget.getArmor(Mockito.anyInt(), Mockito.eq(true))).thenReturn(3);
    Mockito.when(mockTarget.getInternal(Mockito.anyInt())).thenReturn(3);
    Mockito.when(mockShooter.getWeight()).thenReturn(100.0);
    testPhysicalInfo.setShooter(mockShooter);
    testPhysicalInfo.setAttackType(punch);
    testPhysicalInfo.initDamage(punch, mockShooterState, mockTargetState, true, mockGame);
    Assert.assertEquals(0.583, testPhysicalInfo.getProbabilityToHit(), TOLERANCE);
    Assert.assertEquals(10.0, testPhysicalInfo.getMaxDamage(), TOLERANCE);
    Assert.assertEquals(0.5929, testPhysicalInfo.getExpectedCriticals(), TOLERANCE);
    Assert.assertEquals(0.1943, testPhysicalInfo.getKillProbability(), TOLERANCE);
    Assert.assertEquals(10.0, testPhysicalInfo.getExpectedDamageOnHit(), TOLERANCE);

    // Test a non-biped trying to punch.
    testPhysicalInfo.setShooter(Mockito.mock(QuadMech.class));
    testPhysicalInfo.initDamage(punch, mockShooterState, mockTargetState, true, mockGame);
    Assert.assertEquals(0.0, testPhysicalInfo.getProbabilityToHit(), TOLERANCE);
    Assert.assertEquals(0.0, testPhysicalInfo.getMaxDamage(), TOLERANCE);
    Assert.assertEquals(0.0, testPhysicalInfo.getExpectedCriticals(), TOLERANCE);
    Assert.assertEquals(0.0, testPhysicalInfo.getKillProbability(), TOLERANCE);
    Assert.assertEquals(0.0, testPhysicalInfo.getExpectedDamageOnHit(), TOLERANCE);

    // Test not being able to hit.
    Mockito.when(mockToHit.getValue()).thenReturn(13);
    testPhysicalInfo.initDamage(punch, mockShooterState, mockTargetState, true, mockGame);
    Assert.assertEquals(0.0, testPhysicalInfo.getProbabilityToHit(), TOLERANCE);
    Assert.assertEquals(0.0, testPhysicalInfo.getMaxDamage(), TOLERANCE);
    Assert.assertEquals(0.0, testPhysicalInfo.getExpectedCriticals(), TOLERANCE);
    Assert.assertEquals(0.0, testPhysicalInfo.getKillProbability(), TOLERANCE);
    Assert.assertEquals(0.0, testPhysicalInfo.getExpectedDamageOnHit(), TOLERANCE);

    // Test a non-mech.
    testPhysicalInfo.setShooter(Mockito.mock(Tank.class));
    testPhysicalInfo.initDamage(punch, mockShooterState, mockTargetState, true, mockGame);
    Assert.assertEquals(0.0, testPhysicalInfo.getProbabilityToHit(), TOLERANCE);
    Assert.assertEquals(0.0, testPhysicalInfo.getMaxDamage(), TOLERANCE);
    Assert.assertEquals(0.0, testPhysicalInfo.getExpectedCriticals(), TOLERANCE);
    Assert.assertEquals(0.0, testPhysicalInfo.getKillProbability(), TOLERANCE);
    Assert.assertEquals(0.0, testPhysicalInfo.getExpectedDamageOnHit(), TOLERANCE);
  }
  @Before
  public void setUp() throws Exception {
    // Mocks
    ServerManagementContext smCtxt =
        Mockito.mock(ServerManagementContext.class, Mockito.RETURNS_MOCKS);
    ClientHandshakeAckMessage msg = mock(ClientHandshakeAckMessage.class);
    final MessageChannelInternal channel = mock(MessageChannelInternal.class);
    ChannelManager chMgr = mock(ChannelManager.class);
    ChannelStats stats = mock(ChannelStats.class);

    final ArgumentCaptor<ChannelID> cidCollector = ArgumentCaptor.forClass(ChannelID.class);

    when(channel.getChannelID())
        .then(
            new Answer<ChannelID>() {

              @Override
              public ChannelID answer(InvocationOnMock invocation) throws Throwable {
                return cidCollector.getValue();
              }
            });

    final ArgumentCaptor<ChannelManagerEventListener> lsnrCaptor =
        ArgumentCaptor.forClass(ChannelManagerEventListener.class);
    Mockito.doNothing().when(chMgr).addEventListener(lsnrCaptor.capture());

    when(channel.getRemoteAddress()).thenReturn(new TCSocketAddress(8192));
    when(channel.createMessage(TCMessageType.CLIENT_HANDSHAKE_ACK_MESSAGE)).thenReturn(msg);
    when(chMgr.getChannel(cidCollector.capture())).thenReturn(channel);
    when(msg.getChannel()).thenReturn(channel);

    channelMgrMbean = new DSOChannelManagerImpl(chMgr, mock(TCConnectionManager.class), "1.0");
    Mockito.doAnswer(
            new Answer<Object>() {

              @Override
              public Object answer(InvocationOnMock invocation) throws Throwable {
                lsnrCaptor.getValue().channelRemoved(channel);
                return null;
              }
            })
        .when(channel)
        .close();

    when(smCtxt.getChannelManager()).thenReturn((DSOChannelManagerMBean) channelMgrMbean);
    when(stats.getCounter(Matchers.same(channel), Matchers.startsWith("serverMap")))
        .thenReturn(mock(SampledCumulativeCounter.class));
    when(stats.getCounter(
            Matchers.same(channel),
            Matchers.argThat(
                new ArgumentMatcher<String>() {

                  @Override
                  public boolean matches(Object argument) {
                    // Ugly, ugly, ugly
                    String str = (String) argument;
                    return !str.startsWith("serverMap");
                  }
                })))
        .thenReturn(SampledCounter.NULL_SAMPLED_COUNTER);
    when(smCtxt.getChannelStats()).thenReturn(stats);
    mbeanSvr = mock(MBeanServer.class);
    dso =
        new DSO(
            smCtxt,
            mock(ServerConfigurationContext.class),
            mbeanSvr,
            mock(TerracottaOperatorEventHistoryProvider.class));
  }
  @SuppressWarnings("unchecked")
  @Override
  protected void setup(TestContainer container) throws Exception {
    AESEncrypter.generateKey();

    container.addBean(configService = Mockito.mock(APPConfigurationServiceBean.class));
    container.addBean(Mockito.mock(ServiceInstanceDAO.class));

    container.addBean(Mockito.mock(APPConcurrencyServiceBean.class));
    container.addBean(Mockito.mock(ProductProvisioningServiceFactoryBean.class));
    container.addBean(Mockito.mock(APPCommunicationServiceBean.class));

    serviceMock = Mockito.mock(Service.class);
    besDAO = Mockito.mock(BesDAO.class);
    subcriptionService = Mockito.mock(SubscriptionService.class);
    identityService = Mockito.mock(EnhancedIdentityService.class);
    Mockito.doReturn(Arrays.asList(new VOUserDetails()))
        .when(besDAO)
        .getBESTechnologyManagers(Matchers.any(ServiceInstance.class));

    Mockito.doReturn(identityService)
        .when(besDAO)
        .getBESWebService(Matchers.eq(IdentityService.class), Matchers.any(ServiceInstance.class));

    Mockito.doNothing()
        .when(besDAO)
        .setUserCredentialsInContext(
            Matchers.any(BindingProvider.class), Matchers.anyString(),
            Matchers.anyString(), Matchers.anyMap());

    Mockito.doReturn(subcriptionService)
        .when(besDAO)
        .getBESWebService(
            Matchers.eq(SubscriptionService.class), Matchers.any(ServiceInstance.class));

    Mockito.doNothing()
        .when(subcriptionService)
        .completeAsyncSubscription(
            Matchers.anyString(), Matchers.anyString(), Matchers.any(VOInstanceInfo.class));
    Mockito.doNothing()
        .when(subcriptionService)
        .abortAsyncSubscription(
            Matchers.anyString(), Matchers.anyString(), Matchers.anyListOf(VOLocalizedText.class));
    Mockito.doReturn(subcriptionService)
        .when(serviceMock)
        .getPort(Matchers.any(QName.class), Matchers.eq(SubscriptionService.class));

    Mockito.doReturn(serviceMock)
        .when(besDAO)
        .createWebService(Matchers.any(URL.class), Matchers.any(QName.class));

    Mockito.doReturn(identityService)
        .when(serviceMock)
        .getPort(Matchers.any(QName.class), Matchers.eq(IdentityService.class));

    container.addBean(besDAO);
    container.addBean(Mockito.mock(OperationDAO.class));

    container.addBean(Mockito.mock(ServiceInstanceDAO.class));
    container.addBean(Mockito.mock(OperationServiceBean.class));

    container.addBean(authService = Mockito.spy(new APPAuthenticationServiceBean()));
    container.addBean(Mockito.mock(OperationServiceBean.class));

    container.addBean(new APPlatformServiceBean());
    controller = Mockito.mock(APPlatformController.class);
    InitialContext context = new InitialContext();
    context.bind("bss/app/controller/ess.vmware", controller);
    container.addBean(controller);

    besDAO = container.get(BesDAO.class);

    platformService = container.get(APPlatformService.class);

    em = container.getPersistenceUnit("oscm-app");

    defaultAuth = new PasswordAuthentication("user", "password");
  }