我有一个Spring Boot应用程序,正在使用Spock进行测试。
我在下面的课程中尝试模仿BankStatementServiceClient.fetch()
。我可以看到该bean的接线正确(bankStatementTestClient是模拟对象),但是从测试中调用bankStatementTestClient.fetch()
时总是会得到null。
@SpringBootTest(webEnvironment = RANDOM_PORT)
@ContextConfiguration(classes = [SweepTestConfig])
class TestIntSpec extends Specification {
@Autowired
BankStatementServiceClient bankStatementTestClient
def "mock service"() {
when:
def result = bankStatementTestClient.fetch() //bankStatementTestClient is autowired correctly
then:
result == ["a","b"]
1 * bankStatementTestClient.fetch() >> ["a","b"]
}
}
@TestConfiguration
class SweepTestConfig {
def mockFactory = new DetachedMockFactory()
@Bean
@Primary
BankStatementServiceClient bankStatementTestClient() {
return mockFactory.Mock(BankStatementServiceClient)
}
}
@Component
public class BankStatementServiceClient {
public List<String> fetch() {
return Arrays.asList("dummy1", "dummy2");
}
}