C#测试驱动开发

时间:2018-04-19 14:14:56

标签: c# tdd

我正在尝试使用C#进行一些简单的测试驱动开发测试。但是我没有真正的经验,我遇到了一些麻烦。

我正在尝试执行的测试是用于登录身份验证。以下是我到目前为止的情况。

using System;

namespace TimetableSystem 
{
    public class Timetable 
    { 
        public bool TimetableLogin(string username, string password)
        {
            throw new NotImplementedException();
        }
    }
}

测试方法

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TimetableSystem;

namespace TimetableSystemTests
{
    [TestClass]
    public void TestLoginMethodValid()
    {
        Timetable auth = new Timetable();
        bool result = auth.TimetableLogin("Name", "Password"); 
        Assert.IsTrue(result);
    }
}

此测试一直失败,我不确定为什么要感谢任何帮助。

1 个答案:

答案 0 :(得分:5)

测试失败,因为您还没有实现登录方法(请参阅NotImplementedException),这是在测试驱动开发中设计的。你编写了足够的代码,以便在不实现的情况下编译方法和测试,然后你去实现你的方法,以便测试通过。

将登录服务注入您的TimeTable类:

public interface ILoginService
{
   bool Login(string username, string password);
}

public class TimeTable
{
   ILoginService _loginService;
   public TimeTable(ILoginService loginService)
   {
     _loginService = loginService;
   }

   public bool TimeTableLogin(string username, string password)
   {
      return loginService.Login(username, password);
   }
}

然后在您的测试项目中创建一个模拟作为您的登录服务的实现。此版本的服务仅用于测试。

public MockLoginService : ILoginService
{
   public bool Login(string username, string password)
   {
     return (username == "Name" && password == "Password");
   }
}

然后在测试中:

[TestMethod]
public void TestLoginMethodValid()
{
  MockLoginService mockLoginService = new MockLoginService();
  Timetable auth = new Timetable(mockLoginService);
  bool result = auth.TimetableLogin("Name", "Password"); 
  Assert.IsTrue(result);
}

现在您正在测试TimeTable.TimetableLogin中的逻辑而不是登录服务。接下来,您将实现要在生产中使用的ILoginService的真实版本,并且您可以确信TimeTable.TimetableLogin将按预期执行。