gpt4 book ai didi

c# - 单元测试用例的最佳实践

转载 作者:行者123 更新时间:2023-12-02 02:08:02 24 4
gpt4 key购买 nike

我正在使用xUnit.net测试框架,在每个单元测试中,我都有在每种情况下执行的某些步骤。我想知道是否有一种方法可以在我的单元用例开始之前调用此方法一次,并在所有单元测试用例执行完毕后调用此方法。

例如:在下面的场景中,我有两个单元案例,在每种情况下,我都创建一个本地数据库,用数据填充它,然后运行我的测试,完成后我调用方法来删除数据库。我在每个测试用例中都这样做。我不想创建多次,而是希望创建一次并填充一次,然后在执行所有测试用例后删除数据库。对我来说,删除我创建的内容很重要,因为测试用例有某些情况,如果在执行测试时未创建数据库,这些情况将会失败。

[Fact]
public void UnitCase1()
{
CreateDb();
UploadData();
...//My set of operation to test this case
...//Assert
DeleteDb()
}

[Fact]
public void UnitCase2()
{
CreateDb();
UploadData();
...//My set of operation to test this case
...//Assert
DeleteDb()
}

在埃里克回答后进行编辑:(我尝试过,但不起作用)

public class CosmosDataFixture : IDisposable
{
public static readonly string CosmosEndpoint = "https://localhost:8081";
public static readonly string EmulatorKey = "Mykey";
public static readonly string DatabaseId = "Databasename";
public static readonly string RecordingCollection = "collectionName";
string Root = Directory.GetParent( Directory.GetCurrentDirectory() ).Parent.Parent.FullName;
DocumentClient client = null;

public void ReadAllData( DocumentClient client )
{
//reading document code
}

public void ReadConfigAsync()
{
client = new DocumentClient( new Uri( CosmosEndpoint ), EmulatorKey,
new ConnectionPolicy
{
ConnectionMode = ConnectionMode.Direct,
ConnectionProtocol = Protocol.Tcp

} );
}
public void CreateDatabase()
{// create db code
}
private void DeleteDatabase()
{
// delete db code
}
public CosmosDataFixture()
{
ReadConfigAsync();
CreateDatabase();
ReadAllData( client );

}

public void Dispose()
{
DeleteDatabase();
}
}
public class CosmosDataTests : IClassFixture<CosmosDataFixture>
{
CosmosDataFixture fixture;

public CosmosDataTests( CosmosDataFixture fixture )
{
this.fixture = fixture;
}

[Fact]
public async Task CheckDatabaseandCollectionCreation()
{
List<string> collectionName = new List<string>();
var uri = UriFactory.CreateDatabaseUri(DatabaseId);// don't get DatabaseId or client says does not exist in current context
var collections = await client.ReadDocumentCollectionFeedAsync( uri );
foreach( var collection in collections )
{
collectionName.Add( collection.Id);
}

}

最佳答案

这就是 NUnit 中 [SetUp][TearDown] 的用途。它们分别在每个测试用例之前和之后运行。在 xUnit 中,您通常会实现默认构造函数和 IDisposable

例如:


public TestClass()
{
CreateDb();
UploadData();
}


public void Dispose()
{
DeleteDb()
}

[Fact]
public void UnitCase1()
{
...//My set of operation to test this case
...//Assert
}

[Fact]
public void UnitCase2()
{
...//My set of operation to test this case
...//Assert
}

关于c# - 单元测试用例的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68118679/

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