Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/375.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java SpringCloudEureka-如何模拟RestTemplate以避免请求第二个服务_Java_Microservices_Spring Cloud_Spring Cloud Netflix - Fatal编程技术网

Java SpringCloudEureka-如何模拟RestTemplate以避免请求第二个服务

Java SpringCloudEureka-如何模拟RestTemplate以避免请求第二个服务,java,microservices,spring-cloud,spring-cloud-netflix,Java,Microservices,Spring Cloud,Spring Cloud Netflix,我正在尝试为我的一个微服务编写一个集成测试,在将对象保存到数据库中之前,调用另一个微服务以执行一些验证 由于第二个微服务未运行,我想模拟对外部服务的请求,但测试失败,出现错误: Condition failed with Exception: mockServer.verify() | | | java.lang.AssertionError: Further request(s) expected leaving 1 unsatisfied expecta

我正在尝试为我的一个微服务编写一个集成测试,在将对象保存到数据库中之前,调用另一个微服务以执行一些验证

由于第二个微服务未运行,我想模拟对外部服务的请求,但测试失败,出现错误:

Condition failed with Exception:

mockServer.verify()
|          |
|          java.lang.AssertionError: Further request(s) expected leaving 1 unsatisfied expectation(s).
|          0 request(s) executed.
|           
|           at org.springframework.test.web.client.AbstractRequestExpectationManager.verify(AbstractRequestExpectationManager.java:159)
|           at org.springframework.test.web.client.MockRestServiceServer.verify(MockRestServiceServer.java:116)
以下是测试逻辑:

@SpringBootTest(classes = PropertyApplication.class,
        webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
        properties = ["eureka.client.enabled:false"])
class TestPropertyListingServiceDemo extends IntegrationTestsSetup {
@Autowired
private PropertyListingService listingService
@Autowired
private RestTemplate restTemplate

private static MockRestServiceServer mockServer


def setup() {
    mockServer = MockRestServiceServer.createServer(restTemplate)
}


def "test: save listing for in-existent User"() {

    setup: "building listing with invalid user id"
    def listing = generatePropertyListing()

    mockServer.expect(once(), requestTo("http://user-service/rest/users/exists/trackingId=" + listing.getUserTID()))
            .andExpect(method(GET))
            .andRespond(withStatus(NOT_FOUND).body("No such user."))


    when: "saving listing"
    listingService.save(listing)

    then: "exception is thrown"
    mockServer.verify() // <------------- here I am getting the error

    BizItemBusinessValidationException e = thrown()
    e.getMessage() == "Listing could not be saved. User not found."
}
}

RestTemplate配置:

@Configuration
public class BeanConfiguration {

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

如有任何建议,将不胜感激。谢谢大家!

正如@Spencergib正确建议的那样,您可以在测试配置中模拟restTemplate

第二个选项,您可以尝试使用MockRestServiceServer

检查下面的链接。看看这对你的案子是否有帮助


为了执行测试,我执行了以下步骤:

1.禁用的eureka客户端

@SpringBootTest(classes = PropertyApplication.class,
        webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = ["eureka.client.enabled:false"])
1.禁用的eureka客户端 模仿@Spancergib建议的RestTemplate,并将Autowire注入我的服务(作为一个普通的Springbean)

  • 在模拟RestTemplate方法之前调用MockitoAnnotations.initMocks(this)

    initMocks(this) URI=URI.create(servicesConfig.getUsersServiceURI()+“/rest/users/exists/trackingId=“+userTID”)

  • Mockito.when(restemplatemock.getForEntity)(uri, ResponseEntity.class),然后返回(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)
        }
    }
    

    让您的测试创建一个模拟rest模板bean吗?
        @Mock
        RestTemplate restTemplateMock
    
        @Autowired
        @InjectMocks
        private PropertyListingService listingService
    
    @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)
        }
    }