Nitesh Virani
Nitesh Virani

Reputation: 1712

Mock objects returns null

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> {
}

Upvotes: 1

Views: 3223

Answers (2)

nicholas.hauschild
nicholas.hauschild

Reputation: 42849

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.

Upvotes: 3

Nathan Hughes
Nathan Hughes

Reputation: 96385

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.

Upvotes: 2

Related Questions