我最近开始使用mockito学习spring boot junit测试,但我经常陷入困境。这是我的问题:
我创建了一个简单的addEmployeeTest,由于我的存储库(我将数据存储在我的postgres数据库中)导致空指针异常,我存储数据的地方以某种方式返回null。
这是我的文件:
员工.java
package springbootproject.model;
import lombok.*;
import javax.persistence.*;
@Data
@Entity
@Builder
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "first_name", nullable = false)
private String firstName;
@Column(name = "last_name", nullable = false)
private String lastName;
@Column(name = "email", nullable = false)
private String email;
}
EmployeeRepsory.java
package springbootproject.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import springbootproject.model.Employee;
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {}
EmployeeController.java
package springbootproject.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springbootproject.model.Employee;
import springbootproject.repository.EmployeeRepository;
@RestController
@RequestMapping("/api/v1")
public class EmployeeController {
@Autowired
private EmployeeRepository employeeRepository;
@PostMapping("/employees")
public Employee createEmployee(@RequestBody Employee employee) {
return this.employeeRepository.save(employee);
}
}
EmployeeControllerTest.java
package springbootproject.controller;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import springbootproject.model.Employee;
import springbootproject.repository.EmployeeRepository;
@DataJpaTest
public class EmployeeControllerTest {
@Autowired
private EmployeeRepository employeeRepository;
@Test
public void addEmployeeTest() {
Employee employee = Employee.builder()
.id(1L).firstName("abc").lastName("def").email("[email protected]")
.build();
employeeRepository.save(employee);
assertThat(employee.getId()).isGreaterThan(0L);
}
}
应用程序.属性
spring.datasource.url = jdbc:postgresql://localhost:5432/employees
spring.datasource.username = postgres
spring.datasource.password = postgres
spring.jpa.show-sql = true
## Hiberate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
我已经被这个问题困扰了一段时间,我不知道它是否太基础了。我不太明白。谢谢
这可能是因为,您的存储库与测试类位于不同的包中,请确保 Spring 扫描包含您的存储库的包。您可以通过在主应用程序类中使用 @SpringBootApplication(scanBasePackages = "springbootproject.repository") 或类似注释来完成此操作。