服务类春季启动中的空指针异常

时间:2018-10-05 10:51:03

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

Good Day ..我正在尝试创建一个Spring Boot Web应用程序,在其中我必须在spring boot的用户详细信息中找到该用户,但是在使用测试时出现错误,这是我的配置:

用户类别:

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = "USERS")
public class User implements Serializable {

  /**
     * 
     */
    private static final long serialVersionUID = 1L;

  @Id
  @GeneratedValue(strategy= GenerationType.IDENTITY)
  @Column(name = "USERNAME")
  private String username;

  @Column(name = "PASSWORD", nullable = false)
  private String password;

  @Column(name = "ENABLED", nullable = false)
  private boolean enabled;

  public User() {
    super();
    // TODO Auto-generated constructor stub
}

public User(String username, String password, boolean enabled, Set<Authorities> authorities, Customer customer) {
    super();
    this.username = username;
    this.password = password;
    this.enabled = enabled;
    this.authorities = authorities;
    this.customer = customer;
}

@OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
  private Set<Authorities> authorities = new HashSet<>();

  @OneToOne(cascade = CascadeType.ALL)
    private Customer customer;
  //Getter and Setter methods

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public boolean isEnabled() {
    return enabled;
}

public void setEnabled(boolean enabled) {
    this.enabled = enabled;
}

public Set<Authorities> getAuthorities() {
    return authorities;
}

public void setAuthorities(Set<Authorities> authorities) {
    this.authorities = authorities;
}

public Customer getCustomer() {
    return customer;
}

public void setCustomer(Customer customer) {
    this.customer = customer;
}

}

用户存储库:

package com.vishal.project.repos;
import com.vishal.project.entities.User;
public interface UserRepository extends CrudRepository<User,Long> {

    User findUserByUsername(String username);

}

UserDetailsS​​erviceImpl.class

package com.vishal.project.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User.UserBuilder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.vishal.project.entities.User;

import com.vishal.project.repos.UserRepository;



@Service("UserService")
public class UserDetailsServiceImpl implements UserDetailsService {

  @Autowired
  private UserRepository userRepo;

  @Transactional(readOnly = true)
  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    User user = userRepo.findUserByUsername(username);
    UserBuilder builder = null;
    if (user != null) {

      builder = org.springframework.security.core.userdetails.User.withUsername(username);
      builder.disabled(!user.isEnabled());
      builder.password(user.getPassword());
      String[] authorities = user.getAuthorities()
          .stream().map(a -> a.getAuthority()).toArray(String[]::new);

      builder.authorities(authorities);
    } else {
      throw new UsernameNotFoundException("User not found.");
    }
    return builder.build();
  }

  public User save(User user) {
      return userRepo.save(user);
  }


}

所以我正在运行Test,例如: UserDetails测试:

package com.vishal.project;

import static org.junit.Assert.assertNotNull;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.GenericApplicationContext;

import org.springframework.security.core.userdetails.UserDetailsService;

import com.vishal.project.entities.User;
import com.vishal.project.services.UserService;



public class UserDetailsTest {

    private static Logger logger = LoggerFactory.getLogger(UserDetailsTest.class);

    private GenericApplicationContext ctx;
    private UserDetailsService userDetailsService;
    private UserService userService;

    @Before
    public void SetUp() {
        ctx = new AnnotationConfigApplicationContext(OnlineBookShoppeApplication.class);
        userDetailsService = ctx.getBean(UserDetailsService.class);
        logger.info("starting to run tests now............");
        assertNotNull(userDetailsService);
    }   
        @Test
        public void testfindByUsername() {
             User user = userService.findByUsername("admin");
             String Username = user.getUsername();
             logger.info("Username=" + Username);

        }

        @After
         public void teardown() {
            ctx.close();
        }

    }

但是出现n错误,例如:

java.lang.NullPointerException
    at com.vishal.project.UserDetailsTest.testfindByUsername(UserDetailsTest.java:37)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)

UserService接口:

package com.vishal.project.services;

import com.vishal.project.entities.User;

public interface UserService {

    User findByUsername(String username);
    User save (User user);

}

我们将不胜感激...

1 个答案:

答案 0 :(得分:1)

您的userService字段为null,因为您尚未为其分配值。您的测试似乎没有使用userDetailsService字段,因此您可以删除它,然后替换以下行:

userDetailsService = ctx.getBean(UserDetailsService.class);

与此:

userService = ctx.getBean(UserService.class);