Skip to content

Creating a custom TestDataProvider

Mixermachine edited this page Oct 5, 2019 · 2 revisions

The TestDataProvider is the heart of the base-test library. It tries to instantiate every class you throw at it. Simpler classes like int or its wrapper Integer are handled by an internal <String, Function> Map.

Example for a seeded approach (taken from TestDataStatics.getSeededPrimitiveMap()):

Map<String, Function<String, Object>> map = new HashMap<>();

map.put(boolean.class.getName(), x -> (x.hashCode() % 2 != 0));
map.put(char.class.getName(), x -> (char) (x.hashCode() % Character.MAX_VALUE));
map.put(byte.class.getName(), x -> (byte) (x.hashCode() % (Byte.MAX_VALUE - Byte.MIN_VALUE) - Byte.MAX_VALUE));
map.put(short.class.getName(), x -> (short) (x.hashCode() %
		(Short.MAX_VALUE - Short.MIN_VALUE) - Short.MAX_VALUE));
map.put(int.class.getName(), String::hashCode);
map.put(long.class.getName(), x -> (long) x.hashCode() << 16);
map.put(float.class.getName(), x -> ((float) x.hashCode()) / 3);
map.put(double.class.getName(), x -> ((double) x.hashCode()) * 2 / 3);

When you encouter an error message like

WARNING: Could not initialize *yourSpecificClass*
Please refer to https://github.com/Mixermachine/base-test/wiki/Creating-a-custom-TestDataProvider to get an idea how to use customMaps to initialize the TestDataProvider

you have to add your own custom mappings for a the class the creation failed for. Example:

TestDataProvider provider = TestDataProvider.getSeededTestDataProvider();
Map<String, Function<String, Object>> map = new HashMap<>();

map.put(*yourSpecificClass*.class.getName(), x -> *yourSpecificClass*.specialInit(x))
provider.addCustomMappings(map);

// Initialize checks with the TestDataProvider you just created.

Try to use the provided seed variable x when every you can to prevent generating equal objects. The seed will be incremeted for each variable the TestDataProvider instantiates but is constant between runs.

Clone this wiki locally