您没有正确实现代码以支持单元测试 - 您正在Database方法中创建外部对象 ()。另外,您没有使用IDatabase接口,而是使用的具体实现Database
public static User Connexion(String login, String MotDePasse)
{
Database bdd = new Database(); // this is inline, concrete implementation, this cannot be mocked
User us = bdd._Context.UserSet.FirstOrDefault(u => u.login == login);
if (us == null)
throw new Exception("Nom d'utilisateur erroné");
if (us.password != MotDePasse)
throw new Exception("Mot de passe erroné");
else
return us;
}
您至少应该阅读有关Dependency Injection的内容。
这个简短的示例可以帮助您了解代码中的问题
public static User Connexion(String login, String MotDePasse, IDatabase bdd)
{
User us = bdd._Context.UserSet.FirstOrDefault(u => u.login == login);
if (us == null)
throw new Exception("Nom d'utilisateur erroné");
if (us.password != MotDePasse)
throw new Exception("Mot de passe erroné");
else
return us;
}
这一次,Connexion 松散地绑定到 IDatabase 接口,而不是它的实现。在运行时,您将提供new Database()其值,但在测试时,模拟实现。