Is there a less bloated way to check for constraints in the grail?

Is there a less overblown way to test constraints? It seems to me that this is too much code to test the limitations.

class BlogPostTests extends GrailsUnitTestCase {

    protected void setUp() {
        super.setUp()
        mockDomain BlogPost
    }

    void testConstraints() {
        BlogPost blogPost = new BlogPost(title: "", text: "")
        assertFalse blogPost.validate()
        assertEquals 2, blogPost.errors.getErrorCount()
        assertEquals "blank", blogPost.errors.getFieldError("title").getCode()
        assertEquals "blank", blogPost.errors.getFieldError("text").getCode()

        blogPost = new BlogPost(title: "title", text: ObjectMother.bigText(2001))
        assertFalse blogPost.validate()
        assertEquals 1, blogPost.errors.getErrorCount()
        assertEquals "maxSize.exceeded", blogPost.errors.getFieldError("text").getCode()
    }
}
+3
source share
4 answers

I would advise against testing getErrorCount(), as your tests will be fragile (since you add other restrictions, you will not have to update each instance new BlogPost()anywhere in the test cases). Just check hasErrors().

In addition to this ... for each restriction, you need to generate some test data that violate it, call the verification procedure and confirm the errors. This is the code you need.

. :

private void assertConstraintWorks(clazz, fieldName, testData, expectedErrorCode) {
    def instance = clazz.newInstance((fieldName): testData)
    assertFalse instance.validate()
    assertTrue instance.hasErrors()
    assertEquals expectedErrorCode, instance.errors?.getFieldError(fieldName)?.code
}

void testConstraints() {
    assertConstraintWorks BlogPost, 'title', '', 'blank'
    assertConstraintWorks BlogPost, 'text', '', 'blank'
    assertConstraintWorks BlogPost, 'text', ObjectMother.bigText(2001), 'maxSize.exceeded'
}
+3

, , , DSL grails, , .

0

, , , : , ? , , , - Grails, . , ( Groovy), IMHO , . , TDD, .

0

. , , mockForConstraintsTests() ( mockDomain())

, , , , , . , , ( )

0

Source: https://habr.com/ru/post/1746900/


All Articles