在 ASP.NET Core MVC Web 应用程序中,我需要测试我的数据库,因此我创建了一个包含
DbContext
的项目。现在我需要测试这个数据库(DbContext
),尽管我读过一些文章,指出测试最好使用内存数据库来执行。
但是我需要使用我的实际数据库,因为它有很多数据,很难在单元测试中播种。
为了测试数据库,我编写了这个测试类:
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using WERP.DataAccess.Data;
namespace TestDbContext
{
[TestClass]
public class UnitTest1
{
const string CONN_STRING =
@"Server=.\\SQLEXPRESS;Database=WERP;Trusted_Connection=True;TrustServerCertificate=True";
private ApplicationDbContext _dbContext;
[TestInitialize]
public void Setup()
{
var serviceProvider = new ServiceCollection()
.AddEntityFrameworkSqlServer()
.BuildServiceProvider();
var builder =
new DbContextOptionsBuilder<ApplicationDbContext>();
builder.UseSqlServer(CONN_STRING).UseInternalServiceProvider(serviceProvider);
_dbContext = new ApplicationDbContext(builder.Options);
}
[TestMethod]
public void TestMethod1()
{
Assert.IsNotNull(_dbContext); // ok
Assert.IsNotNull(_dbContext.Currencies); //ok
Assert.IsNotNull(_dbContext.Currencies.FirstOrDefault()); //Instance Failure error
}
}
}
但是我在单元测试结果中收到错误“实例失败”。我做错了什么?如何解决这个问题,以便能够测试数据库?
错误堆栈跟踪:
TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnectionString connectionOptions, Boolean withFailover)
SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
SqlInternalConnectionTds.ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, DbConnectionPool pool)
SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
SqlConnection.TryOpen(TaskCompletionSource`1 retry, SqlConnectionOverrides overrides)
SqlConnection.Open(SqlConnectionOverrides overrides)
SqlConnection.Open()
SqlServerConnection.OpenDbConnection(Boolean errorsExpected)
RelationalConnection.OpenInternal(Boolean errorsExpected)
RelationalConnection.Open(Boolean errorsExpected)
RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
Enumerator.InitializeReader(Enumerator enumerator)
<>c.<MoveNext>b__21_0(DbContext _, Enumerator enumerator)
SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
Enumerator.MoveNext()
Enumerable.TryGetSingle[TSource](IEnumerable`1 source, Boolean& found)
lambda_method171(Closure, QueryContext)
QueryCompiler.Execute[TResult](Expression query)
EntityQueryProvider.Execute[TResult](Expression expression)
UnitTest1.TestMethod1() line 34
RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)
MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
连接字符串 .\SQLEXPRESS 而不是 .\SQLEXPRESS 中出现错误