我在某处读到每个测试必须只测试一件事。但是,良好实践手册中是否允许对类似行为进行分组?我目前正在编写一些测试(带有 NUnit 的 C#),下面是我所面临的一个示例:
[TearDown]
public void Cleanup()
{
Hotkeys.UnregisterAllLocals();
Hotkeys.UnregisterAllGlobals();
}
[Test]
public void KeyOrderDoesNotMatter()
{
Hotkeys.RegisterGlobal("Ctrl+Alt+P", delegate { });
Assert.That(Hotkeys.IsRegisteredGlobal("Alt+P+Ctrl"), Is.True);
}
[Test]
public void KeyCaseDoesNotMatter()
{
Hotkeys.RegisterGlobal("Ctrl+Alt+P", delegate { });
Assert.That(Hotkeys.IsRegisteredGlobal("ctrl+alt+p"), Is.True);
}
[Test]
public void KeySpacesDoesNotMatter()
{
Hotkeys.RegisterGlobal("Ctrl+Alt+P", delegate { });
Assert.That(Hotkeys.IsRegisteredGlobal("Ctrl + Alt + P"), Is.True);
}
分组后,它们将变为:
[TearDown]
public void Cleanup()
{
Hotkeys.UnregisterAllLocals();
Hotkeys.UnregisterAllGlobals();
}
[Test]
public void KeyIsNotStrict()
{
// order
Hotkeys.RegisterGlobal("Ctrl+Alt+A", delegate { });
Assert.That(Hotkeys.IsRegisteredGlobal("Alt+A+Ctrl"), Is.True);
// whitespace
Hotkeys.RegisterGlobal("Ctrl+Alt+B", delegate { });
Assert.That(Hotkeys.IsRegisteredGlobal("Ctrl + Alt + B"), Is.True);
// case
Hotkeys.RegisterGlobal("Ctrl+Alt+C", delegate { });
Assert.That(Hotkeys.IsRegisteredGlobal("ctrl+alt+c"), Is.True);
}
那么最佳实践是什么(如果存在),为什么?
obs:我对单元测试比较陌生...