DefaultMediaTypesMappingCache implements MediaTypesMappingCache { @Override public synchronized Optional<MediaTypes> mediaTypesFor(final String actionName) { if (actionNameToMediaTypesCache == null) { actionNameToMediaTypesCache = mediaTypesMappingCacheInitialiser.initialiseCache(); } return ofNullable(actionNameToMediaTypesCache.get(actionName)); }  @Override synchronized Optional<MediaTypes> mediaTypesFor(final String actionName);  }
@Test public void shouldReturnMediaTypesForActionName() throws Exception { final String actionName = "example.add-recipe"; final MediaType requestMediaType = new MediaType("application/vnd.example.add-recipe+json"); final MediaType responseMediaType = new MediaType("application/vnd.example.recipe-added+json"); when(mediaTypesMappingCacheInitialiser.initialiseCache()).thenReturn(of(actionName, new MediaTypes(requestMediaType, responseMediaType))); final Optional<MediaTypes> mediaTypes = defaultMediaTypesMappingCache.mediaTypesFor(actionName); assertThat(mediaTypes.get().getRequestMediaType().get(), is(requestMediaType)); assertThat(mediaTypes.get().getResponseMediaType().get(), is(responseMediaType)); }
@Test public void shouldInititaliseTheCacheOnlyOnce() throws Exception { final String actionName = "example.add-recipe"; final MediaType requestMediaType = new MediaType("application/vnd.example.add-recipe+json"); final MediaType responseMediaType = new MediaType("application/vnd.example.recipe-added+json"); when(mediaTypesMappingCacheInitialiser.initialiseCache()).thenReturn(of(actionName, new MediaTypes(requestMediaType, responseMediaType))); defaultMediaTypesMappingCache.mediaTypesFor(actionName); defaultMediaTypesMappingCache.mediaTypesFor(actionName); defaultMediaTypesMappingCache.mediaTypesFor(actionName); defaultMediaTypesMappingCache.mediaTypesFor(actionName); defaultMediaTypesMappingCache.mediaTypesFor(actionName); verify(mediaTypesMappingCacheInitialiser, times(1)).initialiseCache(); }
@Test public void shouldReturnEmptyIfNoMappingFound() throws Exception { when(mediaTypesMappingCacheInitialiser.initialiseCache()).thenReturn(new HashMap<>()); final Optional<MediaTypes> mediaTypes = defaultMediaTypesMappingCache.mediaTypesFor("some-unknown-action"); assertThat(mediaTypes.isPresent(), is(false)); }