I am trying to test whether my SpringBoot Repository works adding the new User to database and I am getting a NullPointer Exception during the Junit test. Here is the code.
User:
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>{
}
UserService:
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);
}
}
and 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]");
}
}
My testing is throwing nullpointer exception during testCreateUser because I think in UserService, UserRepository is null.
I added the repository annotation to UserRepository. I tried adding the @SpringBootApplication. Could you maybe help why.
You should not put @SpringBootApplication on your UserService class. This annotation should be on your main application class only.
Use on top of your test class @ExtendWith(SpringExtension.class) for junit 5 and @RunWith(SpringRunner.class) for junit 4.
For me your test should look like this: