### Question:
FlagService { public Flag addFlag(Flag flag) throws FlagCreatedWithIdException, FlagNameAlreadyExistsException { if (flag.getFlagId() != null) { throw new FlagCreatedWithIdException("flag includes the id " + flag.getFlagId()); } if (flagRepository.findByName(flag.getName()) != null) { throw new FlagNameAlreadyExistsException("there is already a flag with name " + flag.getName()); } return flagRepository.save(flag); } @Autowired  FlagService(FlagRepository flagRepository); List<Flag> getFlags(); Flag getFlag(Long id); Flag addFlag(Flag flag); void removeFlag(Long id); void updateFlag(Flag flag);  }### Answer:
@Test public void canAddFlag() throws FlagCreatedWithIdException, FlagNameAlreadyExistsException { final boolean sticky = randomBoolean(); final Flag newFlag = new Flag(null, randomString(), 10, sticky); final Long generatedId = randomLong(); when(repository.save(newFlag)) .thenReturn(new Flag(generatedId, newFlag.getName(), newFlag.getPortionIn(), sticky)); final Flag savedFlag = flagService.addFlag(newFlag); assertThat(savedFlag.getFlagId(), is(generatedId)); }
@Test public void flagMustComeWithoutId() { final Flag flag = new Flag(randomLong(), randomString(), 10, false); expectException(() -> flagService.addFlag(flag), FlagCreatedWithIdException.class, "flag includes the id", "flag was created successfully"); }
@Test public void flagNamesMustBeUnique() { final String name = randomString(); final Flag newFlag = new Flag(null, name, 10, false); final Flag existingFlag = new Flag(randomLong(), name, 20, false); when(repository.findByName(name)).thenReturn(existingFlag); expectException(() -> flagService.addFlag(newFlag), FlagNameAlreadyExistsException.class, "name", "flag was created successfully"); }