Search code examples
javaspring-bootgroovyspock

Calling a service on Spock gets null object


Im trying to perform test under the spock framework with the following structure

class UserServiceSpec extends Specification{

   ModelMapper modelMapper = Stub(ModelMapper.class)

   UserRepository userRepository=Mock(UserRepository.class)

   UserService userService

   def setup(){
       userService= new UserServiceImpl(userRepository,modelMapper)
   }
   def "find user by email"(){
      given: "Creates a constant with an existing email"
          def constant ="juan@rodriguez.com"
      when: "Calling the method findUserByEmail"
          def response= userService.findUserByEmail(constant)
      then:"Comparing the response result with the constant"
        
         response.getEmail()==constant
   }
}

However when i try to get the value of response.getEmail(), the result is a null object and it should get the same parameter as "constant", the error is:

Cannot invoke method getEmail() on null object

The code structure for UserService and the implementation is:

 public interface UserService {

     UserModel findUserByEmail(String email);
 }

The UserService implementation is :

@Service
@Qualifier("userDetailsService")
public class UserServiceImpl implements UserService, UserDetailsService {

    private final UserRepository userRepository;

    private final ModelMapper modelMapper;

    public UserServiceImpl(UserRepository userRepository,ModelMapper modelMapper){
       this.userRepository= userRepository;
       this.modelMapper= modelMapper;
    }

}

However, if i call the Service from the controller (spring project) with the same method i get an object with it's parameter. How is it possible to fix this spock test?

  • I tried "@Autowired" for the service instead of initializing as a UserServiceImpl but it does not work.
  • I tried without mocking the mapper and the repository and still getting the same null object.

Solution

  • You don't specify any interactions with the mock UserRepository, so Spock returns null from any method call you make on it. Presuming your repository is an ordinary one, say something like this:

    then:
    userRepository.findByEmail(constant) >> { c -> new UserEntity(email: c, ...) }
    constant == response.email // expected value comes first, and you can use Groovy property syntax