我正在尝试使用C#进行一些简单的测试驱动开发测试.但是我没有真正的经验,我遇到了一些麻烦.
我正在尝试执行的测试是用于登录身份验证.以下是我到目前为止的情况.
using System;
namespace TimetableSystem
{
public class Timetable
{
public bool TimetableLogin(string username, string password)
{
throw new NotImplementedException();
}
}
}
Run Code Online (Sandbox Code Playgroud)
测试方法
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);
}
}
Run Code Online (Sandbox Code Playgroud)
这个测试一直在失败,我不确定为什么感谢任何帮助.
测试失败,因为您尚未实现登录方法(请参阅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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在测试项目中创建一个模拟作为登录服务的实现.此版本的服务仅用于测试.
public MockLoginService : ILoginService
{
public bool Login(string username, string password)
{
return (username == "Name" && password == "Password");
}
}
Run Code Online (Sandbox Code Playgroud)
然后在测试中:
[TestMethod]
public void TestLoginMethodValid()
{
MockLoginService mockLoginService = new MockLoginService();
Timetable auth = new Timetable(mockLoginService);
bool result = auth.TimetableLogin("Name", "Password");
Assert.IsTrue(result);
}
Run Code Online (Sandbox Code Playgroud)
现在您正在测试TimeTable.TimetableLogin中的逻辑而不是登录服务.接下来,您将实现要在生产中使用的ILoginService的真实版本,并且您可以确信TimeTable.TimetableLogin将按预期执行.