gpt4 book ai didi

sql-server - 在单元测试之前运行脚本

转载 作者:行者123 更新时间:2023-12-03 00:23:09 30 4
gpt4 key购买 nike

SQL Server 单元测试中的测试初始化​​脚本在每个测试方法之前运行并在每个测试方法之后运行测试清理。

例如我有这个结构

UnitTests          -- Main Project
- FooSchema -- Test Class
- SprocFoo1 -- Individual Unit Tests / Test Methods
- SprocFoo2
- BarSchema
- SprocBar1
- SprocBar2

这样的测试运行

 -- Test Initialiaze for TestClass FooSchema
-- Pre-Test -- for SprocFoo1
-- Test -- for SprocFoo1
-- Post-Test -- for SprocFoo1
-- Pre-Test -- for SprocFoo2
-- Test -- for SprocFoo2
-- Post-Test -- for SprocFoo2
-- Test Cleanup for TestClass FooSchema
-- Test Initialiaze for TestClass BarSchema
-- Pre-Test -- for SprocBar1
-- Test -- for SprocBar1
-- Post-Test -- for SprocBar1
-- Pre-Test -- for SprocBar2
-- Test -- for SprocBar2
-- Post-Test -- for SprocBar2
-- Test Cleanup for TestClass BarSchema

如何添加一个将在项目开始时运行的脚本以及一个将在项目最后运行的脚本?

所以它会像这样运行

 -- Pre MasterUnitTest
-- Test Initialiaze for TestClass FooSchema
-- Pre-Test -- for SprocFoo1
-- Test -- for SprocFoo1
-- Post-Test -- for SprocFoo1
-- Pre-Test -- for SprocFoo2
-- Test -- for SprocFoo2
-- Post-Test -- for SprocFoo2
-- Test Cleanup for TestClass FooSchema
-- Test Initialiaze for TestClass BarSchema
-- Pre-Test -- for SprocBar1
-- Test -- for SprocBar1
-- Post-Test -- for SprocBar1
-- Pre-Test -- for SprocBar2
-- Test -- for SprocBar2
-- Post-Test -- for SprocBar2
-- Test Cleanup for TestClass BarSchema
-- Post MasterUnitTest

最佳答案

Visual Studio 设计者生成的 SQL 数据库单元测试实际上是常见的 MSUnit 测试类。

如果您想执行一些设置(Pre MasterUnitTest)和拆卸(Post MasterUnitTest)逻辑,您只需重构 Visual Studio 生成的测试并将它们嵌套在将运行设置和拆卸逻辑的类中。这是一个例子:

[TestClass]
public class NestedUnitTests
{
[ClassInitialize()]
public static void ClassInit(TestContext context) {
Debug.WriteLine("Init before all individual Test Classes");
}

[TestMethod]
public void Init()
{ }

[TestClass]
public class NestedFooSchemaTestClass
{
[TestMethod]
public void Test1InClass()
{
Debug.WriteLine("Test Class Foo Schema - Method 1");
Assert.AreEqual(true, true);
}
}

[TestClass]
public class NestedBarSchemaTestClass
{
[TestMethod]
public void Test2InClass()
{
Debug.WriteLine("Test Class Foo Bar - Method 2");
Assert.AreEqual(true, true);
}
}

[ClassCleanup()]
public static void ClassCleanup() {
Debug.WriteLine("Clean after all Test Classes executed");
}
}

当我用 TestRunner 运行它时,我得到:

Init before all individual Test Classes
Test Class Foo Schema - Method 1
Test Class Foo Bar - Method 2
Clean after all Test Classes executed

注意:使用此方法唯一无法实现的是在另一个类初始化之前执行类清理(例如,在 Bar 的类初始化之前执行 Foo 的类清理)。所有类的测试清理将在最后运行。这是因为在所有测试完成运行后,运行时会批量卸载测试类,这是有意为之,因为测试应该隔离

如果您想完全控制执行,另一种方法是通过使用 MSTest 命令行实用程序的自定义脚本来运行测试。这样您就可以运行前脚本(或预测试),然后运行主测试 dll,最后运行后脚本(或后测试)。

以下链接提供了如何从命令行使用 MSTest 的更多信息:

http://msdn.microsoft.com/en-us/library/jj155804.aspx

关于sql-server - 在单元测试之前运行脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25884894/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com