Mockito is returning a null pointer when mocking a service/controller
when i tried to run the test it is throwing a null pointer at userService.setUser(user);
and tried running it in debug mode, it just initiating my mocks as null.
is there something i am missing ?
any one else faced similar problem before?
i did try using @spy on userService but no luck.
//SERVICE
package com.ecommerce.munna.user;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import java.util.*;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public void setUser(User user) {
userRepository.save(user);
}
public List<User> getAllUsers() {
List<User> userList = new ArrayList<>();
userRepository.findAll()
.forEach(userList::add); //findAll is an interable so convert this into list to send it back
return userList;
}
/*public User getUserByUserNameandPassword(String userName, String password)
{
return userRepository.findByIdandPassword(userId,password);
}*/
}
//TEST
package com.ecommerce.munna.user;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.ArrayList;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
//
@RunWith(MockitoJUnitRunner.class)
class UserServiceTest {
@Mock
private TestBuilder testBuilder;
@Mock
private User user;
@Mock
private UserRepository userRepository;
@InjectMocks
private UserService userService;
@Test
void setUser_shouldStoreNewuserInRepository() throws Exception {
ArrayList<User> userList= new ArrayList<User>();
user=testBuilder.tetsUserBuilder();
user.setId(1L);
userList.add(user);
user.setId(2L);
userList.add(user);
userService.setUser(user);
when(userRepository.findAll()).thenReturn(userList);
assertEquals(2,userList.size());
}
}
TEST BUILDER
package com.ecommerce.munna.user;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TestBuilder {
// @Autowired User user;
// @Bean
public static User tetsUserBuilder(){
User user=new User.UserBuilder()
.id(1L)
.userName("munnaTest")
.password("testPassword")
.firstName("munna")
.lastName("Gunturu")
.dateOfBirth("06/06/1999")
.eMail("m@yahoo.com")
.gender("Male")
.build();
return user;
}
}
java gradle mockito
add a comment |
when i tried to run the test it is throwing a null pointer at userService.setUser(user);
and tried running it in debug mode, it just initiating my mocks as null.
is there something i am missing ?
any one else faced similar problem before?
i did try using @spy on userService but no luck.
//SERVICE
package com.ecommerce.munna.user;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import java.util.*;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public void setUser(User user) {
userRepository.save(user);
}
public List<User> getAllUsers() {
List<User> userList = new ArrayList<>();
userRepository.findAll()
.forEach(userList::add); //findAll is an interable so convert this into list to send it back
return userList;
}
/*public User getUserByUserNameandPassword(String userName, String password)
{
return userRepository.findByIdandPassword(userId,password);
}*/
}
//TEST
package com.ecommerce.munna.user;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.ArrayList;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
//
@RunWith(MockitoJUnitRunner.class)
class UserServiceTest {
@Mock
private TestBuilder testBuilder;
@Mock
private User user;
@Mock
private UserRepository userRepository;
@InjectMocks
private UserService userService;
@Test
void setUser_shouldStoreNewuserInRepository() throws Exception {
ArrayList<User> userList= new ArrayList<User>();
user=testBuilder.tetsUserBuilder();
user.setId(1L);
userList.add(user);
user.setId(2L);
userList.add(user);
userService.setUser(user);
when(userRepository.findAll()).thenReturn(userList);
assertEquals(2,userList.size());
}
}
TEST BUILDER
package com.ecommerce.munna.user;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TestBuilder {
// @Autowired User user;
// @Bean
public static User tetsUserBuilder(){
User user=new User.UserBuilder()
.id(1L)
.userName("munnaTest")
.password("testPassword")
.firstName("munna")
.lastName("Gunturu")
.dateOfBirth("06/06/1999")
.eMail("m@yahoo.com")
.gender("Male")
.build();
return user;
}
}
java gradle mockito
Have you tried initializing the user a different way?
– MAbraham1
Dec 28 '18 at 19:51
yeah, my user is getting pouplated but userservice is freaking out in test. UPDATED MY POST WITH TEST BUILDER.
– vmk
Dec 28 '18 at 19:57
yup, tried it too.. but no luck.
– vmk
Dec 28 '18 at 20:01
add a comment |
when i tried to run the test it is throwing a null pointer at userService.setUser(user);
and tried running it in debug mode, it just initiating my mocks as null.
is there something i am missing ?
any one else faced similar problem before?
i did try using @spy on userService but no luck.
//SERVICE
package com.ecommerce.munna.user;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import java.util.*;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public void setUser(User user) {
userRepository.save(user);
}
public List<User> getAllUsers() {
List<User> userList = new ArrayList<>();
userRepository.findAll()
.forEach(userList::add); //findAll is an interable so convert this into list to send it back
return userList;
}
/*public User getUserByUserNameandPassword(String userName, String password)
{
return userRepository.findByIdandPassword(userId,password);
}*/
}
//TEST
package com.ecommerce.munna.user;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.ArrayList;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
//
@RunWith(MockitoJUnitRunner.class)
class UserServiceTest {
@Mock
private TestBuilder testBuilder;
@Mock
private User user;
@Mock
private UserRepository userRepository;
@InjectMocks
private UserService userService;
@Test
void setUser_shouldStoreNewuserInRepository() throws Exception {
ArrayList<User> userList= new ArrayList<User>();
user=testBuilder.tetsUserBuilder();
user.setId(1L);
userList.add(user);
user.setId(2L);
userList.add(user);
userService.setUser(user);
when(userRepository.findAll()).thenReturn(userList);
assertEquals(2,userList.size());
}
}
TEST BUILDER
package com.ecommerce.munna.user;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TestBuilder {
// @Autowired User user;
// @Bean
public static User tetsUserBuilder(){
User user=new User.UserBuilder()
.id(1L)
.userName("munnaTest")
.password("testPassword")
.firstName("munna")
.lastName("Gunturu")
.dateOfBirth("06/06/1999")
.eMail("m@yahoo.com")
.gender("Male")
.build();
return user;
}
}
java gradle mockito
when i tried to run the test it is throwing a null pointer at userService.setUser(user);
and tried running it in debug mode, it just initiating my mocks as null.
is there something i am missing ?
any one else faced similar problem before?
i did try using @spy on userService but no luck.
//SERVICE
package com.ecommerce.munna.user;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import java.util.*;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public void setUser(User user) {
userRepository.save(user);
}
public List<User> getAllUsers() {
List<User> userList = new ArrayList<>();
userRepository.findAll()
.forEach(userList::add); //findAll is an interable so convert this into list to send it back
return userList;
}
/*public User getUserByUserNameandPassword(String userName, String password)
{
return userRepository.findByIdandPassword(userId,password);
}*/
}
//TEST
package com.ecommerce.munna.user;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.ArrayList;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
//
@RunWith(MockitoJUnitRunner.class)
class UserServiceTest {
@Mock
private TestBuilder testBuilder;
@Mock
private User user;
@Mock
private UserRepository userRepository;
@InjectMocks
private UserService userService;
@Test
void setUser_shouldStoreNewuserInRepository() throws Exception {
ArrayList<User> userList= new ArrayList<User>();
user=testBuilder.tetsUserBuilder();
user.setId(1L);
userList.add(user);
user.setId(2L);
userList.add(user);
userService.setUser(user);
when(userRepository.findAll()).thenReturn(userList);
assertEquals(2,userList.size());
}
}
TEST BUILDER
package com.ecommerce.munna.user;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TestBuilder {
// @Autowired User user;
// @Bean
public static User tetsUserBuilder(){
User user=new User.UserBuilder()
.id(1L)
.userName("munnaTest")
.password("testPassword")
.firstName("munna")
.lastName("Gunturu")
.dateOfBirth("06/06/1999")
.eMail("m@yahoo.com")
.gender("Male")
.build();
return user;
}
}
java gradle mockito
java gradle mockito
edited Dec 28 '18 at 20:02
vmk
asked Dec 28 '18 at 19:46
vmkvmk
112
112
Have you tried initializing the user a different way?
– MAbraham1
Dec 28 '18 at 19:51
yeah, my user is getting pouplated but userservice is freaking out in test. UPDATED MY POST WITH TEST BUILDER.
– vmk
Dec 28 '18 at 19:57
yup, tried it too.. but no luck.
– vmk
Dec 28 '18 at 20:01
add a comment |
Have you tried initializing the user a different way?
– MAbraham1
Dec 28 '18 at 19:51
yeah, my user is getting pouplated but userservice is freaking out in test. UPDATED MY POST WITH TEST BUILDER.
– vmk
Dec 28 '18 at 19:57
yup, tried it too.. but no luck.
– vmk
Dec 28 '18 at 20:01
Have you tried initializing the user a different way?
– MAbraham1
Dec 28 '18 at 19:51
Have you tried initializing the user a different way?
– MAbraham1
Dec 28 '18 at 19:51
yeah, my user is getting pouplated but userservice is freaking out in test. UPDATED MY POST WITH TEST BUILDER.
– vmk
Dec 28 '18 at 19:57
yeah, my user is getting pouplated but userservice is freaking out in test. UPDATED MY POST WITH TEST BUILDER.
– vmk
Dec 28 '18 at 19:57
yup, tried it too.. but no luck.
– vmk
Dec 28 '18 at 20:01
yup, tried it too.. but no luck.
– vmk
Dec 28 '18 at 20:01
add a comment |
1 Answer
1
active
oldest
votes
Welcome to Stack Overflow!
Any unit tests cosist of tree parts in a defined order: arrange, act and assert.
Your test does the arrange part after the act part:
userService.setUser(user); // act
when(userRepository.findAll()).thenReturn(userList); // arrange
The last line her should be the first in the test method.
Thank you timothy, It still didn't work.
– vmk
Dec 28 '18 at 20:43
@vmk did you stumble into this: tedvinke.wordpress.com/2014/02/13/… ?
– Timothy Truckle
Dec 28 '18 at 21:13
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53963612%2fmockito-is-returning-a-null-pointer-when-mocking-a-service-controller%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Welcome to Stack Overflow!
Any unit tests cosist of tree parts in a defined order: arrange, act and assert.
Your test does the arrange part after the act part:
userService.setUser(user); // act
when(userRepository.findAll()).thenReturn(userList); // arrange
The last line her should be the first in the test method.
Thank you timothy, It still didn't work.
– vmk
Dec 28 '18 at 20:43
@vmk did you stumble into this: tedvinke.wordpress.com/2014/02/13/… ?
– Timothy Truckle
Dec 28 '18 at 21:13
add a comment |
Welcome to Stack Overflow!
Any unit tests cosist of tree parts in a defined order: arrange, act and assert.
Your test does the arrange part after the act part:
userService.setUser(user); // act
when(userRepository.findAll()).thenReturn(userList); // arrange
The last line her should be the first in the test method.
Thank you timothy, It still didn't work.
– vmk
Dec 28 '18 at 20:43
@vmk did you stumble into this: tedvinke.wordpress.com/2014/02/13/… ?
– Timothy Truckle
Dec 28 '18 at 21:13
add a comment |
Welcome to Stack Overflow!
Any unit tests cosist of tree parts in a defined order: arrange, act and assert.
Your test does the arrange part after the act part:
userService.setUser(user); // act
when(userRepository.findAll()).thenReturn(userList); // arrange
The last line her should be the first in the test method.
Welcome to Stack Overflow!
Any unit tests cosist of tree parts in a defined order: arrange, act and assert.
Your test does the arrange part after the act part:
userService.setUser(user); // act
when(userRepository.findAll()).thenReturn(userList); // arrange
The last line her should be the first in the test method.
answered Dec 28 '18 at 20:26
Timothy TruckleTimothy Truckle
8,32821834
8,32821834
Thank you timothy, It still didn't work.
– vmk
Dec 28 '18 at 20:43
@vmk did you stumble into this: tedvinke.wordpress.com/2014/02/13/… ?
– Timothy Truckle
Dec 28 '18 at 21:13
add a comment |
Thank you timothy, It still didn't work.
– vmk
Dec 28 '18 at 20:43
@vmk did you stumble into this: tedvinke.wordpress.com/2014/02/13/… ?
– Timothy Truckle
Dec 28 '18 at 21:13
Thank you timothy, It still didn't work.
– vmk
Dec 28 '18 at 20:43
Thank you timothy, It still didn't work.
– vmk
Dec 28 '18 at 20:43
@vmk did you stumble into this: tedvinke.wordpress.com/2014/02/13/… ?
– Timothy Truckle
Dec 28 '18 at 21:13
@vmk did you stumble into this: tedvinke.wordpress.com/2014/02/13/… ?
– Timothy Truckle
Dec 28 '18 at 21:13
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53963612%2fmockito-is-returning-a-null-pointer-when-mocking-a-service-controller%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Have you tried initializing the user a different way?
– MAbraham1
Dec 28 '18 at 19:51
yeah, my user is getting pouplated but userservice is freaking out in test. UPDATED MY POST WITH TEST BUILDER.
– vmk
Dec 28 '18 at 19:57
yup, tried it too.. but no luck.
– vmk
Dec 28 '18 at 20:01