如何使用Spock在Spring Boot过滤器中模拟服务或存根服务方法?

时间:2015-03-26 17:55:25

标签: java spring testing spring-boot spock

目前我的Spring Boot应用程序中有一个过滤器,它使用Spring服务来完成一些繁重的工作。

public class HmacAuthenticationFilter implements Filter {

    @Autowired
    MyService myservice

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        myservice.callMethod();
    }
}

在我的Spock测试中,我想模拟过滤器使用的整个服务或者存根myservice.callMethod();返回特定值。

有关如何做到这一点的任何提示?

1 个答案:

答案 0 :(得分:1)

可以使用HotSwappableTargetSource

完成
@WebAppConfiguration
@SpringApplicationConfiguration(TestApp)
@IntegrationTest('server.port:0')

class HelloSpec extends Specification {

@Autowired
@Qualifier('swappableHelloService')
HotSwappableTargetSource swappableHelloService

def "test mocked"() {
  given: 'hello service is mocked'
  def mockedHelloService = Mock(HelloService)
  and:
  swappableHelloService.swap(mockedHelloService)

  when:
  //hit endpoint
  then:
  //asserts 
  and: 'check interactions'
  interaction {
      1 * mockedHelloService.hello(postfix) >> { ""Mocked, $postfix"" as String }
  }
  where:
  postfix | _
  randomAlphabetic(10) | _
}
}

这是TestApp(覆盖你想用代理模拟的bean)

class TestApp extends App {

//override hello service bean
@Bean(name = HelloService.HELLO_SERVICE_BEAN_NAME)
public ProxyFactoryBean helloService(@Qualifier("swappableHelloService") HotSwappableTargetSource targetSource) {
def proxyFactoryBean = new ProxyFactoryBean()
proxyFactoryBean.setTargetSource(targetSource)
proxyFactoryBean
}

@Bean
public HotSwappableTargetSource swappableHelloService() {
  new HotSwappableTargetSource(new HelloService());
}
}

看一下这个例子https://github.com/sf-git/spock-spring