testing methods that accept Class arguments
I'm trying to figure out how test a small library I'm working on . Using this simplifie开发者_Python百科d 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?
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".
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.
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.
精彩评论