0

I have been trying to get simple test cases to work without success. They're just giving a null pointer error:

java.lang.NullPointerException

Example:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringCrudApplication.class)
public class ServiceTest {


UserService userService;

@Autowired
public void setUserService(UserService userService) {
    this.userService = userService;
}

@Test
public void findUserByIdTest() throws Exception {

    long id = (long) 0;

    User user = new User();
    user.setId(id);
    user.setAddress("main st");
    user.setEmail("drew@gmail.com");
    user.setUsername("Drew");

          System.out.println("Name: "+user.getUsername()+" ID: "+user.getId()); //this is printing

    userService.saveUser(user);

    User userTest = userService.findUserById(id);

    System.out.println("Username="+userTest.getUsername());

    assertEquals("Drew", userTest.getUsername());

}

I am getting the following output in the console:

Name: Drew ID: 0

However once it gets to:

userService.saveUser(user);

the null pointer is created.

Here is the method being tested:

 public class UserServiceImpl implements UserService {

    private static final AtomicLong counter = new AtomicLong();

    private static List<User> users;

    static {
        users = populateDummyUsers();
    }

 @Override
    public User findUserById(Long id) {

        for (User user : users) {
            if (user.getId() == id) {
                return user;
            }
        }

        return null;
    }

@Override
    public void saveUser(User user) {

        if(user != null) {
            user.setId(counter.incrementAndGet());
            users.add(user);
        }

    }
Mike3355
  • 11,305
  • 24
  • 96
  • 184
  • 1
    Possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – xlecoustillier Mar 11 '16 at 17:11
  • because in you saveUser method you increment the id of user object by 1 and then store it. so user with id = 0 is stored with id = 1. when you try to get that user you pass 0 as parameter and the method cant find the user with 0 id in the users list and returns null, hence the exception. – Rahul Sharma Mar 11 '16 at 17:18
  • You are very correct! Please move this comment to answers. – Mike3355 Mar 11 '16 at 17:44

1 Answers1

0

Looks like your user service is null.. Spring context.xml need to be there in test resource folder. Else you will have to mock the userserice. Use mocking to mock and stub the response.

Rohit Kasat
  • 300
  • 3
  • 13