@DataJpaTest Junit 5 @Autowired NullPointer(SpringBoot)

时间:2019-11-27 15:27:15

标签: java spring spring-boot spring-data-jpa junit5

我已经使用Spring Data创建了一个新的Spring Boot应用程序。 尝试测试JpaRepository时遇到问题:

[ERROR] Failures: 
[ERROR]   EmployeeRepositoryTest.testDeleteEmployee:46 NullPointer
[ERROR]   EmployeeRepositoryTest.testGetEmployee:37 NullPointer
[ERROR]   EmployeeRepositoryTest.testSaveEmployee » Test 
Expected exception of type cla...
该行中的

java.lang.NullPointerException

repository.save(employee);

其中存储库已定义为:

@Autowired
private EmployeeRepository repository;

遵循我的pom.xml和测试类:

@ExtendWith({SpringExtension.class})
    @DataJpaTest
    class EmployeeRepositoryTest {

        @Autowired
        private EmployeeRepository repository;

        @Test(expectedExceptions = ResourceNotFoundException.class)
        void testSaveEmployee() throws ResourceNotFoundException {
            Employee employee = new Employee("John", "Smith", "john.smith@email.com");
            repository.save(employee);
            employee = repository.findById(employee.getId()).orElseThrow(() -> new ResourceNotFoundException(""));
            assertNotNull(employee);
            assertEquals(employee.getFirstName(), "John", "The employee firstname should be John");
        }
    }

...

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
   ...

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.13.1</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.5.2</version>
        <scope>test</scope>
    </dependency>
</dependencies>
...   

您能帮助您了解哪个问题吗?

在EmployeeRepository界面下面:

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long>{    
}

0 个答案:

没有答案