2016-06-18 7 views
0

コントローラで使用されるService Beanをモックする方法を探していますので、MockMvcを使用してコントローラのみをテストできます。しかし、実際のBeanをSpockモックに置き換える簡単な方法は見つけられません。すべてがスプリングブート1.3.2バージョンを使用しています。私はモック/スタブでこのautowired Beanを交換する方法が必要ですSpockを使用したコントローラテストでのMock Springサービス

@ContextConfiguration(classes = [Application], loader = SpringApplicationContextLoader) 
@WebAppConfiguration 
@ActiveProfiles("test") 
class NewsletterIssueControllerIntegrationSpec extends Specification { 

    MockMvc mockMvc 

    @Autowired 
    GetLatestNewsletterIssueService getLatestNewsletterIssueService 

    @Autowired 
    WebApplicationContext webApplicationContext 

    def setup() { 
    ConfigurableMockMvcBuilder mockMvcBuilder = MockMvcBuilders.webAppContextSetup(webApplicationContext) 
    mockMvc = mockMvcBuilder.build() 
    } 

    def "Should get 404 when latest issue does not exist"() { 
    given: 
     getLatestNewsletterIssueService.getLatestIssue() >> Optional.empty() // this won't work because it is real bean, not a Mock 
    expect: 
     mockMvc.perform(MockMvcRequestBuilders 
       .get("/issues/latest") 
       .contentType(JVM_BLOGGERS_V1) 
       .accept(JVM_BLOGGERS_V1) 
     ).andExpect(MockMvcResultMatchers.status().isNotFound()) 
    } 

} 

:詳細を下回る:

私は、次のコントローラクラス

@RestController 
@RequestMapping(path = "/issues") 
@AllArgsConstructor(onConstructor = @__(@Autowired)) 
public class NewsletterIssueController { 

    private final GetLatestNewsletterIssueService latestNewsletterIssueService; 

    @RequestMapping(
    method = RequestMethod.GET, 
    path = "/latest" 
) 
    public ResponseEntity getLatestIssue() { 
    Optional<NewsletterIssueDto> latestIssue = latestNewsletterIssueService.getLatestIssue(); 

    if (latestIssue.isPresent()) { 
     return ResponseEntity.ok(latestIssue.get()); 
    } else { 
     return ResponseEntity.notFound().build(); 
    } 
    } 
} 

そして、このクラスの統合スポックのテストを持っています私は '与えられた'セクションで相互作用を定義することができます。

答えて

1

私はテストでローカル設定を作成し、そこにあるBeanをオーバーライドします。

私はGroovyのか分からないが、それはJavaでこれをしたいと思います:

@ContextConfiguration(classes = NewsletterIssueControllerIntegrationSpec.Conf.class, loader = SpringApplicationContextLoader.class) 
@WebAppConfiguration 
@ActiveProfiles("test") 
class NewsletterIssueControllerIntegrationSpec extends Specification { 
    @Configuration 
    @Import(Application.class) 
    public static class Conf { 
    @Bean 
    public GetLatestNewsletterIssueService getLatestNewsletterIssueService() { 
     return mock(GetLatestNewsletterIssueService.class); 
    } 
    } 

    // […] 
} 

警告:このアプローチはMockitoとうまく動作しますが、それが機能するためにあなたがスポックのプレリリース版が必要になる場合がありますref:https://github.com/spockframework/spock/pull/546

ところで、Spring Boot 1.4は、これを簡略化するために@MockBeanの構成を提供します。

+0

私がJavaを使用していた場合、これは私の問題を解決することになります。つまりSpockのためにあなたは気づいたほど単純ではありません。私は新しいSpring Bootまたは新しいSpockのいずれかを、私が計画した通りに動作させるために必要とします。 –

関連する問題