Dyl*_*tie 1 unit-testing fluentvalidation nancy
我正在使用NancyFX和FluentValidation,如https://github.com/NancyFx/Nancy/wiki/Nancy-and-Validation所述.我的网络应用程序运行正常,验证工作正常,但当我尝试对任何使用验证的模块进行单元测试时,我收到错误
Nancy.Validation.ModelValidationException : No model validator factory could be located.
Please ensure that you have an appropriate validation package installed, such as
one of the Nancy.Validation packages.
Run Code Online (Sandbox Code Playgroud)
我已经验证我的单元测试项目引用了 Nancy.Validation.FluentValidation和FluentValidation程序集.
我的测试代码如下所示:
public class ArticleModuleTests {
private Browser browser;
private IDatabase db;
const int USER_ID = 123;
const int ARTICLE_ID = 456;
[SetUp]
public void SetUp() {
var user = new User { Username = "test", Id = USER_ID };
db = A.Fake<IDatabase>();
browser = new Browser(with => {
with.Module<ArticleModule>();
with.RequestStartup((container, pipelines, context) => context.CurrentUser = user);
with.Dependency(db);
});
}
[Test]
public void User_Can_Publish_Article() {
var article = new { title = "Test" };
var result = browser.Post($"/users/{USER_ID}/articles", with => {
with.HttpRequest();
with.Body(JsonConvert.SerializeObject(article));
});
result.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
}
}
Run Code Online (Sandbox Code Playgroud)
我的模块代码是:
public class ArticlesModule : NancyModule {
private IDatabase database;
public ArticlesModule(IDatabase db) {
this.database = db;
Post["/users/{id:int}/articles"] = args => PostArticle(args.id);
}
private dynamic PostArticle(int userId) {
var article = this.Bind<Article>();
var validation = this.Validate(article);
if (!validation.IsValid) return Negotiate.WithModel(validation).WithStatusCode(HttpStatusCode.BadRequest);
database.CreateArticle(userId, article);
return NegotiatorExtensions.WithModel(Negotiate, result)
.WithStatusCode(HttpStatusCode.Created)
.WithHeader("Location", $"http://whatever/users/{userId}/articles/{article.Id}");
}
}
Run Code Online (Sandbox Code Playgroud)
我的验证课是:
public class ArticleValidator : AbstractValidator<Article> {
public ArticleValidator() {
RuleFor(article => article.Title)
.NotEmpty()
.WithMessage("The \"title\" property is required");
RuleFor(article => article.Title)
.Length(2, 50)
.WithMessage("The \"title\" property must be between 2 and 50 characters");
}
}
Run Code Online (Sandbox Code Playgroud)
该NancyFX文档说:"创建一个验证类...有没有必要,因为它是自动检测到任何地方注册." - 但我猜测任何自动检测都没有为单元测试项目开火.我正在使用.NET 4.5.2并使用NCrunch作为我的测试运行器; 我需要做些什么来让我的测试代码获取与我的应用程序模块相同的验证类?
好的,事实证明,因为NancyFX会自动检测并实例化验证类,所以我的代码中没有明确的引用Nancy.Validation.FluentValidation,因此NCrunch在构建我的测试项目时省略了这个程序集.在NCrunch项目设置中设置"将引用的组件复制到工作区"修复了它.
| 归档时间: |
|
| 查看次数: |
333 次 |
| 最近记录: |