使用Hoverfly和Java测试第3部分:状态

以前,我们使用Hoverfly模拟了一个延迟情况。 现在是时候深入研究并进行基于状态的测试了。 通过进行有状态仿真,我们可以根据状态如何更改测试端点的行为方式。

Hoverfly确实具有状态功能。 Hoverfly模拟中的状态就像一张地图。 最初它是空的,但是您可以定义如何根据每个请求填充它。

我们的策略是拥有一个初始化状态的请求,然后指定更改该状态的其他请求。

 public class SimulationStateTests { 
    private Hoverfly hoverfly; 
    @BeforeEach

    void setUp() {

        var simulation = SimulationSource.dsl(service( " http://localhost:8085 " )

                .get( "/initialize" )

                .willReturn(success( "{\"initialized\":true}" , "application/json" )

                        .andSetState( "shouldSucceed" , "true" )

                )

                .get( "/state" )

                .withState( "shouldSucceed" , "false" )

                .willReturn(serverError().andSetState( "shouldSucceed" , "true" ))

                .get( "/state" )

                .withState( "shouldSucceed" , "true" )

                .willReturn(success( "{\"username\":\"test-user\"}" , "application/json" )

                        .andSetState( "shouldSucceed" , "false" )) 
        );

        var localConfig = HoverflyConfig.localConfigs().disableTlsVerification().asWebServer().proxyPort( 8085 );

        hoverfly = new Hoverfly(localConfig, SIMULATE);

        hoverfly.start();

        hoverfly.simulate(simulation);

    }

    @AfterEach

    void tearDown() {

        hoverfly.close();

    }
 }

不幸的是,在状态上,我们只能以键值方式指定值,而不能通过为键传递函数。但是,通过正确的解决方法,可以模拟许多情况。

在示例中,我们首先初始化状态,然后发出基于状态而行为不同的请求,但它们也会更改状态。

因此,我们希望有一个连续的先成功然后失败模式,可以在下面的测试中进行描述。

 @Test

    void testWithState() {

        var client = HttpClient.newHttpClient();

        var initializationRequest = HttpRequest.newBuilder()

                .uri(URI.create( " http://localhost:8085/initialize " ))

                .build();

        var initializationResponse = client.sendAsync(initializationRequest, HttpResponse.BodyHandlers.ofString())

                .thenApply(HttpResponse::body)

                .join();

        Assertions.assertEquals( "{\"initialized\":true}" , initializationResponse); 
        var statefulRequest = HttpRequest.newBuilder()

                .uri(URI.create( " http://localhost:8085/state " ))

                .build();

        for ( int i = 0 ; i < 100 ; i++) {

            var response = client.sendAsync(statefulRequest, HttpResponse.BodyHandlers.ofString())

                    .join();

            int statusCode = i % 2 == 0 ? 200 : 500 ; 
            Assertions.assertEquals(statusCode, response.statusCode());

        }

    }

这就是有状态模拟的全部内容。 在下一部分中,我们将继续进行Hoverfly匹配器。

翻译自: https://www.javacodegeeks.com/2020/09/testing-with-hoverfly-and-java-part-3-state.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值