@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)); }
@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()); }
@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"); }
@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") ); }
@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)) ); }
@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"); }
@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()); }
@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())) ); }
@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())) ); }
@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(); } } } }
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)); }
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; }
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); }
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()]); }
@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; }
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; }
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; }
@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); }
@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); } } } }
@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)); }
@BeforeEach public void setUp(@Mock Database database) { invocationOnMocks = new CopyOnWriteArrayList<>(); doAnswer(invocationOnMocks::add).when(database).update(any()); Database.setDefault(database); RankingChartConfig config = RankingChartConfig.get(); config.setUserRateFactor(0); config.setLastRankNo(0); config.setLastObfuscatedRate(0); Config.getDefault().store(); }
@Test @DisplayName("of all bots is empty when the game starts") void allBotsStartGameWithEmptyTurnMeter(@Mock UserInterface ui) { Bot bot1 = anyBot(); Bot bot2 = anyBot(); game = new Game(ui, aPlayer().withTeam(bot1, bot2, anyBot()).build(), anyPlayer()); assertEquals(0, bot1.getTurnMeter()); assertEquals(0, bot2.getTurnMeter()); }
@Test @DisplayName("of all bots gets reset to empty when entering a new game") void turnMeterGetsResetBetweenGames(@Mock UserInterface ui) { Bot bot = aBot().withSpeed(30).build(); Player player = aPlayer().withTeam(bot, anyBot(), anyBot()).build(); game = new Game(ui, player, anyPlayer()); game.turn(); assertEquals(30, bot.getTurnMeter()); game = new Game(ui, player, anyPlayer()); assertEquals(0, bot.getTurnMeter()); }
@Test @DisplayName("of a bot gets reduced by 1000 when it reaches or passes 1000") void turnMeterIsReducedBy1000WhenTurnMeterPasses1000(@Mock UserInterface ui) { Bot bot = aBot().withSpeed(501).build(); game = new Game(ui, aPlayer().withTeam(bot, anyBot(), anyBot()).build(), anyPlayer()); game.turn(); assertEquals(501, bot.getTurnMeter(), "Turn Meter should be 0 + 501 => 501"); game.turn(); assertEquals(2, bot.getTurnMeter(), "Turn Meter should be 501 + 501 => 1002 - 1000 => 2"); game.turn(); assertEquals(503, bot.getTurnMeter(), "Turn Meter should be 2 + 501 => 503"); game.turn(); assertEquals(4, bot.getTurnMeter(), "Turn Meter should be 503 + 501 => 1004 - 1000 => 4"); }
@Test() @DisplayName("a winner") void gameEndsWithAWinner(@Mock UserInterface ui) { game = new Game(ui); game.loop(); assertTrue(game.getWinner().isPresent()); }
@Test() @DisplayName("the considerably stronger player winning") void strongerPlayerWinsGame(@Mock UserInterface ui) { Player strongPlayer = aPlayer().withTeam( aBot().withPower(1000).build(), aBot().withPower(1000).build(), aBot().withPower(1000).build()) .build(); Player weakPlayer = aPlayer().withTeam( aBot().withIntegrity(1).build(), aBot().withIntegrity(1).build(), aBot().withIntegrity(1).build()) .build(); game = new Game(ui, strongPlayer, weakPlayer); game.loop(); assertEquals(strongPlayer, game.getWinner().orElseThrow(IllegalStateException::new)); }
@Test() @DisplayName("the considerably faster player winning") void fasterPlayerWinsGame(@Mock UserInterface ui) { Player fastPlayer = aPlayer().withTeam( aBot().withSpeed(200).build(), aBot().withSpeed(300).build(), aBot().withSpeed(400).build()) .build(); Player slowPlayer = aPlayer().withTeam( aBot().withSpeed(20).build(), aBot().withSpeed(30).build(), aBot().withSpeed(40).build()) .build(); game = new Game(ui, slowPlayer, fastPlayer); game.loop(); assertEquals(fastPlayer, game.getWinner().orElseThrow(IllegalStateException::new)); }
@SuppressWarnings("ThrowableResultOfMethodCallIgnored") @Test @DisplayName("when both players chose the same name") void playersCannotHaveSameName(@Mock UserInterface ui) { Player horst = aPlayer().withName("Horst").build(); Player theOtherHorst = aPlayer().withName("Horst").build(); Throwable exception = expectThrows(IllegalArgumentException.class, () -> new Game(ui, horst, theOtherHorst)); assertTrue(exception.getMessage().contains("Horst")); }
private void registerMockitoTestClassMocksAndSpies(ApplicationContextMock applicationContext) { new Mirror().on(myTestClass.getClass()).reflectAll().fields().matching(f -> f.isAnnotationPresent(Mock.class) || f.isAnnotationPresent(Spy.class)).forEach( f -> { try { applicationContext.putOrReplaceBean(f.get(myTestClass)); } catch (IllegalAccessException e) { getLogger().trace(e.getMessage(), e); } } ); }