我在春季创建了用于持久存储JSON主体中的对象的API,并且它可以正常工作,但是我正尝试创建一堆测试,我需要这些示例数据。我正在尝试使用与该实体相关的服务将数据保留在测试中,但是当我尝试这样做时,我得到了NullPointerException。您能帮我解决这个问题吗?
实体类:
@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;
}
与实体相关的服务:
@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);
}
}
抛出NullPointerException的测试:
public class EmployeeCRUDtest {
TestUtils testUtils = new TestUtils();
@Autowired
EmployeeService employeeService;
@Test
public void shouldPersistEmployee(){
EmployeeEntity emp = testUtils.generateSingleRandomEmployee();
employeeService.addEmployee(emp);
}
}
答案 0 :(得分:1)
您缺少使@Autowired
在测试中起作用的注释:
@RunWith(SpringRunner.class)
public class EmployeeCRUDtest