简体   繁体   English

对数据库中条目的创建进行单元测试

[英]Unit testing the creation of an entry in the database

I'm wanted to write a simple unit test for a service.我想为服务编写一个简单的单元测试。 This is the method in my service which I want to unitest.这是我要统一测试的服务中的方法。

@Log4j
@Service
public class Service {

     @Autowired
     private Repository repository;

    public JpaRecord create(JpaRecord jpaRecord) {
        return repository.save(jpaRecord);
    }
}

This method just creates a new entry in the Database.此方法只是在数据库中创建一个新条目。

This is the JpaRecord:这是 JpaRecord:

@Data
@Entity
@Table(name = "TEST", schema = "TEST")
public class JpaRecord implements Serializable {
    private static final long serialVersionUID = 1L;

    JpaRecord() {
        // default constructor
    }

    public JpaRecord(
            String name,
            Date createdAt,
            Blob file
    ) {
        this.name = name;
        this.createdAt = createdAt;
        this.file = file;
    }

    @Id
    @Column(name = "ID", nullable = false)
    @GeneratedValue(strategy = GenerationType.SEQUENCE,
            generator = "TEST_SEQx")
    @SequenceGenerator(
            sequenceName = "TEST_SEQ", allocationSize = 1,
            name = "TEST_SEQx")
    private Long id;

    @Column(name = "NAME")
    private String name;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "CREATED_AT")
    private Date createdAt;

    @Lob
    @Column(name = "FILE")
    private Blob file;
}

The id should not be null, all the other entries can be null. I wrote this test to check if the DB entry is not null, which means it is created. id不应该是 null,所有其他条目都可以是 null。我写这个测试是为了检查数据库条目是否不是 null,这意味着它已创建。

public class ServiceTest {

    @Autowired
    private Service Service;

    @Autowired
    private JpaRecord JpaRecord;

    @Before
    public void setUp(){

    }

    @Test
    public void testCreateWhenNull(){
        // prepare data
        JpaRecord = new JpaRecord("testProject", new Date(),null);
        // run

        // test with assert
        Assert.assertNotNull(Service.create(JpaRecord));
    }

}

I then get a java.lang.NullPointerException.然后我得到一个 java.lang.NullPointerException。 I would really appreciate any suggestion on how I should approach a problem to unit test it.我真的很感激任何关于我应该如何处理问题以对其进行单元测试的建议。 It is my first time unit testing and I wanted to start with a simple null check.这是我第一次进行单元测试,我想从一个简单的 null 检查开始。

you are missing some configuration related spring boot JUnit testing at the class level that's why you are getting Nullpointer Exception.please read the following link reference link您缺少一些配置相关的 spring 启动 JUnit 在 class 级别进行测试,这就是您获得 Nullpointer Exception 的原因。请阅读以下链接参考链接

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

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