0

I have previously developed in Rails. I found writing tests pretty easy, and I have recently moved to a project where MVC .NET is used for our main product.

I have figured out how to work with MVC .NET, but I still am not sure on how I should go around writing unit tests for my models. I will give a really quick dirty example on how I would write my unit test in rails:

describe "user.name_is_newton?" 

  context "user's name is newton" do
    before :each do
      @user = User.create(:name => "newton")
    end

    it { @user.name_is_newton?.should be_true }
  end    
end

The reason I am finding it hard to switch is because I am used to Rails providing a separate database for testing. It will (apparently) create a User entry in the test database behind the scenes and make it very easy to write the test. I am not sure how write a similar test in MVC .NET. Any help is appreciated! Thanks!

4

1 回答 1

0

在 MVC 中,您通常根本不想使用数据库进行单元测试,而是尝试重构,以便您测试作用于 IEnumerable<[entity]> 或 IQueryable<[entity]> 甚至只是实体本身。这样,您的单位就可以尽可能地处理一般的“事情”。但也许我在告诉你一些你已经知道的事情。

如果您绝对必须处理更复杂的对象,则需要模拟它们,或者再次重构以使用接口并只是模拟接口。

我确实有一个有用的 MVC 模拟库,例如 HttpContextBase、HtmlHelper、HttpResponseBase、DbSet,以及像 ShouldEqual 这样的助手。它们太长了,无法在此处不必要地粘贴,但请询问,我会很乐意提供它们。他们使用最小起订量。

您上面使用 Moq 的示例可能是:

测试方法:

public User CreateUser(string name)
{
    return new User { Name = name };
}

单元测试:

[Test]
public void CreateUser_NameIsNewton()
{
     var user = CreateUser("Newton");
     Assert.AreEqual(user.Name, "Newton");
}
于 2012-07-11T12:11:40.980 回答