假模拟数据2个不同属性的相同值

时间:2019-11-22 14:35:11

标签: c# asp.net-core .net-core bogus

伪造的数据具有相同的值对于2个不同的属性,可能有2个属性在流畅的api中具有相同的值。

var users = new Faker<User>()
   .StrictMode(false)
   .RuleFor(o => o.Id, f => orderIds++)
   .RuleFor(o => o.UserName, f => f.Person.FullName) // This needs to be same as the next property
   .RuleFor(o => o.NormalizedUserName, f => f.Person.FullName) // This should be same but uppercase

想要的生成数据:

[
  {
   userName: "Ivan Horvat",
   normalizedUserName: "IVAN HORVAT"
  },
  {
   userName: "John Doe",
   normalizedUserName: "JOHN DOE"
  }
]

我希望生成的每个实体都具有相同的UserNameNormalizedUsername,但每个实体都有自己的实体。

2 个答案:

答案 0 :(得分:2)

以下按预期工作

[TestClass]
public class MyTestClass1 {
    [TestMethod]
    public void MyTestMethod() {
        //Arrange
        int orderIds = 0;

        var faker = new Faker<User>()
           .StrictMode(false)
           .RuleFor(o => o.Id, f => ++orderIds)
           .RuleFor(o => o.UserName, f => f.Person.FullName) // This needs to be same as the next property
           .RuleFor(o => o.NormalizedUserName, f => f.Person.FullName.ToUpper()) // This should be same but uppercase
           .RuleFor(o => o.Email, f => $"{f.Person.FirstName}.{f.Person.LastName}@company.com");
        //Act
        var user = faker.Generate();

        //Assert
        user.UserName.ToUpper().Should().Be(user.NormalizedUserName);
    }

    public class User {
        public int Id { get; internal set; }
        public string UserName { get; internal set; }
        public string NormalizedUserName { get; internal set; }
        public string Email { get; internal set; }
    }
}

所有创建的实例均具有所需的值,如注释中所示。请注意,ToUpper()

使用了NormalizedUserName

答案 1 :(得分:1)

也可以通过使用RuleFor(Prop, (f, usr) =>)重载来使两个属性具有相同的值。

void Main()
{
   int orderIds = 0;
   var users = new Faker<User>()
      .StrictMode(false)
      .RuleFor(o => o.Id, f => orderIds++)
      .RuleFor(o => o.UserName, f => f.Person.FullName) // This needs to be same as the next property
      .RuleFor(o => o.NormalizedUserName, (f, usr) => usr.UserName.ToUpper()); // This should be same but uppercase

   users.Generate(3).Dump();
}

public class User{
   public int Id{get;set;}
   public string UserName{get;set;}
   public string NormalizedUserName {get;set;}
}

results