### Question:
BeanLocator { public <T> T getBeanByPartialName(String partialName, Class<T> beanClass) { Map<String, T> matchingBeansByName = applicationContext.getBeansOfType(beanClass) .entrySet() .stream() .filter(beanAndName -> beanAndName.getKey().contains(partialName)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); return getOnlyOneOrThrow(beanClass.getSimpleName() + "{name: *" + partialName + "*}", matchingBeansByName); } BeanLocator(ApplicationContext applicationContext); T getBean(Class<T> beanClass); T getBeanByPartialName(String partialName, Class<T> beanClass);  }### Answer:
@Test void getBeanByPartialName_returns_when_one_bean_matches() { ApplicationContext applicationContext = mock(ApplicationContext.class); BeanLocator beanLocator = new BeanLocator(applicationContext); when(applicationContext.getBeansOfType(String.class)) .thenReturn(Maps.build(String.class, "someTestBeanName", "testBean", "otherBeanName", "otherBean")); assertThat(beanLocator.getBeanByPartialName("Test", String.class)).isEqualTo("testBean"); }
@Test void getBeanByPartialName_throws_when_no_bean_matches() { ApplicationContext applicationContext = mock(ApplicationContext.class); BeanLocator beanLocator = new BeanLocator(applicationContext); when(applicationContext.getBeansOfType(String.class)) .thenReturn(Collections.emptyMap()); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> beanLocator.getBeanByPartialName("Test", String.class)) .withMessage("No bean matching String{name: *Test*}"); }
@Test void getBeanByPartialName_throws_when_more_than_one_bean_matches() { ApplicationContext applicationContext = mock(ApplicationContext.class); BeanLocator beanLocator = new BeanLocator(applicationContext); when(applicationContext.getBeansOfType(String.class)) .thenReturn(Maps.build(String.class, "testBeanName1", "testBean1", "testBeanName2", "testBean2" )); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> beanLocator.getBeanByPartialName("Bean", String.class)) .withMessage("Multiple beans matching String{name: *Bean*}. Available: testBeanName1, testBeanName2"); }