【问题标题】:Java Spring - Persisting object with API works, but I can't persist object with service in test, null pointerJava Spring - 使用 API 持久化对象有效,但我无法在测试中使用服务持久化对象,空指针
【发布时间】:2019-03-07 20:38:32
【问题描述】:

我在 spring 中创建了用于从 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);
    }
}

【问题讨论】:

标签: java spring hibernate junit spring-data


【解决方案1】:

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

@RunWith(SpringRunner.class)
public class EmployeeCRUDtest

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-12
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多