Java jUnit:如何测试实体的强制属性

Java jUnit:如何测试实体的强制属性,java,unit-testing,junit,Java,Unit Testing,Junit,我对jUnit测试非常陌生,我正在尝试为我的Spring Boot应用程序编写一些集成测试。我的计划是测试是否设置了对象的所有必需属性。我想出了这样的想法: @Test(expected = org.springframework.orm.jpa.JpaSystemException.class) public void testMessageMandatoryAttributes() { Message corruptedMessage = new Message(); //

我对
jUnit
测试非常陌生,我正在尝试为我的
Spring Boot
应用程序编写一些
集成测试。我的计划是测试是否设置了对象的所有必需属性。我想出了这样的想法:

@Test(expected = org.springframework.orm.jpa.JpaSystemException.class)
public void testMessageMandatoryAttributes() {
    Message corruptedMessage = new Message();
    // set id
    // corruptedMessage.setId(id);
    // set conversation thread
    // corruptedMessage.setConversationThread(conversationThread);
    messageRepository.save(corruptedMessage);
}

然而,我的消息实体有更多的强制属性…如何在一个函数中测试所有属性是否正确设置?

基本上,您需要测试
messageRepository。save(Message)
方法抛出一个异常,其中包含有关缺少字段的一些信息

在下面找到一段代码片段,它可以帮助您实现目标。用需要验证的内容替换catch块中的断言

@Test
public void testMessageMandatoryAttributes() {
    Message corruptedMessage = new Message();
    // set id
    // corruptedMessage.setId(id);
    // set conversation thread
    // corruptedMessage.setConversationThread(conversationThread);

   try {
       messageRepository.save(corruptedMessage);
       fail();
   catch (YourException e) {
       assertEquals("Expected value", e.getXxx());
       // ...
   }
}

如果您想断言异常,那么我建议使用
ExpectedException
。如果您想验证对象属性,我建议使用write you custom matcher。

我不明白。似乎您正在自己设置所有属性(通过测试中的setter),那么您想测试什么?您介意发布您想为其编写测试的java代码吗?更容易看到您需要什么JUnit测试then@pgiecek我的目标是创建一个测试,上面写着“您试图创建一个对象并将其保存到数据库中,但是您没有分配所有必需的属性,所以您得到了这个、这个和这个字段的这个例外,也就是说,它应该如何……”好的。基本上你想测试这个方法
messageRepository.save(Message)
抛出一个异常,包含一些关于缺少字段的信息,对吗?@deeveeABC没有什么要发布的…我有一个实体,我想通过Spring JPA将它保存到数据库中,我想编写一个失败测试来测试所有必填字段(由数据库结构定义)被填充…或者更像是反之亦然-它们中没有一个被填充,它将为所有它们抛出异常(将等待)。