I have created API in spring for persisting object from JSON body andi it works fine, but I'm trying to create a bunch of tests and I need sample data for them. I'm trying to persist that data within test using service related to that entity, but when I'm trying to do that I'm getting NullPointerException. Could you please help me resolve this problem?
Entity class:
@Entity
@Table(name = "employees")
@NoArgsConstructor
@Data
public class EmployeeEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private int employeeId;
private String firstName;
private String lastName;
}
Entity related service:
@Service
public class EmployeeService {
@Autowired
EmployeeRepository employeeRepository;
public void addEmployee(EmployeeEntity employee){
employeeRepository.save(employee);
}
public Iterable<EmployeeEntity> getAllEmployees(){
return employeeRepository.findAll();
}
public Optional<EmployeeEntity> getEmployeeById(Long id){
return employeeRepository.findById(id);
}
}
Test that throws NullPointerException:
public class EmployeeCRUDtest {
TestUtils testUtils = new TestUtils();
@Autowired
EmployeeService employeeService;
@Test
public void shouldPersistEmployee(){
EmployeeEntity emp = testUtils.generateSingleRandomEmployee();
employeeService.addEmployee(emp);
}
}
You're missing an annotation that makes @Autowired
in tests work:
@RunWith(SpringRunner.class)
public class EmployeeCRUDtest
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.