Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@snekse
Created April 11, 2017 17:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save snekse/6b743f5aec3ab19adaf699f604dda9ce to your computer and use it in GitHub Desktop.
Save snekse/6b743f5aec3ab19adaf699f604dda9ce to your computer and use it in GitHub Desktop.
spring-spock-integration-testing blog post samples
@TestConfiguration
class IntegrationTestMockingConfig {
private DetachedMockFactory factory = new DetachedMockFactory()
@Bean
ExternalRankingService externalRankingService() {
factory.Mock(ExternalRankingService)
}
}
@SpringBootTest
@AutoConfigureMockMvc
@Import([IntegrationTestMockingConfig])
class PersonControllerIntTest extends Specification {
@Autowired MockMvc mvc
/**
* This is our mock we created in our test config.
* We inject it in so we can control it in our specs.
*/
@Autowired ExternalRankingService externalRankingServiceMock
def "GetRank"() {
when: 'Calling getRank for a known seed data entity'
MvcResult mvcResult = mvc.perform(get("/persons/1/rank"))
.andExpect(status().is2xxSuccessful())
.andReturn()
then: 'we define the mock for JUST the external service'
externalRankingServiceMock.getRank(_) >> {
new Rank(level: 1, classification: 'Captain')
}
noExceptionThrown()
when: 'inspecting the contents'
def content = mvcResult.response.contentAsString
then: 'result contains mix of mocked service data and actual wired component data'
content == 'Capt James Kirk ~ Captain:Level 1'
}
}
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class SampleTestApplicationWebIntegrationTests {
@Autowired private TestRestTemplate restTemplate;
//You'll now be able to mock calls to VehicleDetailsService
@MockBean private VehicleDetailsService vehicleDetailsService;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment