java类org.mockito.Mock的实例源码

AnalyticsServiceImplTest.java 文件源码 项目:services-in-one 阅读 30 收藏 0 点赞 0 评论 0
@Test
public void testGetEnergyStatisticsEmptyEnergyList() throws Exception {

    Random rand = new Random();
    int randomNumberOfDays = rand.nextInt(10) + 1;;
    ZonedDateTime startDate =  ZonedDateTime.now();
    ZonedDateTime endDate = startDate.plusDays(randomNumberOfDays);

    new MockUp<AnalyticsServiceImpl>() {
        @mockit.Mock
        List<AnalyticsServiceImpl.Energy> getEnergyList (String start, String end) {
            List<AnalyticsServiceImpl.Energy> emptyList = new ArrayList<>();
            return emptyList;
        }
    };

    List<Double> expected = new ArrayList<>();
    for (int i = 0; i < randomNumberOfDays + 1; i++) {
        expected.add(0.00);
    }

    List<Double> actual =  analyticsService.getEnergyStatistics(startDate, endDate);
    assertEquals(expected.size(), actual.size());
    assertTrue(expected.equals(actual));
}
TurnMeterTest.java 文件源码 项目:kata-botwars 阅读 28 收藏 0 点赞 0 评论 0
@Test
@DisplayName("increases per turn by the speed of the bot")
void turnMeterGetsIncreasedPerTurnBySpeedOfBot(@Mock UserInterface ui) {
    Bot bot1 = aBot().withSpeed(30).build();
    Bot bot2 = aBot().withSpeed(45).build();

    game = new Game(ui, aPlayer().withTeam(bot1, bot2, anyBot()).build(), anyPlayer());

    game.turn();
    assertEquals(30, bot1.getTurnMeter());
    assertEquals(45, bot2.getTurnMeter());

    game.turn();
    assertEquals(60, bot1.getTurnMeter());
    assertEquals(90, bot2.getTurnMeter());
}
AttackTest.java 文件源码 项目:kata-botwars 阅读 28 收藏 0 点赞 0 评论 0
@Test
@DisplayName("is performed when a bot makes its move")
void botAttacksWhenMakingMove(@Mock UserInterface ui) {
    Bot bot = aBot().withSpeed(500).build();
    Bot opponent = aBot().withIntegrity(100).build();

    when(ui.selectTarget(eq(bot), anyListOf(Bot.class))).thenReturn(Optional.of(opponent));

    game = new Game(ui, aPlayer().withTeam(bot, anyBot(), anyBot()).build(),
            aPlayer().withTeam(opponent, anyBot(), anyBot()).build());
    game.turn();
    assertEquals(100, opponent.getIntegrity(), "Bot should not attack in first turn");
    game.turn();
    assertTrue(opponent.getIntegrity() < 100, "Bot should attack and damage opponent in second turn");

}
AttackTest.java 文件源码 项目:kata-botwars 阅读 92 收藏 0 点赞 0 评论 0
@Test
@DisplayName("is only performed against the selected target")
void botAttacksOnlyTheSelectedTarget(@Mock UserInterface ui) {
    Bot bot = aBot().withSpeed(1000).build();
    Bot opponent1 = aBot().withIntegrity(100).build();
    Bot opponent2 = aBot().withIntegrity(100).build();
    Bot opponent3 = aBot().withIntegrity(100).build();

    when(ui.selectTarget(eq(bot), anyListOf(Bot.class))).thenReturn(Optional.of(opponent1));

    game = new Game(ui, aPlayer().withTeam(bot, anyBot(), anyBot()).build(),
            aPlayer().withTeam(opponent1, opponent2, opponent3).build());
    game.turn();
    assertAll(
            () -> assertTrue(opponent1.getIntegrity() < 100),
            () -> assertTrue(opponent2.getIntegrity() == 100, "Opponent 2 should not be attacked"),
            () -> assertTrue(opponent3.getIntegrity() == 100, "Opponent 3 should not be attacked")
    );

}
AttackTest.java 文件源码 项目:kata-botwars 阅读 33 收藏 0 点赞 0 评论 0
@Test
@DisplayName("destroying a bot gets it removed from its team")
void botDestroyedFromAttackIsRemovedFromTeam(@Mock UserInterface ui) {
    Bot bot = aBot().withPower(100).withSpeed(1000).build();
    Bot opponent = aBot().withIntegrity(1).build();

    when(ui.selectTarget(eq(bot), anyListOf(Bot.class))).thenReturn(Optional.of(opponent));

    game = new Game(ui, aPlayer().withTeam(bot, anyBot(), anyBot()).build(),
            aPlayer().withTeam(opponent, anyBot(), anyBot()).build());

    assertEquals(3, opponent.getOwner().getTeam().size());
    game.turn();
    assertAll(
            () -> assertEquals(2, opponent.getOwner().getTeam().size()),
            () -> assertFalse(opponent.getOwner().getTeam().contains(opponent))
    );
}
ContinuousDamageTest.java 文件源码 项目:kata-botwars 阅读 37 收藏 0 点赞 0 评论 0
@Test
@DisplayName("that destroys its target will have that bot removed from its team before it can attack")
void botDestroyedFromContinuousDamageWillBeRemovedBeforeItsAttack(@Mock UserInterface ui) {
    Effect continuousDamage = createEffectFactoryFor(aBot().withPower(9999).build(),
            1, ContinuousDamage.class).newInstance();
    Bot bot = aBot().withIntegrity(1).withStatusEffects(continuousDamage).withPower(100).withSpeed(1000).build();
    Bot target = aBot().withIntegrity(100).build();

    when(ui.selectTarget(eq(bot), anyListOf(Bot.class))).thenReturn(Optional.of(target));

    Game game = new Game(ui, aPlayer().withTeam(bot, anyBot(), anyBot()).build(),
            aPlayer().withTeam(target, anyBot(), anyBot()).build());

    game.turn();

    assertEquals(100, target.getIntegrity(),
            "Bot should have been destroyed by Continuous Damage before is had a chance to attack");

}
StunTest.java 文件源码 项目:kata-botwars 阅读 31 收藏 0 点赞 0 评论 0
@Test
@DisplayName("lets the affected bot miss its next move")
void stunnedBotMissesNextMove(@Mock UserInterface ui) {
    Effect effect = createEffectFactoryFor(anyBot(),
            1, Stun.class).newInstance();
    Bot stunnedBot = aBot().withSpeed(1000).withStatusEffects(effect).build();
    Bot target = aBot().withIntegrity(100).build();

    when(ui.selectTarget(eq(stunnedBot), anyListOf(Bot.class))).thenReturn(Optional.of(target));

    Game game = new Game(ui,
            aPlayer().withTeam(stunnedBot, anyBot(), anyBot()).build(),
            aPlayer().withTeam(target, anyBot(), anyBot()).build());

    game.turn();

    assertEquals(100, target.getIntegrity(), "Stunned bot should not damage opponent bot");
    assertEquals(0, stunnedBot.getEffects().size());

}
GameTest.java 文件源码 项目:kata-botwars 阅读 33 收藏 0 点赞 0 评论 0
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
@Test
@DisplayName("when a player has a team of less than 3 bots")
void cannotCreateGameWithIncompleteTeamSetup(@Mock UserInterface ui) {
    Player playerWithCompleteTeam = aPlayer().withTeam(anyBot(), anyBot(), anyBot()).build();
    Player playerWithIncompleteTeam = aPlayer().withTeam(anyBot(), anyBot()).build();

    Throwable exception = expectThrows(IllegalArgumentException.class,
            () -> new Game(ui, playerWithCompleteTeam, playerWithIncompleteTeam));

    assertAll(
            () -> assertTrue(exception.getMessage().contains(playerWithIncompleteTeam.toString())),
            () -> assertFalse(exception.getMessage().contains(playerWithCompleteTeam.toString()))
    );

}
GameTest.java 文件源码 项目:kata-botwars 阅读 35 收藏 0 点赞 0 评论 0
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
@Test
@DisplayName("when a player has the same bot twice in his team")
void cannotCreateGameWithDuplicateBotInTeam(@Mock UserInterface ui) {
    Bot duplicateBot = anyBot();
    Player playerWithDuplicateBotInTeam = aPlayer().withTeam(duplicateBot, duplicateBot, anyBot()).build();
    Player playerWithValidTeam = aPlayer().withTeam(anyBot(), anyBot(), anyBot()).build();

    Throwable exception = expectThrows(IllegalArgumentException.class,
            () -> new Game(ui, playerWithValidTeam, playerWithDuplicateBotInTeam));

    assertAll(
            () -> assertTrue(exception.getMessage().contains(playerWithDuplicateBotInTeam.toString())),
            () -> assertTrue(exception.getMessage().contains(duplicateBot.toString())),
            () -> assertFalse(exception.getMessage().contains(playerWithValidTeam.toString()))
    );
}
MockBinder.java 文件源码 项目:mosquito-report-api 阅读 33 收藏 0 点赞 0 评论 0
@Override
protected void configure() {
    bindFactory(new InstanceFactory<User>(test.getCurrentUser())).to(User.class);
    bindFactory(new InstanceFactory<Env>(test.getEnv())).to(Env.class);

    for (Field field : fields) {
        if (field.isAnnotationPresent(Mock.class)) {
            try {   
                field.setAccessible(true);
                bindFactory(new InstanceFactory<Object>(field.get(test))).to(field.getType());
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
}
MockitoPrinter.java 文件源码 项目:che 阅读 33 收藏 0 点赞 0 评论 0
default void printInvocationsOnAllMockedFields() {
  new MockitoDebuggerImpl()
      .printInvocations(
          Arrays.asList(this.getClass().getDeclaredFields())
              .stream()
              .filter(
                  field -> {
                    return field.isAnnotationPresent(Mock.class);
                  })
              .map(
                  field -> {
                    try {
                      field.setAccessible(true);
                      return field.get(this);
                    } catch (IllegalArgumentException | IllegalAccessException e) {
                      e.printStackTrace();
                      return null;
                    }
                  })
              .filter(field -> field != null)
              .toArray(Object[]::new));
}
MockitoAfterTestNGMethod.java 文件源码 项目:mockito-cookbook 阅读 33 收藏 0 点赞 0 评论 0
private Set<Object> instanceMocksIn(Object instance, Class<?> clazz) {
    Set<Object> instanceMocks = new HashSet<Object>();
    Field[] declaredFields = clazz.getDeclaredFields();
    for (Field declaredField : declaredFields) {
        if (declaredField.isAnnotationPresent(Mock.class) || declaredField.isAnnotationPresent(Spy.class)) {
            declaredField.setAccessible(true);
            try {
                Object fieldValue = declaredField.get(instance);
                if (fieldValue != null) {
                    instanceMocks.add(fieldValue);
                }
            } catch (IllegalAccessException e) {
                throw new MockitoException("Could not access field " + declaredField.getName());
            }
        }
    }
    return instanceMocks;
}
MockitoAfterTestNGMethod.java 文件源码 项目:astor 阅读 42 收藏 0 点赞 0 评论 0
private Set<Object> instanceMocksIn(Object instance, Class<?> clazz) {
    Set<Object> instanceMocks = new HashSet<Object>();
    Field[] declaredFields = clazz.getDeclaredFields();
    for (Field declaredField : declaredFields) {
        if (declaredField.isAnnotationPresent(Mock.class) || declaredField.isAnnotationPresent(Spy.class)) {
            declaredField.setAccessible(true);
            try {
                Object fieldValue = declaredField.get(instance);
                if (fieldValue != null) {
                    instanceMocks.add(fieldValue);
                }
            } catch (IllegalAccessException e) {
                throw new MockitoException("Could not access field " + declaredField.getName());
            }
        }
    }
    return instanceMocks;
}
MockAnnotationProcessor.java 文件源码 项目:astor 阅读 44 收藏 0 点赞 0 评论 0
public Object process(Mock annotation, Field field) {
    MockSettings mockSettings = Mockito.withSettings();
    if (annotation.extraInterfaces().length > 0) { // never null
        mockSettings.extraInterfaces(annotation.extraInterfaces());
    }
    if ("".equals(annotation.name())) {
        mockSettings.name(field.getName());
    } else {
        mockSettings.name(annotation.name());
    }
    if(annotation.serializable()){
        mockSettings.serializable();
    }

    // see @Mock answer default value
    mockSettings.defaultAnswer(annotation.answer().get());
    return Mockito.mock(field.getType(), mockSettings);
}
DaggerTestInitializer.java 文件源码 项目:injected-test-runner 阅读 32 收藏 0 点赞 0 评论 0
private static Object[] buildConstructorArgs(Object test) throws IllegalAccessException {
    Map<Class<?>, List<Object>> result = new TreeMap<Class<?>, List<Object>>(new SimpleClassComparator());
    for (Field field : test.getClass().getDeclaredFields()) {
        field.setAccessible(true);
        if (field.getAnnotation(Mock.class) != null) {
            if (result.get(field.getType()) == null) {
                result.put(field.getType(), new ArrayList<Object>());
            }
            result.get(field.getType()).add(field.get(test));
        }
    }
    List<Object> combined = new ArrayList<Object>();
    for (List<Object> objects : result.values()) {
        combined.addAll(objects);
    }
    combined.add(new Object());
    return combined.toArray(new Object[result.size()]);
}
MockModuleAnnotationProcessor.java 文件源码 项目:injected-test-runner 阅读 40 收藏 0 点赞 0 评论 0
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    for (Element rootElement : roundEnv.getRootElements()) {
        if (rootElement.getAnnotation(MockModule.class) != null) {
            TypeElement type = (TypeElement) rootElement;
            PackageElement packageElement = (PackageElement) type.getEnclosingElement();
            PendingModule module = new PendingModule(type.getSimpleName() + "MockModule", packageElement.getQualifiedName().toString(), type.getQualifiedName().toString(), getInjectsElement(type));

            for (Element element : type.getEnclosedElements()) {
                if (element.getAnnotation(Mock.class) != null) {
                    TypeMirror fieldType = element.asType();
                    module.addMock(new MockField(fieldType.toString(), element.getSimpleName().toString(), element.getAnnotationMirrors()));
                }
            }

            writeModuleSource(module);
        }
    }
    return true;
}
MockitoExtension.java 文件源码 项目:qpp-conversion-tool 阅读 37 收藏 0 点赞 0 评论 0
private String getMockName(Parameter parameter) {
    String explicitMockName = parameter.getAnnotation(Mock.class).name().trim();
    if (!explicitMockName.isEmpty()) {
        return explicitMockName;
    }
    else if (parameter.isNamePresent()) {
        return parameter.getName();
    }
    return null;
}
MockitoExtension.java 文件源码 项目:mastering-junit5 阅读 35 收藏 0 点赞 0 评论 0
private String getMockName(Parameter parameter) {
    String explicitMockName = parameter.getAnnotation(Mock.class).name()
            .trim();
    if (!explicitMockName.isEmpty()) {
        return explicitMockName;
    } else if (parameter.isNamePresent()) {
        return parameter.getName();
    }
    return null;
}
MockitoExtension.java 文件源码 项目:mastering-junit5 阅读 32 收藏 0 点赞 0 评论 0
private String getMockName(Parameter parameter) {
    String explicitMockName = parameter.getAnnotation(Mock.class).name()
            .trim();
    if (!explicitMockName.isEmpty()) {
        return explicitMockName;
    } else if (parameter.isNamePresent()) {
        return parameter.getName();
    }
    return null;
}
MockitoExtension.java 文件源码 项目:intellij-spring-assistant 阅读 33 收藏 0 点赞 0 评论 0
private String getMockName(Parameter parameter) {
  String explicitMockName = parameter.getAnnotation(Mock.class).name().trim();
  if (!explicitMockName.isEmpty()) {
    return explicitMockName;
  } else if (parameter.isNamePresent()) {
    return parameter.getName();
  }
  return null;
}
MockitoExtension.java 文件源码 项目:open-kilda 阅读 38 收藏 0 点赞 0 评论 0
private String getMockName(Parameter parameter) {
    String explicitMockName = parameter.getAnnotation(Mock.class).name().trim();
    if (!explicitMockName.isEmpty()) {
        return explicitMockName;
    } else if (parameter.isNamePresent()) {
        return parameter.getName();
    }
    return null;
}
MockParameterFactory.java 文件源码 项目:junit5-extensions 阅读 120 收藏 0 点赞 0 评论 0
@Override
public Object getParameterValue(Parameter parameter) {
  Mock annotation = parameter.getAnnotation(Mock.class);
  MockSettings settings = Mockito.withSettings();
  if (annotation.extraInterfaces().length > 0) {
    settings.extraInterfaces(annotation.extraInterfaces());
  }
  if (annotation.serializable()) {
    settings.serializable();
  }
  settings.name(annotation.name().isEmpty() ? parameter.getName() : annotation.name());
  settings.defaultAnswer(annotation.answer());

  return Mockito.mock(parameter.getType(), settings);
}
MockitoExtension.java 文件源码 项目:selenium-jupiter 阅读 35 收藏 0 点赞 0 评论 0
private String getMockName(Parameter parameter) {
    String explicitMockName = parameter.getAnnotation(Mock.class).name()
            .trim();
    if (!explicitMockName.isEmpty()) {
        return explicitMockName;
    } else if (parameter.isNamePresent()) {
        return parameter.getName();
    }
    return null;
}
MockitoExtension.java 文件源码 项目:Mastering-Software-Testing-with-JUnit-5 阅读 34 收藏 0 点赞 0 评论 0
private String getMockName(Parameter parameter) {
    String explicitMockName = parameter.getAnnotation(Mock.class).name()
            .trim();
    if (!explicitMockName.isEmpty()) {
        return explicitMockName;
    } else if (parameter.isNamePresent()) {
        return parameter.getName();
    }
    return null;
}
MockitoExtension.java 文件源码 项目:Mastering-Software-Testing-with-JUnit-5 阅读 41 收藏 0 点赞 0 评论 0
private String getMockName(Parameter parameter) {
    String explicitMockName = parameter.getAnnotation(Mock.class).name()
            .trim();
    if (!explicitMockName.isEmpty()) {
        return explicitMockName;
    } else if (parameter.isNamePresent()) {
        return parameter.getName();
    }
    return null;
}
MockitoExtension.java 文件源码 项目:jwebassembly 阅读 38 收藏 0 点赞 0 评论 0
private String getMockName(Parameter parameter) {
    String explicitMockName = parameter.getAnnotation(Mock.class).name().trim();
    if (!explicitMockName.isEmpty()) {
        return explicitMockName;
    } else if (parameter.isNamePresent()) {
        return parameter.getName();
    }
    return null;
}
MockitoExtension.java 文件源码 项目:vertx-acme4j 阅读 37 收藏 0 点赞 0 评论 0
private String getMockName(Parameter parameter) {
    String explicitMockName = parameter.getAnnotation(Mock.class).name().trim();
    if (!explicitMockName.isEmpty()) {
        return explicitMockName;
    }
    else if (parameter.isNamePresent()) {
        return parameter.getName();
    }
    return null;
}
TestBinder.java 文件源码 项目:rest-jersey-utils 阅读 35 收藏 0 点赞 0 评论 0
@Override
protected void configure() {
    Set<Field> f = ReflectionUtils.getAllFields(instanceToReadMocksFrom.getClass());
    for (Field field : f) {
        if (field.getAnnotation(Mock.class) != null || field.getAnnotation(Spy.class) != null) {
            try {
                field.setAccessible(true);
                bindReflectedInstance(field.get(instanceToReadMocksFrom), field.getType());
            } catch (Exception e) {
                throw new IllegalArgumentException("Unable to bind mock field " + field.getName() + " from "
                        + instanceToReadMocksFrom.getClass().getName(), e);
            }
        }
    }
}
AnalyticsServiceImplTest.java 文件源码 项目:services-in-one 阅读 30 收藏 0 点赞 0 评论 0
@Test
public void testGetEnergyStatistics2Days() throws Exception {

    ZoneId zoneId = ZoneId.of("Asia/Singapore");
    ZonedDateTime startDate =  ZonedDateTime.of(2017, 03, 28, 0, 0, 0, 0, zoneId);
    ZonedDateTime endDate = ZonedDateTime.of(2017, 03, 29, 0, 0, 0, 0, zoneId);


    new MockUp<AnalyticsServiceImpl>() {
        @mockit.Mock
        List<AnalyticsServiceImpl.Energy> getEnergyList (String start, String end) {
            List<AnalyticsServiceImpl.Energy> energyList = new ArrayList<>();

            AnalyticsServiceImpl.Energy energy1 = new AnalyticsServiceImpl.Energy("nclenergy.201703280000.out");
            energy1.setUsage(200.0);
            energyList.add(energy1);

            AnalyticsServiceImpl.Energy energy2 = new AnalyticsServiceImpl.Energy("nclenergy.201703290000.out");
            energy2.setUsage(300.0);
            energyList.add(energy2);

            AnalyticsServiceImpl.Energy energy3 = new AnalyticsServiceImpl.Energy("nclenergy.201703300000.out");
            energy3.setUsage(450.0);
            energyList.add(energy3);

            return energyList;
        }
    };

    List<Double> expected = new ArrayList<>();
    expected.add(100.0);
    expected.add(150.0);

    List<Double> actual =  analyticsService.getEnergyStatistics(startDate, endDate);
    assertEquals(expected.size(), actual.size());
    assertTrue(expected.equals(actual));
}
MockitoExtension.java 文件源码 项目:logbook-kai-plugins 阅读 38 收藏 0 点赞 0 评论 0
private String getMockName(Parameter parameter) {
    String explicitMockName = parameter.getAnnotation(Mock.class).name().trim();
    if (!explicitMockName.isEmpty()) {
        return explicitMockName;
    }
    else if (parameter.isNamePresent()) {
        return parameter.getName();
    }
    return null;
}


问题


面经


文章

微信
公众号

扫码关注公众号