简体   繁体   English

"ConstraintValidator 在测试期间始终具有空值"

[英]ConstraintValidator always has null value during test

after fixing a bug in an older Java Spring MVC 4.1 application, I wanted to add a unit test, but the method the current code base is using for testing won't actually execute validation.在修复了较旧的 Java Spring MVC 4.1 应用程序中的错误后,我想添加一个单元测试,但当前代码库用于测试的方法实际上不会执行验证。

So I wanted to add MVCMock, but when it executes the validation methods, the values passed to isValid<\/code> is always null.所以我想添加 MVCMock,但是当它执行验证方法时,传递给isValid<\/code>的值始终为 null。

Relevant files below (I've tried to strip out as much noise as possible):下面的相关文件(我试图去除尽可能多的噪音):

// Unit Test
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@EnableWebMvc
@ContextConfiguration(locations = {"/applicationContext-test.xml"})
public class ExampleControllerTest extends AbstractControllerTestBase {
    @Autowired
    private WebApplicationContext context;

    private MockMvc mockMvc;


    @Before
    public void setup() {
        this.mockMvc = webAppContextSetup(this.context).build();
    }

    @Test
    public void fileUploadZipArchive() throws Exception {
        // Upload a zip file
        File mockFile = new File("src/test/resources/fixtures/ex.zip");

        MockHttpServletRequestBuilder multipart = MockMvcRequestBuilders
                .fileUpload("/files/ex/upload/Tex")
                .file("ex.zip",  FileUtils.readFileToByteArray(mockFile));

        MvcResult result = mockMvc.perform(multipart)
                .andReturn();
    }

The javadoc of the file method states that the name should be the name of the file. file方法的 javadoc声明name应该是文件的名称。 I agree that that is a bit misleading.我同意这有点误导。 Instead it should be the name of the request parameter to use, which should be (generally speaking) the same as the property in your model object.相反,它应该是要使用的请求参数的名称,它应该(一般来说)与模型对象中的属性相同。

.file("ex.zip",  FileUtils.readFileToByteArray(mockFile));

With this a request parameter named ex.zip will be part of the request, however you have one that is named file .有了这个,名为ex.zip的请求参数将成为请求的一部分,但是您有一个名为file的参数。

.file("file",  FileUtils.readFileToByteArray(mockFile));

Using the above line should fix it and properly bind to your object in turn properly invoking your validator.使用上面的行应该修复它并正确绑定到您的对象,进而正确调用您的验证器。

On a side node, your validator should properly handle the null case as well or add a @NotNull on the field as well.在侧节点上,您的验证器也应该正确处理null情况,或者也应该在字段上添加@NotNull The @Valid on the field doesn't do anything so you can remove that.字段上的@Valid不执行任何操作,因此您可以将其删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM