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:
@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.
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. 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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.