0

我有一个单元测试,我试图让验证成功。

基本上,当我调用 时badMockedSecureFile.validate(),它并没有达到我的预期,并且这两个字段的验证失败,encryptedFileName并且encryptedFileData.

当我中断调试器时,我只是在随后的断言中得到一个null值。badMockedSecureFile.errors这是我的两个文件:

任何投入将不胜感激。我找不到完全相同的问题。如果这很重要,我将grails 2.2.4Oracle JDK 1.7.0_25一起使用。

编辑:我只是想指出我删除了mockForConstraintTests电话,它现在似乎正在工作。我有这种感觉,我没有在某个地方进行 RTFM,并且这种行为在单元测试中发生了变化,还是发生了其他事情?

SecureFile.groovy

class SecureFile implements Serializable {

    /**
     * An unencrypted version of the file name.  This file name is unencrypted
     * when the appropriate password and key combo is used and it is never
     * persisted to the database for security (see transients below).
     */
    String fileName

    /**
     * Unencrypted version of the file data.  Never persisted to the
     * database for security (see transients below).
     */
    byte[] fileData

    String encryptedFileName
    byte[] encryptedFileData
    Date dateAdded
    Date dateUpdated
    Date dateDeleted

    static constraints = {
        encryptedFileName(nullable: false, blank: false)
        encryptedFileData(nullable: false)
    }

    static transients = ["fileName", "fileData"]

    static belongsTo = [user: User]
}

SecureFileTests.groovy

import static org.junit.Assert.*
import grails.test.mixin.*
import grails.test.mixin.support.*

import org.junit.*

/**
 * See the API for {@link grails.test.mixin.support.GrailsUnitTestMixin} for usage instructions
 */
@TestFor(SecureFile)
class SecureFileTests {

    static final String SAMPLE_PDF_FILE = "fileEncryptionTestSample.pdf"

    void testConstraints() {
        def samplePdfFile = new FileInputStream(SAMPLE_PDF_FILE)

        // Not really encrypted for this mock.
        def mockedSecureFile = new SecureFile(
                encryptedFileName: "--Not-Really-Encrypted--",
                encryptedFileData: samplePdfFile.getBytes()
                )
        mockForConstraintsTests(SecureFile, [mockedSecureFile])

        // Validation should fail if both properties are null.
        def badMockedSecureFile = new SecureFile()

        assert !badMockedSecureFile.validate()
        assert "nullable" == badMockedSecureFile.errors["encryptedFileName"].code
        assert "nullable" == badMockedSecureFile.errors["encryptedFileData"].code
    }
}
4

1 回答 1

0

从 badMockedSecureFile.errors["encryptedFileName"].code 中删除代码。

你会得到你所期望的。

mockForConstraintsTests(SecureFile)

// Validation should fail if both properties are null.
def badMockedSecureFile = new SecureFile()

assert !badMockedSecureFile.validate()
assert "nullable" == badMockedSecureFile.errors["encryptedFileName"]
assert "nullable" == badMockedSecureFile.errors["encryptedFileData"]
于 2013-09-03T10:47:12.173 回答