Java Spring-使用API​​持久化对象有效,但是我无法在测试中将对象与服务持久化,空指针

时间:2019-03-07 20:38:33

标签: java spring junit nullpointerexception persistence

我在春季创建了用于持久存储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);
    }
}

1 个答案:

答案 0 :(得分:1)

您缺少使@Autowired在测试中起作用的注释:

@RunWith(SpringRunner.class)
public class EmployeeCRUDtest