Чтобы выполнить мои тесты, я сделал следующие шаги:
1. Отключенный клиент eureka
@SpringBootTest(classes = PropertyApplication.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = ["eureka.client.enabled:false"])
1. Отключенный клиент eureka Mocked RestTemplate, предложенный @spancergibb, и ввел мою службу с помощью Autowire (как обычная пружинная фасоль)
@Mock
RestTemplate restTemplateMock
@Autowired
@InjectMocks
private PropertyListingService listingService
Вызывал MockitoAnnotations.initMocks (this) перед тем, как имитировать метод RestTemplate.
MockitoAnnotations.initMocks (this) URI uri = URI.create (servicesConfig.getUsersServiceURI () + "/ rest / users / exist / trackingId =" + userTID)
Mockito.when (restTemplateMock.getForEntity (uri, ResponseEntity.class)). ThenReturn (responseEntity)
Ниже приведен мой полный тестовый класс:
@SpringBootTest(classes = PropertyApplication.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = ["eureka.client.enabled:false"])
class TestPropertyListingService extends IntegrationTestsSetup {
@Mock
RestTemplate restTemplateMock
@Autowired
@InjectMocks
private PropertyListingService listingService
@Autowired
private PropertyService propertyService
static boolean testsSetupExecuted
static Property dbProperty
def setup() {
if (!testsSetupExecuted) {
schemaService.initSchema()
purgeCollection(PropertyListing.simpleName)
dbProperty = propertyService.save(generateProperty())
testsSetupExecuted = true
}
}
def "test: save listing for in-existent User"() {
setup:
def listing = generatePropertyListing()
listing.setPropertyTID(dbProperty.getTrackingId())
mockUserRestCall(listing.userTID, new ResponseEntity("Mocking: User not found", NOT_FOUND))
when: "saving listing"
listingService.save(listing)
then: "exception is thrown"
BizItemBusinessValidationException e = thrown()
e.getMessage() == "Listing could not be saved. User not found, UserTID = ${listing.userTID}"
}
def "test: save listing with past checkin/checkout date"() {
setup:
def listing = generatePropertyListing()
listing.setPropertyTID(dbProperty.getTrackingId())
mockUserRestCall(listing.userTID, new ResponseEntity("Mocked response", OK));
when: "saving with past dates"
listing.setCheckInDate(new Date(System.currentTimeMillis() - 100000))
listing.setCheckOutDate(new Date(System.currentTimeMillis() - 100000))
listingService.save(listing)
then: "exception is thrown"
BizItemSchemaValidationException e = thrown()
e.getMessage().startsWith('[PropertyListing] validation failed [[Invalid future date for [CheckIn Date] =')
e.getMessage().contains('Invalid future date for [CheckOut Date] =')
}
def mockUserRestCall(String userTID, ResponseEntity responseEntity) {
MockitoAnnotations.initMocks(this)
URI uri = URI.create(servicesConfig.getUsersServiceURI() + "/rest/users/exists/trackingId=" + userTID)
Mockito.when(restTemplateMock.getForEntity(uri, ResponseEntity.class)).thenReturn(responseEntity)
}
}