### Question:
IdPopulator { Object populateIfNecessary(Object entity) { Assert.notNull(entity, "Entity may not be null!"); Neo4jPersistentEntity<?> nodeDescription = neo4jMappingContext.getRequiredPersistentEntity(entity.getClass()); IdDescription idDescription = nodeDescription.getIdDescription(); if (!idDescription.isExternallyGeneratedId()) { return entity; } PersistentPropertyAccessor propertyAccessor = nodeDescription.getPropertyAccessor(entity); Neo4jPersistentProperty idProperty = nodeDescription.getRequiredIdProperty(); if (propertyAccessor.getProperty(idProperty) != null) { return entity; } IdGenerator<?> idGenerator; Optional<String> optionalIdGeneratorRef = idDescription.getIdGeneratorRef(); if (optionalIdGeneratorRef.isPresent()) { idGenerator = neo4jMappingContext .getIdGenerator(optionalIdGeneratorRef.get()).orElseThrow(() -> new IllegalStateException( "Id generator named " + optionalIdGeneratorRef.get() + " not found!")); } else { idGenerator = neo4jMappingContext.getOrCreateIdGeneratorOfType(idDescription.getIdGeneratorClass().get()); } propertyAccessor.setProperty(idProperty, idGenerator.generateId(nodeDescription.getPrimaryLabel(), entity)); return propertyAccessor.getBean(); } IdPopulator(Neo4jMappingContext neo4jMappingContext);   }### Answer:
@Test void shouldRejectNullEntity() { IdPopulator idPopulator = new IdPopulator(neo4jMappingContext); Assertions.assertThatIllegalArgumentException().isThrownBy(() -> idPopulator.populateIfNecessary(null)) .withMessage("Entity may not be null!"); }
@Test void shouldIgnoreInternalIdGenerator() { IdDescription toBeReturned = IdDescription.forInternallyGeneratedIds(); doReturn(toBeReturned).when(nodeDescription).getIdDescription(); doReturn(nodeDescription).when(neo4jMappingContext).getRequiredPersistentEntity(Sample.class); IdPopulator idPopulator = new IdPopulator(neo4jMappingContext); Sample sample = new Sample(); assertThat(idPopulator.populateIfNecessary(sample)).isSameAs(sample); verify(nodeDescription).getIdDescription(); verify(neo4jMappingContext).getRequiredPersistentEntity(Sample.class); verifyNoMoreInteractions(nodeDescription, neo4jMappingContext); }
@Test void shouldNotActOnAssignedProperty() { IdPopulator idPopulator = new IdPopulator(new Neo4jMappingContext()); Sample sample = new Sample(); sample.theId = "something"; Sample populatedSample = (Sample) idPopulator.populateIfNecessary(sample); assertThat(populatedSample).isSameAs(sample); assertThat(populatedSample.theId).isEqualTo("something"); }
@Test void shouldInvokeGenerator() { IdPopulator idPopulator = new IdPopulator(new Neo4jMappingContext()); Sample sample = new Sample(); Sample populatedSample = (Sample) idPopulator.populateIfNecessary(sample); assertThat(populatedSample).isSameAs(sample); assertThat(populatedSample.theId).isEqualTo("Not necessary unique."); }