2

I'm trying to figure out how test a small library I'm working on . Using this simplified method as an example:

private int countMappableFields(Class<?> type) {
    int mappableFields = 0;
    Field[] fields = type.getFields();
    for (int i = 0; i < fields.length ; i++) {
        if (FieldHelper.isMappable(fields[i]))
            mappableFields++;               
    }
    return mappableFields;
}

Should I define a couple of classes in separate files and reference them in all my tests? Is there a different approach that will allow to construct an object for each case?

0

3 Answers 3

1

You can define the classes inline in your test class; there's no reason to make separate files for them.

public class TestCase {
    private static class NoFieldClass
    {
    }

    // And so on.

    @Test
    public void shouldFindZeroMappableFieldsInNoFieldClass() {
        assertTrue(0 == countMappableFields(NoFieldClass.class));
    }
}

This keeps your test source code area clean. It will create multiple class files, but at least the inline classes you define will look like "TestCase$NoFieldClass.class" instead of being the top-level "NoFieldClass.class".

Sign up to request clarification or add additional context in comments.

Comments

0

I'd typically just make a private static class inside the test class for that sort of thing. If you have multiple test files needing to do the same sort of thing, you might want to create top level classes instead.

1 Comment

I wouldn't ever make them common, because that then ties the tests together, coupling them when there's likely no reason to other than laziness.
0

Depends on what you're testing for. If you're doing some sort of customized reflection (e.g. FieldHelper is only returning a subset of fields for some reason) you might want to actually test the objects you're going to be using it on) - i.e. actually run your reflection tests on a map<CLass,Integer> where the classes are mapped to the expected values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.