컨트롤러에서 사용되는 Service Bean을 모방 할 방법을 찾고 있으므로 MockMvc를 사용하여 컨트롤러 만 테스트 할 수 있습니다. 하지만 실제 콩을 Spock mock으로 대체하는 쉬운 방법을 찾을 수 없습니다. 모든 것은 spring-boot 1.3.2 버전을 사용합니다. 자세한 내용은 아래 :Spock을 사용한 컨트롤러 테스트에서 모의 스프링 서비스
나는이 클래스에 대한 다음과 같은 컨트롤러 클래스
@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();
}
}
}
그리고 통합 스팍 테스트 한 :이 모의/스텁과 콩을 autowire가 대체 할 수있는 방법을
@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())
}
}
필요 그래서 '주어진'섹션에서 상호 작용을 정의 할 수 있습니다.
Java를 사용하면이 문제가 해결 될 것이므로 Spock에 +1하면 매우 간단합니다. 새로운 봄 부팅 또는 새로운 Spock이 필요합니다. –