1

I have below Test class:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringTestConfig.class)
public class UserServiceTest {

    @Inject
    private UserRepository userRepository;

    @Inject
    private UserService userService;

    @Test
    public void testProcessInvoice() throws SQLException {
        User user = new User();
        user.setFirstName("abc");
        when(userRepository.save(any(User.class))).thenReturn(user);
        Assert.assertNotNull(userService);
        User savedUser = userService.save(user);
        Assert.assertEquals("abc", savedUser.getFirstName());
    }
}

I have below SpringTestConfig.java

@Configuration
public class SpringTestConfig {
    @Bean
    public UserService userService() {
        return Mockito.mock(UserService.class);
    }
    @Bean
    public UserRepository userRepository() {
        return Mockito.mock(UserRepository.class);
    }
}

call to User savedUser = userService.save(user); returns null user object. I am not able to figure it out why it is returning null.

EDIT: UserRepository is JpaRepository, if this is a problem

public interface UserRepository extends JpaRepository<User, Long> {
}

2 Answers 2

3

Your UserService is a mock object, and has no defined behavior for dealing with the #save(User) method.

Mocking the object under test is probably not what you are after here. I would recommend your objects under test are instantiated in the test, and injected with the mocks or stubs of the objects that they utilize.

Sign up to request clarification or add additional context in comments.

2 Comments

yes, correct so I had run again with when(userService.save(any(User.class))).thenReturn(user); and it returns the object. how does it test the functionality of userService.save since I have defined mocking behavior on that?
You aren't if you are mocking your object under test!
2

Your configuration needs to return a real UserService:

@Configuration
public class SpringTestConfig {
    @Bean
    public UserService userService() {
        return new UserServiceImpl(); // or whatever your implementation is 
    }
    @Bean
    public UserRepository userRepository() {
        return Mockito.mock(UserRepository.class);
    }
}

Mocks are for collaborators, not for the thing you're testing.

1 Comment

I have followed what you said, like return new UserServiceImpl(userRepository()); now userService.save(user) calls actual implementation. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.