MapNetworkPublisher extends NetworkPublisher<Map<String, T>> { @Override public final void publish(Map<String, T> publishMap) { final Map<String, T> publishMapCopy = ImmutableMap.copyOf(publishMap); if (!keys.isEmpty()) { publishMap.keySet().forEach(key -> checkArgument(keys.contains(key), "Key must be in keys " + "list: " + key)); } checkNamePresent(); if (!publishMapCopy.containsKey("") && !keys.isEmpty()) { doPublish(publishMapCopy); } else if (!publishMapCopy.keySet().isEmpty()) { doPublishSingle(publishMapCopy.get("")); } else { doPublish(); } } protected  MapNetworkPublisher(Set<String> keys); @Override final void publish(Map<String, T> publishMap);  }
@Test public void testPublisherCallsCorrectDoPublishWhenKeysAreProvided() { boolean[] doPublishMapWasCalled = {false}; final DoubleMapPublisher doubleMapPublisher = new DoubleMapPublisher(new HashSet<>(Arrays.asList("Apple"))) { @Override protected void doPublish() { fail(SHOULD_NOT_HAVE_BEEN_CALLED); } @Override protected void doPublish(Map<String, Double> publishMap) { assertTrue("Map should be empty", publishMap.isEmpty()); doPublishMapWasCalled[0] = true; } @Override protected void doPublishSingle(Double value) { fail(SHOULD_NOT_HAVE_BEEN_CALLED); } }; doubleMapPublisher.setName("Don't care"); doubleMapPublisher.publish(new HashMap<>()); assertTrue("doPublish should have been called", doPublishMapWasCalled[0]); }
@Test public void testPublisherCallsCorrectDoPublishWhenNoKeysAreProvided() { boolean[] doPublishNothingWasCalled = {false}; final DoubleMapPublisher doubleMapPublisher = new DoubleMapPublisher(new HashSet<>()) { @Override protected void doPublish() { doPublishNothingWasCalled[0] = true; } @Override protected void doPublish(Map<String, Double> publishMap) { fail(SHOULD_NOT_HAVE_BEEN_CALLED); } @Override protected void doPublishSingle(Double value) { fail(SHOULD_NOT_HAVE_BEEN_CALLED); } }; doubleMapPublisher.setName("Don't care"); doubleMapPublisher.publish(new HashMap<>()); assertTrue("doPublish should have been called", doPublishNothingWasCalled[0]); }
@Test public void testPublisherCallsCorrectDoPublishWhenNoKeysAreProvidedAndMapIsNotEmpty() { final double expected = Math.PI; boolean[] doPublishSingleValueWasCalled = {false}; final DoubleMapPublisher doubleMapPublisher = new DoubleMapPublisher(new HashSet<>()) { @Override protected void doPublish() { fail(SHOULD_NOT_HAVE_BEEN_CALLED); } @Override protected void doPublish(Map<String, Double> publishMap) { fail(SHOULD_NOT_HAVE_BEEN_CALLED); } @Override protected void doPublishSingle(Double value) { doPublishSingleValueWasCalled[0] = true; assertEquals("Should have published the expected value", expected, value, 0.001); } }; doubleMapPublisher.setName("Don't care"); doubleMapPublisher.publish(ImmutableMap.of("", expected)); assertTrue("doPublish with a single value should have been called", doPublishSingleValueWasCalled[0]); }