Back to Repositories

Validating @BindDimen Type Constraints in ButterKnife

This test suite validates the dimension binding functionality in ButterKnife’s annotation processing system. It focuses on type validation for the @BindDimen annotation, ensuring proper data type constraints are enforced during compile-time.

Test Coverage Overview

The test coverage focuses on validating type constraints for the @BindDimen annotation in ButterKnife.

Key areas tested include:
  • Type validation for dimension bindings
  • Compile-time error detection for invalid types
  • Annotation processor error messaging

Implementation Analysis

The testing approach uses compile-time verification through the ButterKnifeProcessor. It employs Google’s compile-testing framework to validate annotation processing behavior, specifically checking error cases when incorrect types are used with @BindDimen.

The test implements:
  • Source code generation for test cases
  • Compilation result assertion
  • Error message verification

Technical Details

Testing tools and configuration:
  • JUnit test framework
  • Google Truth assertion library
  • JavaFileObjects for source generation
  • ButterKnifeProcessor for annotation processing
  • Compile-testing framework for processor validation

Best Practices Demonstrated

The test exemplifies several testing best practices in annotation processor validation.

Notable practices include:
  • Isolated test cases for specific validation rules
  • Clear error message verification
  • Precise line number checking for compilation errors
  • Clean test method naming that describes the validation rule

jakewharton/butterknife

butterknife-runtime/src/test/java/butterknife/BindDimenTest.java

            
package butterknife;

import butterknife.compiler.ButterKnifeProcessor;
import com.google.testing.compile.JavaFileObjects;
import javax.tools.JavaFileObject;
import org.junit.Test;

import static com.google.common.truth.Truth.assertAbout;
import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource;

public final class BindDimenTest {
  @Test public void typeMustBeIntOrFloat() {
    JavaFileObject source = JavaFileObjects.forSourceString("test.Test", ""
        + "package test;\n"
        + "import butterknife.BindDimen;\n"
        + "public class Test {\n"
        + "  @BindDimen(1) String one;\n"
        + "}"
    );

    assertAbout(javaSource()).that(source)
        .processedWith(new ButterKnifeProcessor())
        .failsToCompile()
        .withErrorContaining("@BindDimen field type must be 'int' or 'float'. (test.Test.one)")
        .in(source).onLine(4);
  }
}