使用 Wiremock .NET C# 实现动态响应

huangapple go评论52阅读模式
英文:

Dynamic Response using Wiremock .NET C#

问题

我最近开始使用Wiremock .net来创建一个模拟API,它将在Kubernetes中运行。我在代码中有这一行,在Wiremock服务器启动时运行:

server
  .Given(
    Request.Create()
      .WithPath(_urlPath)
      .UsingPost()
      .WithBody(new XPathMatcher($"{_surname}='TestResponse'"))
  )
 .RespondWith(Response.Create()
   .WithStatusCode(200)
   .WithHeader("content-type", "text/xml;charset=UTF-8")
   .WithBody(GetTestData())
);

在我的测试数据响应中,我有一个CreatedDateTime。我想知道是否有一种有效的方法,在每次发送请求到Wiremock测试服务器时更改这个日期?

我目前的代码在一个循环中,不断读取响应文件并调用一个函数来更新响应中的日期。这样做可以工作,但我想知道是否有更好的方法。

英文:

I have recently started using wiremock .net to create a mock API which is going to be run in kubernetes. I have this line in my code which is ran when the Wiremock server is started:

server
  .Given(
    Request.Create()
      .WithPath(_urlPath)
      .UsingPost()
      .WithBody(new XPathMatcher($"{_surname}='TestResponse'"))
  )
 .RespondWith(Response.Create()
   .WithStatusCode(200)
   .WithHeader("content-type", "text/xml;charset=UTF-8")
   .WithBody(GetTestData())
);

In my Test Data response I have a CreatedDateTime. I was wondering is there an effective way to change this everytime a resquest is sent to the wiremock test server?

I currently have my code in a while loop which constanly reads the response file and calls a function to update the date in the response. It works but i was wondering of there is a better way please.

while (server.IsStarted)
{
    MockSetup.MockResponses(server);
    MockSetup.UpdateDates();
    Console.WriteLine("Mock Running");
    Thread.Sleep(30000);
    continue;
}

答案1

得分: 1

你可以使用 response templating 使用 Handlebars.Net.Helpers 生成一个新的 DateTime

示例:

{{DateTime.Now}}

// 或者

{{DateTime.Now \"yyyy-MM-dd\"}}
英文:

You can use response templating using Handlebars.Net.Helpers to generate a new DateTime.

Example:

{{DateTime.Now}}

// or

{{DateTime.Now \"yyyy-MM-dd\"}}

huangapple
  • 本文由 发表于 2023年4月17日 03:04:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76029833.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定