### Question:
ExistingVisitAssignmentHandler extends BaseEncounterVisitHandler { @Override public void beforeCreateEncounter(Encounter encounter) { if (encounter.getVisit() != null) { return; } List<Patient> patients = new ArrayList<>(); patients.add(encounter.getPatient()); List<Visit> visits = Context.getVisitService().getVisits(null, patients, null, null, null, encounter.getEncounterDatetime(), null, null, null, true, false); if (visits == null) { return; } Date encounterDate = encounter.getEncounterDatetime(); for (Visit visit : visits) { if (visit.getStartDatetime().after(encounterDate)) { continue; } if (visit.getStopDatetime() != null && visit.getStopDatetime().before(encounterDate)) { continue; } if (visit.getLocation() == null || Location.isInHierarchy(encounter.getLocation(), visit.getLocation())) { encounter.setVisit(visit); return; } } }  @Override String getDisplayName(Locale locale); @Override void beforeCreateEncounter(Encounter encounter);  }### Answer:
@Test public void beforeCreateEncounter_shouldAssignExistingVisitIfMatchFound() { Encounter encounter = Context.getEncounterService().getEncounter(1); Assert.assertNull(encounter.getVisit()); new ExistingVisitAssignmentHandler().beforeCreateEncounter(encounter); Assert.assertNotNull(encounter.getVisit()); Assert.assertNotNull(encounter.getVisit().getVisitId()); }
@Test public void beforeCreateEncounter_shouldNotAssignVisitIfNoMatchFound() { Encounter encounter = Context.getEncounterService().getEncounter(1); Assert.assertNull(encounter.getVisit()); Calendar calendar = Calendar.getInstance(); calendar.setTime(encounter.getEncounterDatetime()); calendar.set(Calendar.YEAR, 1900); encounter.setEncounterDatetime(calendar.getTime()); new ExistingVisitAssignmentHandler().beforeCreateEncounter(encounter); Assert.assertNull(encounter.getVisit()); }
@Test public void beforeCreateEncounter_shouldNotAssignVisitWhichStoppedBeforeEncounterDate() { Encounter encounter = Context.getEncounterService().getEncounter(1); Assert.assertNull(encounter.getVisit()); Visit visit = Context.getVisitService().getVisit(1); Calendar calendar = Calendar.getInstance(); calendar.setTime(visit.getStartDatetime()); calendar.set(Calendar.YEAR, 2004); visit.setStopDatetime(calendar.getTime()); Context.getVisitService().saveVisit(visit); new ExistingVisitAssignmentHandler().beforeCreateEncounter(encounter); Assert.assertNull(encounter.getVisit()); }