集成测试是否应该重做使用模拟的单元测试?

时间:2018-08-07 19:03:24

标签: c# unit-testing tdd

在编写单元测试时,我一次只会检查一门课。如果我需要使用其他类,那么我将使用模拟来确保测试是独立的。

稍后我想编写集成测试,是否应该只复制/粘贴所有使用模拟的单元测试,并在删除模拟对象之后对其进行测试?

示例代码:

public class Event
{
    string title;
    List<Hour> hoursList = new List<Hour>();
    public Event(string title) { this.title = title; }
    public void AddHour(Hour newHour) { hoursList.Add(newHour); }
    public int HourCount() { return hoursList.Count; }
    public int TotalDuration() {
        int total = 0;
        foreach (var hour in hoursList)
        total += hour.GetDuration();
        return total;
    }
}
public class Hour
{
    string start;
    string end;
    public Hour(string start, string end) { this.start = start; this.end = end; }
    public virtual int GetDuration() { /* algorightm calculating duration in minutes */  }
}

示例测试:

int expected = 165;
Event Concert = new Event("Local band concert");
Mock<Hour> ehMock = new Mock<Hour>("07:00", "08:30");
ehMock.Setup(x => x.GetDuration()).Returns(90);
Mock<Hour> ehMock2 = new Mock<Hour>("19:15", "20:30");
ehMock2.Setup(x => x.GetDuration()).Returns(75);
Concert.AddHour(ehMock.Object);
Concert.AddHour(ehMock2.Object);
Assert.AreEqual(expected, Concert.TotalDuration());

在上面的单元测试中,我正在测试Event类的TotalDuration方法,模拟了Hour类,并重写了GetDuration()方法。现在我应该使用相同的测试进行集成测试,但是没有模拟吗?

也许上面的例子太简单了,不需要集成测试。如果我要进行更高级的单元测试,那么建议使用相同功能的集成测试?

2 个答案:

答案 0 :(得分:2)

一个更抽象的答案:这两件事的范围完全不同。

单元测试可以测试单个单元的所有方面。所有单元,所有功能。进行隔离测试。换句话说:您构建了一大堆乐高积木,并且单元测试告诉您所有这些构建块完全可以完成他们应该做的事情。

另一方面:集成测试归结为确保正确的集成。含义:您想出了最重要的“路径”,您想采用它,并编写了集成/功能测试以锤炼这些路径。

testing pyramid的全部要点是保留单元测试,以便可以编写数量更少的集成测试。因为单元测试可以快速运行,并且可以帮助您快速识别和修复错误。集成测试更为重要,但同时 价格更高*,并且您将它们用于无法正确进行单元测试的事情。

因此:当然,集成测试将“测试”您的单元测试已验证的内容。但是,您只是想将所有单元测试简单地转换为集成测试。

答案 1 :(得分:0)

在这种确切的情况下,由于没有在<?php $the_message = "Welcome"; if($session->is_signed_in()){ echo $session->is_signed_in(); //redirect("index.php"); } if (isset($_POST['submit'])){ $username = trim($_POST['username']); $password = trim($_POST['password']); //METHOD 1to check database user if exists, otherwise sign UP BUDDY! $user_found = User::verify_user($username, $password); //METHOD 2 Check the database. if($user_found){ $session->login($user_found); redirect("index.php"); } else { $the_message = "Your password or username are incorrect"; } //The page is loaded and $user_FOUND is not found } else { $username = ""; $password =""; } ?> 中进行任何设置,因此无法从模拟中获得任何好处,因此进行不带模拟的集成测试也可以做到这一点。此外,向构造函数添加参数,例如“ 07:00”,这意味着您实际上正在反对模拟,因为这种情况一直都是一种确切的情况。 Tldr;我将此示例称为集成测试。

相关问题