我正在使用NancyFX和FluentValidation,如https://github.com/NancyFx/Nancy/wiki/Nancy-and-Validation所述。我的web應用程序運行良好並驗證可以正常使用,但是當我試圖單元測試任何使用驗證模塊,我得到一個錯誤如何讓我的NancyFX單元測試運行我的驗證?
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.
我覈實,我的單元測試的項目有參考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($"https://stackoverflow.com/users/{USER_ID}/articles", with => {
with.HttpRequest();
with.Body(JsonConvert.SerializeObject(article));
});
result.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
}
}
我的模塊代碼是:
public class ArticlesModule : NancyModule {
private IDatabase database;
public ArticlesModule(IDatabase db) {
this.database = db;
Post["https://stackoverflow.com/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}");
}
}
和我的驗證類是:
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");
}
}
的NancyFX docs說:「創建驗證等級......沒有必要在任何地方註冊,因爲它會被自動檢測到。「 - 但我猜想,無論是自動檢測接線是不是爲單元測試項目開火。我在.NET 4.5.2上構建並使用NCrunch作爲測試運行器;我需要做什麼才能讓我的測試代碼像我的應用程序模塊那樣獲取相同的驗證類?
Nancy.Validation.FluentValidation需要在單元測試項目中安裝,不幸的是 – Jon
它已經安裝,但NCrunch在構建測試項目時忽略了它。我已經更新了https://github.com/NancyFx/Nancy/wiki/Nancy-and-Validation並提供了相應的說明。 –