@Test
  public void customRandomizerShouldBeRegisteredInAllBuiltInstances()
      throws BeanPopulationException {
    PopulatorBuilder builder = aNewPopulatorBuilder();

    builder.registerRandomizer(Human.class, String.class, "name", randomizer);

    Populator populator = builder.build();
    Human human = populator.populateBean(Human.class);

    assertThat(human.getName()).isEqualTo(NAME);

    Populator populator2 = builder.build();
    Human human2 = populator2.populateBean(Human.class);

    assertThat(human2.getName()).isNotEqualTo(NAME);
  }
Exemplo n.º 2
0
  @SuppressWarnings("unchecked")
  Map<?, ?> getRandomMap(final Field field) throws IllegalAccessException, BeanPopulationException {
    Class<?> fieldType = field.getType();

    Map<Object, Object> map;
    if (isInterface(field)) {
      map = (Map<Object, Object>) getEmptyTypedMap(fieldType);
    } else {
      try {
        map = (Map<Object, Object>) fieldType.newInstance();
      } catch (InstantiationException e) {
        map = (Map<Object, Object>) objenesis.newInstance(fieldType);
      }
    }

    int size = abs(aNewByteRandomizer().getRandomValue());

    Type fieldGenericType = field.getGenericType();
    Type baseKeyType = String.class;
    Type baseValueType = String.class;
    if (fieldGenericType instanceof ParameterizedType) {
      ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType;
      baseKeyType = parameterizedType.getActualTypeArguments()[0];
      baseValueType = parameterizedType.getActualTypeArguments()[1];
    }
    Class<?> baseKeyTypeClass = (Class<?>) baseKeyType;
    List<?> keyItems = populator.populateBeans(baseKeyTypeClass, size);

    Class<?> baseValueTypeClass = (Class<?>) baseValueType;
    List<?> valueItems = populator.populateBeans(baseValueTypeClass, size);

    for (int index = 0; index < size; index++) {
      map.put(keyItems.get(index), valueItems.get(index));
    }
    return map;
  }