junit SpringBoot测试NullPointer异常

qv7cva1a  于 11个月前  发布在  Spring
关注(0)|答案(2)|浏览(182)

我试图测试我的SpringBoot Repository是否可以将新用户添加到数据库中,并且在Junit测试期间我得到了一个NullPointer异常。下面是代码。
使用者:

package org.example;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.boot.SpringBootConfiguration;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name="users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(nullable=false, unique=true)
    private int creditCardNumber;

    @Column(nullable=false, unique=true)
    private String email;

    @Column(nullable=false)
    private String password;

}

字符串
UserRepository:

package org.example;

import org.example.User;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository<User, Long>{

}


用户服务:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Service;
@SpringBootApplication
@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public User createUser(Long id, int credit_card_number, String email, String password) {
        User user = new User(id,credit_card_number,email, password);
        return userRepository.save(user);
    }
}


UserTest:

package org.example;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class UserTest {

    @Autowired
    private UserService userService;

    @Test
    public void testCreateUser() {
        User newUser = userService.createUser(Integer.toUnsignedLong(23), 203952, "[email protected]", "siofd");
        assertEquals(newUser.getEmail(), "[email protected]");
    }
}


我的测试是在测试UserService时抛出空指针异常,因为我认为在UserService中,UserRepository是空的。
我添加了仓库注解到UserRepository。我尝试添加@SpringBootApplication。你能帮我解释一下为什么吗?

n8ghc7c1

n8ghc7c11#

1.您不应该将**@SpringBootApplication放在UserService类上。此annotation应仅在您的主应用程序类上。
1.在测试类上使用
@ExtendWith(SpringExtension.class)用于junit 5,@RunWith(SpringRunner.class)**用于junit 4。
1.对我来说,你的测试应该是这样的:

@ExtendWith(SpringExtension.class)
@SpringBootTest
public class UserServiceIntegrationTest {

@Autowired
private UserService userService;

@Autowired
private UserRepository userRepository;

@Test
public void testCreateUser() {
    // given
    int creditCardNumber = 203952;
    String email = "[email protected]";
    String password = "siofd";

    User newUser = userService.createUser(null, creditCardNumber, email, password);

    User foundUser = userRepository.findById(newUser.getId()).orElse(null);
    assertThat(foundUser).isNotNull();
    assertThat(foundUser.getEmail()).isEqualTo(email);
    assertThat(foundUser.getPassword()).isEqualTo(password);
    assertThat(foundUser.getCreditCardNumber()).isEqualTo(creditCardNumber);
}
}

字符串

ufj5ltwl

ufj5ltwl2#

修复UserService

首先,请从UserService服务中删除@SpringBootApplication注解。

创建SpringBootApplication注解类

接下来,请使用main方法作为入口点创建一个类,并使用@SpringBootApplication注解它。示例:

@SpringBootApplication
public class SpringSandboxApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringSandboxApplication.class, args);
    }

}

字符串
SpringBootApplication类的名称。

JUnit5样本测试

对于UserService,使用JUnit 5进行最低工作集成测试:

@SpringBootTest
class UserServiceIT {

    @Autowired
    private UserService userService;

    @Autowired
    private UserRepository userRepository;

    @Test
    void testCreateUser() {
        User createdUser = userService.createUser(1L, 1234567890, "[email protected]", "password");
        User retrievedUser = userRepository.findById(1L).orElse(null);

        assertEquals(createdUser.getId(), retrievedUser.getId());
        assertEquals(createdUser.getCreditCardNumber(), retrievedUser.getCreditCardNumber());
        assertEquals(createdUser.getEmail(), retrievedUser.getEmail());
        assertEquals(createdUser.getPassword(), retrievedUser.getPassword());
    }
}


根据您的pom.xml,您可能需要添加Maven Failsafe Plugin定义来自动运行调用mvn的集成测试:

<plugins>
    <build>
        <!-- your other plugin definitions -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-failsafe-plugin</artifactId>
            <version>3.1.2</version>
            <executions>
                <execution>
                    <goals>
                        <goal>integration-test</goal>
                        <goal>verify</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>


关于mvn verify

2024-01-05T12:05:12.752+01:00  INFO 56206 --- [           main] c.g.t.s.service.UserServiceIT            : Started UserServiceIT in 1.462 seconds (process running for 1.894)
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.015 s -- in com.github.tcsizmadia.springsandbox.service.UserServiceIT
[INFO] 
[INFO] Results:
[INFO] 
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] 
[INFO] 
[INFO] --- failsafe:3.1.2:verify (default) @ spring-sandbox ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  3.708 s
[INFO] Finished at: 2024-01-05T12:05:13+01:00
[INFO] ------------------------------------------------------------------------

相关问题