#3934: MaxLengthTextFieldTest.java

projectforge-wicket/src/test/java/org/projectforge/web/wicket/components/MaxLengthTextFieldTest.java

Path: projectforge-wicket/src/test/java/org/projectforge/web/wicket/components/MaxLengthTextFieldTest.java · Lines: 55 · Extends: AbstractTestBase

Purpose: Unit test for MaxLengthTextField.getMaxLength() — a Wicket utility that extracts @Column(length=N) from JPA entity annotations and sets the HTML maxlength attribute on form inputs. Bridges JPA → Wicket → HTML validation.

Source: GitHub

55 lines · 26 code · 22 comments · 7 blank
CommitMessage
9ebb885222016-07-18 Initial commit

The JPA→HTML bridge — why this test matters

PropertyModel<String> model = new PropertyModel<>(new PFUserDO(), "username");
assertInteger(255, MaxLengthTextField.getMaxLength(model));      // From @Column(length=255)
assertInteger(255, MaxLengthTextField.getMaxLength(model, 300)); // Override ignored (DB wins)
assertInteger(100, MaxLengthTextField.getMaxLength(model, 100)); // Manual override wins (100 < 255)

model = new PropertyModel<>(new BaseSearchFilter(), "searchString");
assertNull(MaxLengthTextField.getMaxLength(model));              // No @Column = no maxlength
assertInteger(100, MaxLengthTextField.getMaxLength(model, 100)); // Manual override

assertNull(MaxLengthTextField.getMaxLength(Model.of("test")));   // Plain model = no maxlength

The algorithm under test: getMaxLength(propertyModel, manualMaxLength) follows this logic:

  1. Extract the property name from the Wicket PropertyModel (e.g., "username")
  2. Find the corresponding JPA entity class and field
  3. Read the @Column(length = N) annotation
  4. If a manual maxLength is provided AND it's smaller than the DB column length, use the manual value (HTML validation should be stricter than DB)
  5. If no @Column annotation exists, return null (no maxlength attribute on the HTML input)

This prevents a common bug: users type 300 characters into a form field, submit, and the database truncates to 255. With HTML maxlength set from the JPA annotation, the browser prevents over-long input before submission.

Test cases — 7 assertions covering 5 scenarios

#ModelManual argExpectedWhy
1PFUserDO.usernamenone255@Column(length=255) on the entity
2PFUserDO.username300255300 > 255 — DB constraint wins, manual override ignored
3PFUserDO.username100100100 < 255 — stricter manual limit wins
4BaseSearchFilter.searchStringnonenullNo @Column annotation — no limit
5BaseSearchFilter.searchString100100Manual limit on non-annotated field
6Plain Model.of("test")nonenullNo entity backing — can't read annotations
7Plain Model.of("test")100100Manual limit on plain model

assertInteger helper: Custom assertion that checks both non-null AND equals. Avoids the common pitfall of assertEquals(255, value) passing when value is null (autounboxing would throw NPE).