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?