【问题标题】:Mock get wrong connection String模拟得到错误的连接字符串
【发布时间】:2016-07-10 14:48:01
【问题描述】:

我正在编写一些测试。我在嘲笑实体框架。昨天一切正常,我几乎可以肯定我昨天没有修改任何东西。 在我的测试项目的 app.config 中,我有这个连接字符串

<connectionStrings>
  <add name="PublicAreaContext"
      providerName="System.Data.SqlClient" connectionString="Server=.\SQLSERVER; ..." />
</connectionStrings>

现在我模拟我的实体框架上下文:

var mockContext = new Mock<PublicAreaContext>() { CallBase = true };
... // all my entities mocked
mockContext.Setup(x => x.SaveChanges()).Returns(1);

现在当我开始测试时出现问题,并且上下文似乎是使用错误的连接字符串创建的

我不明白该连接字符串在哪里...我在解决方案 SQLEXPRESS 中寻找它,但没有找到任何东西。在我的服务器 (SQLSERVER) 中,我可以找到一个名为 Castle.Proxy.PublicAreaContext 的数据库。我认为是昨天一切正常时创建的数据库。

您能告诉我可能是什么问题或如何正确设置连接字符串吗?

谢谢

【问题讨论】:

  • 你能向实际使用连接字符串的代码和传入它的代码展示吗?
  • 这可能是因为 CallBase 正在调用默认的 DbContext 构造函数,除非传递了数据库或连接字符串名称,否则将尝试使用上下文类型的名称创建一个。跨度>
  • @haim770: 如果我设置CallBase = false 我得到这个错误:The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.
  • @Spock 我已经改变了......我从我的帖子中删除了“单位”这个词。现在更清楚了

标签: c# entity-framework testing mocking moq


【解决方案1】:

我已经解决了……

我认为当我模拟上下文时,上下文会更改其名称...所以找不到 connectionString... 我更改了上下文,添加了以下构造函数:

public partial class PublicAreaContext : DbContext, IDataContext
{
    public PublicAreaContext() 
        : base("PublicAreaContext") //Here go the name of connection string
    {

    }

    ...
}

【讨论】:

    猜你喜欢
    • 2011-08-17
    • 2013-02-11
    • 1970-01-01
    • 2015-06-05
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    相关资源
    最近更新 更多