【问题标题】:Calling a service on Spock gets null object在 Spock 上调用服务获取空对象
【发布时间】:2021-06-29 21:30:24
【问题描述】:

我尝试在spock框架下进行测试,结构如下

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

但是,当我尝试获取 response.getEmail() 的值时,结果是一个空对象,它应该获得与“常量”相同的参数,错误是:

Cannot invoke method getEmail() on null object

UserService的代码结构和实现是:

 public interface UserService {

     UserModel findUserByEmail(String email);
 }

UserService 的实现是:

@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;
    }

}

但是,如果我使用相同的方法从控制器(spring 项目)调用服务,我会得到一个带有参数的对象。如何修复这个 spock 测试?

  • 我为服务尝试了“@Autowired”,而不是初始化为 UserServiceImpl,但它不起作用。
  • 我尝试不模拟映射器和存储库,但仍然得到相同的空对象。

【问题讨论】:

  • 请注意,您不需要setup 方法;您可以将作业内联。
  • @alex,问为什么findUserByEmail(String) 返回null 并不是很有帮助,而是在您的示例代码中省略了方法定义。在这种情况下,chrylis 有根据地猜测该方法在内部使用了 UserRepository,并且可能他是对的并且正确地回答了您的问题。尽管如此,这是一个推测性的答案,因为您在这里隐藏了信息。请更新您的问题,最好将其转换为MCVE,这样您也会得到更准确的答案。

标签: java spring-boot groovy spock


【解决方案1】:

您没有指定与模拟 UserRepository 的任何交互,因此 Spock 从您对其进行的任何方法调用都会返回 null。假设您的存储库是一个普通的,这样说:

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

【讨论】:

  • 存储库是正常的,感谢您的帮助:)
猜你喜欢
  • 1970-01-01
  • 2014-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-21
相关资源
最近更新 更多