3

我在 Castle 的主干上运行,并尝试对设置了 DTO 验证的控制器操作进行单元测试。控制器继承自 SmartDispatcherController。动作和 DTO 如下所示:


[AccessibleThrough(Verb.Post)]
public void Register([DataBind(KeyReg, Validate = true)] UserRegisterDto dto)
{
    CancelView();
    if (HasValidationError(dto))
    {
        Flash[KeyReg] = dto;
        Errors = GetErrorSummary(dto);
        RedirectToAction(KeyIndex);
    }
    else
    {
        var user = new User { Email = dto.Email };
        // TODO: Need to associate User with an Owning Account
        membership.AddUser(user, dto.Password);
        RedirectToAction(KeyIndex);
    }
}

public class UserRegisterDto
{
    [ValidateNonEmpty]
    [ValidateLength(1, 100)]
    [ValidateEmail]
    public string Email { get; set; }

    [ValidateSameAs("Email")]
    public string EmailConfirm { get; set; }

    [ValidateNonEmpty]
    public string Password { get; set; }

    [ValidateSameAs("Password")]
    public string PasswordConfirm { get; set; }

    // TODO: validate is not empty Guid
    [ValidateNonEmpty]
    public string OwningAccountIdString { get; set; }

    public Guid OwningAccountId
    {
        get { return new Guid(OwningAccountIdString); }
    }

    [ValidateLength(0, 40)]
    public string FirstName { get; set; }

    [ValidateLength(0, 60)]
    public string LastName { get; set; }
}

单元测试如下所示:


[Fact]
public void Register_ShouldPreventInValidRequest()
{
    PrepareController(home, ThorController.KeyPublic, ThorController.KeyHome, HomeController.KeyRegister);

    var dto = new UserRegisterDto { Email = "ff" };
    home.Register(dto);

    Assert.True(Response.WasRedirected);
    Assert.Contains("/public/home/index", Response.RedirectedTo);
    Assert.NotNull(home.Errors);
}

(“home”是我在测试中的 HomeController 实例;home.Errors 包含对 ErrorSummary 的引用,当出现验证错误时应该将其放入 Flash)。

我看到调试器认为 dto 没有验证错误;它显然应该有几个失败,测试运行的方式。

我已经阅读了Joey 关于此的博客文章,但自从写完这篇文章后,Castle 的树干似乎已经搬走了。有人可以阐明一下吗?

4

1 回答 1

1

http://www.candland.net/blog/2008/07/09/WhatsNeededForCastleValidationToWork.aspx似乎包含一个答案。

于 2008-12-27T12:16:59.487 回答