如何在ServiceStack中测试“ApplyTo.Post”RuleSet

时间:2017-06-16 21:33:42

标签: testing servicestack

我想测试我的验证器以了解下面描述的帖子行为。

public interface ITestValidator
{
    bool IsExists(string testName);
}

public class TestValidator : ITestValidator
{

    public bool IsExists(string testName)
    {
        return true;
    }
}

public class TestRequest
{
    public string Name { get; set; }
    public int? Level { get; set; }
}

public class TestRequestValidator : AbstractValidator<TestRequest>
{
    public ITestValidator Validator { get; set; }
    public TestRequestValidator()
    {
        RuleFor(p => p.Level).Must(p => p.HasValue && p > 0);
        RuleSet(ApplyTo.Post, () =>
        {
            RuleFor(p => p.Name).Must(p => !Validator.IsExists(p));
        });
    }
}

我用xunit创建了一个测试,如下所示。

[Fact]
public void test_should_not_be_valid()
{
    var validator = new TestRequestValidator();
    var validationResult = validator.Validate(new TestRequest
    {
        Level = 1,
        Name = null
    });

    Assert.False(validationResult.IsValid);
}

成功完成了这项测试
RuleFor(p => p.Level).Must(p => p.HasValue && p > 0);

但它不适用于

RuleFor(p => p.Name).Must(p => !Validator.IsExists(p));

如何为“ApplyTo.Post,ApplyTo.Get,ApplyTo.Delete”等多项操作测试验证器?

1 个答案:

答案 0 :(得分:2)

您应该能够使用以下内容测试HTTP方法的验证器:

var validator = new TestRequestValidator { 
    Validator = new TestValidator()
};

var result = validator.Validate(
    new ValidationContext(requestDto, null, new MultiRuleSetValidatorSelector("POST")));

Assert.False(result.IsValid);