SWPCore/Tests/PostgresTests.cs

80 lines
2 KiB
C#
Raw Normal View History

using Autofac;
using Insight.Database;
using Shouldly;
using SWP.Core.Database;
using SWP.Core.Database.ConnectionFactory;
namespace SWP.Core.X.TDD;
[TestClass]
public class PostgresTests : TestFixture
{
private IDbConnectionFactory _connFactory;
private IDatabaseOperations _databaseOperations;
[TestInitialize]
public void MyTestMethod()
{
_connFactory = Container.Resolve<IDbConnectionFactory>();
_databaseOperations = Container.Resolve<IDatabaseOperations>();
}
[TestMethod]
public void TestDefaultConnection()
{
//https://stackoverflow.com/questions/69169247/how-to-create-idbconnection-factory-using-autofac-for-dapper
using (var conn = _connFactory.Create())
conn.ExecuteSql("SELECT 1 as p");
}
[TestMethod]
public async Task TestScopeConnectionWithLogging()
{
using var db = _databaseOperations.CreateScope(nameof(TestScopeConnectionWithLogging));
try
{
var user = await db.Connection.QuerySqlAsync<string>(
"SELECT tablename FROM pg_tables limit 5");
}
catch (Exception ex)
{
db.Error(ex);
throw;
}
}
[TestMethod]
public async Task TestScopeConnectionWithErrorLogging()
{
using var db = _databaseOperations.CreateScope(nameof(TestScopeConnectionWithLogging));
try
{
var user = await db.Connection.QuerySqlAsync<string>(
"SELECT tablename FROM pg_tables limit 5");
}
catch (Exception ex)
{
db.Error(ex);
}
}
[TestMethod]
public async Task TestSimpleDatabaseOperation()
{
try
{
await _databaseOperations.ExecuteAsync(async connection =>
{
return await connection.QuerySqlAsync<string>(
"SELECT tablename FROM pg_tables limit 5");
}, nameof(TestSimpleDatabaseOperation));
}
catch (Exception)
{
throw;
}
}
}