Groovy 在spock中的自动接线JpaRepository处进行测试
账户存款Groovy 在spock中的自动接线JpaRepository处进行测试,groovy,spock,spring-test,Groovy,Spock,Spring Test,账户存款 public interface AccountsRepository extends JpaRepository<Account, Long> {} 公共接口AccountsRepository扩展了JpaRepository{} AccountsEndpointTest class AccountsEndpointTest extends Specification { @Shared @Autowired AccountsRepository accountR
public interface AccountsRepository extends JpaRepository<Account, Long> {}
公共接口AccountsRepository扩展了JpaRepository{}
AccountsEndpointTest
class AccountsEndpointTest extends Specification {
@Shared @Autowired AccountsRepository accountRepository
@Shared def entriesCount
def setupSpec() {
accountRepository = Mock()
}
def "create user"() {
given: "the current number of rows in accounts table"
entriesCount = accountRepository.count()
when: "add endpoint is invoked"
// send /user/add request
expect:
entriesCount < accountRepository.count()
}
}
类AccountsEndpointTest扩展了规范{
@共享@Autowired AccountsRepository accountRepository
@共享def entriesCount
def setupSpec(){
accountRepository=Mock()
}
定义“创建用户”(){
给定:“accounts表中的当前行数”
entriesCount=accountRepository.count()
“调用添加端点”时
//发送/用户/添加请求
期望:
entriesCount
entriesCount在给定的和预期的块中为我提供O。我手动测试了它,它的返回值是非零的,因为表中有条目。如何在spock中正确地测试这一点问题在于,与存储库交互的不是一个mock
在setupSpec中,您将使用模拟替换注入的存储库,该模拟在与计数方法交互时默认返回0。删除setupSpec部件以与真正的注入存储库交互。Spock Mock在定义为
@Shared
时不起作用,但这不是您的问题。您缺少@ContextConfiguration
或@springbootest
注释,因此spring实际上被使用并可以注入bean。还要确保类路径上有spock-spring
依赖项
作为旁注,您还可以使用
expect:
accountRepository.count() == old(accountRepository.count()) + 1
要说输入计数应该增加。很好的解释。但是,当我尝试在setupSpec块中删除它时,accountRepository将变为null