6

I am testing the create class in Visual Studio 2012

My controller class is:

  public ActionResult Create()
    {
        return View();
    }

    //
    // POST: /Member/Create

    [HttpPost]
    public ActionResult Create(Member member)
    {
        if (ModelState.IsValid)
        {
            db.Members.Add(member);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(member);
    }

And test class is:

[TestClass]
public class MemberTest
{

    [TestMethod]
    public void Create(Member mem)
    {
        mem.MemID = 123;
        mem.MemName = "sruthy";


        /// dont know what is writing.

    }
}

SampleDataContext.cs

public class SampleDataContext:DbContext
{
    public DbSet<Member> Members { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}

I am stuck in test case please help me.

4

2 回答 2

5

首先 - 为您的数据访问代码创建一个抽象(模拟 DbContext 不是很方便的事情):

public interface IMemberRepository
{
    void Add(Member member);
}

并使您的控制器依赖它

public MemberController(IMemberRepository repository)
{
    this.repository = repository;
}

这将允许轻松地模拟数据访问代码。接下来 - 编写验证控制器行为的测试(我在这里使用 NUnit 和 Moq):

private MemberController controller;
private Mock<IMemberRepository> repositoryMock;
private Member member;

[SetUp]
public void Setup()
{
    repositoryMock = new Mock<IMemberRepository>();
    controller = new MemberController(repositoryMock.Object);
    member = new Member { MemID = 123, MemName = "sruthy" };
}

[Test]
public void ShouldCreateMemberWhenItIsValid()
{
    var result = (RedirectToRouteResult)controller.Create(member);
    Assert.That(result.RouteValues["action"], Is.EqualTo("Index"));
    repositoryMock.Verify(r => r.Add(member));
}

[Test]
public void ShouldNotCreateMemberWhenItIsNotValid()
{
    controller.ModelState.AddModelError("MemName", "Something wrong");
    var result = (ViewResult)controller.Create(member);
    Assert.That(result.ViewName, Is.Empty);
}

并编写实现:

[HttpPost]
public ActionResult Create(Member member)
{
    if (ModelState.IsValid)
    {
        repository.Add(member);
        return RedirectToAction("Index");
    }

    return View(member);
}
于 2013-09-30T10:30:10.733 回答
3

我在单元测试中的理解是:“只测试你的方法在做什么”所以我认为你必须测试你的方法是否做得很好:

  • 模型状态.IsValid

  • db.Members.Add(成员)

  • db.SaveChanges()

但不是 ModelState 或 DbContext 的良好行为。这些在他们自己的单元测试中进行测试。你必须断言只有调用完成。

要执行这种测试,您必须使用依赖注入模式并用模拟替换真实的 DbContext。这些模拟只是断言调用执行良好,而不涉及真正的 dbContext。

我不是单元测试方面的专家,但我认为您必须考虑所有架构才能解耦对象。这允许您用模拟替换真实对象。

于 2013-09-30T10:25:16.690 回答