private String getBeanName(ConfigurableListableBeanFactory beanFactory,
                             BeanDefinitionRegistry registry, MockDefinition mockDefinition,
                             BeanDefinition beanDefinition) {
    if (StringUtils.hasLength(mockDefinition.getName())) {
      return mockDefinition.getName();
    }
    Set<String> existingBeans = getExistingBeans(beanFactory, mockDefinition);
    if (existingBeans.isEmpty()) {
      return this.beanNameGenerator.generateBeanName(beanDefinition, registry);
    }
    if (existingBeans.size() == 1) {
      return existingBeans.iterator().next();
    }
    String primaryCandidate = determinePrimaryCandidate(registry, existingBeans, mockDefinition.getTypeToMock());
    if (primaryCandidate != null) {
      return primaryCandidate;
    }
    throw new IllegalStateException(
      "Unable to register mock bean " + mockDefinition.getTypeToMock()
        + " expected a single matching bean to replace but found "
        + existingBeans);
  }
Factory method used by defined beans to actually create the mock.

@param mockDefinition the mock definition
@param name the bean name
@return the mock instance
spock-spring/src/main/java/org/spockframework/spring/mock/SpockMockPostprocessor.java