DefaultSchemaIdMappingCache implements SchemaIdMappingCache { @Override public synchronized Optional<String> schemaIdFor(final MediaType mediaType) { if(mediaTypeToSchemaIdCache == null) { mediaTypeToSchemaIdCache = schemaIdMappingCacheInitialiser.initialiseCache(); } return ofNullable(mediaTypeToSchemaIdCache.get(mediaType)); }  @Override synchronized Optional<String> schemaIdFor(final MediaType mediaType);  }
@Test public void shouldLazyInitialiseTheCache() throws Exception { final MediaType mediaType = new MediaType("application/vnd.example.add-recipe+json"); final String schemaId = "http: final Map<MediaType, String> mediaTypeToSchemaIdMap = of(mediaType, schemaId); when(schemaIdMappingCacheInitialiser.initialiseCache()).thenReturn(mediaTypeToSchemaIdMap); final Optional<String> schemaIdOptional = defaultSchemaIdMappingCache.schemaIdFor(mediaType); assertThat(schemaIdOptional.isPresent(), is(true)); assertThat(schemaIdOptional.get(), is(schemaId)); }
@Test public void shouldInitialiseTheCacheOnlyOnce() throws Exception { final MediaType mediaType = new MediaType("application/vnd.example.add-recipe+json"); final String schemaId = "http: final Map<MediaType, String> mediaTypeToSchemaIdMap = of(mediaType, schemaId); when(schemaIdMappingCacheInitialiser.initialiseCache()).thenReturn(mediaTypeToSchemaIdMap); assertThat(defaultSchemaIdMappingCache.schemaIdFor(mediaType).get(), is(schemaId)); assertThat(defaultSchemaIdMappingCache.schemaIdFor(mediaType).get(), is(schemaId)); assertThat(defaultSchemaIdMappingCache.schemaIdFor(mediaType).get(), is(schemaId)); assertThat(defaultSchemaIdMappingCache.schemaIdFor(mediaType).get(), is(schemaId)); assertThat(defaultSchemaIdMappingCache.schemaIdFor(mediaType).get(), is(schemaId)); assertThat(defaultSchemaIdMappingCache.schemaIdFor(mediaType).get(), is(schemaId)); verify(schemaIdMappingCacheInitialiser, times(1)).initialiseCache(); }
@Test public void shouldReturnEmptyIfNoMediaTypeFoundInCache() throws Exception { final MediaType mediaType = new MediaType("application/vnd.example.add-recipe+json"); when(schemaIdMappingCacheInitialiser.initialiseCache()).thenReturn(new HashMap<>()); final Optional<String> schemaIdOptional = defaultSchemaIdMappingCache.schemaIdFor(mediaType); assertThat(schemaIdOptional.isPresent(), is(false)); }