2
votes

I get exception when I run test:

java.lang.NullPointerException at com.example.demo.service.database.impl.UserServiceImplTest.getById(UserServiceImplTest.java:69) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) 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.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)

Here is UserServiceImpl:

@Service
public class UserServiceImpl implements UserService {

private final UserRepository userRepository;

@Autowired
public UserServiceImpl(UserRepository userRepository) {
    this.userRepository = userRepository;
}

@Override
public List<User> getAll() {
    return userRepository.findAll();
}

@Override
public User getById(long id) {
    return userRepository.findOne(id);
}

This is my test:

@RunWith(SpringJUnit4ClassRunner.class)
public class UserServiceImplTest {

@InjectMocks
UserServiceImpl userService;

@Mock
UserRepository userRepositoryMock;

@Before
public void setUp(){
    MockitoAnnotations.initMocks(this);
}

@Test
public void getById() {
    long id = 12;
    when(userRepositoryMock.findOne(id)).thenReturn(new User(id));
    Assert.assertEquals(id, userService.getById(id).getId());
  }
}

How to solve this problem?

1

1 Answers

1
votes

Just Remove your setup() method from your test class.

@Before
public void setUp(){
    MockitoAnnotations.initMocks(this);
}

It is needed when you don't use @RunWith(SpringJUnit4ClassRunner.class)

Only one either annotation or setup() method is needed, not both.