Skip to content

Tutorial 8. Testing Only Production classes

Osman Shoukry edited this page Jan 17, 2016 · 1 revision

The Problem

If you are creating two parallel folders one for production classes and another for test classes following the same package naming hierarchy, you are likely to end up running Validation against test classes unintentionally.

Typical setup

Example
├─ pom.xml
└─ src
   ├─ main
   │  ├─ java
   │  │  └─ com
   │  │     └─ example
   │  │        └─ SomeClass.java
   │  └─ resources
   └─ test
      └─ java
         └─ com
            └─ example
               └─ SomeClassTest.java

Setting up PojoClassFilter to filter out any code under the test folder. First find out what is the test path where your classes get copied to. For example, if you are using Maven, this path will be test-classes.

public class SomeClassTest {
  private Validator validator;
  private String packageName = "com.example";
  private PojoClassFilter filterTestClasses = new FilterTestClasses();

  @Before
  public void setup() {
    validator = ValidatorBuilder.create()
                      .with(new GetterMustExistRule())
                      .with(new SetterMustExistRule())
                      .with(new SetterTester())
                      .with(new GetterTester())
                      .build();
  }

  @Test
  public void validateProductionClasses() {
    validator.validate(packageName, filterTestClasses);
  }

  private static class FilterTestClasses implements PojoClassFilter {
    public boolean include(PojoClass pojoClass) {
      return !pojoClass.getSourcePath().contains("/test-classes/");
    }
  }
}