【问题标题】:Moq'ing Reference VariablesMoq'ing 参考变量
【发布时间】:2010-11-12 21:58:44
【问题描述】:

我们开始看到测试驱动开发的好处,并决定采取第一步让 TDD 驱动我们的设计。 (AKA 只是测试)然后希望一旦我们看到测试的好处以及糟糕的模拟如何让我们设计得很好,我们将远离它们并重构.. yada yada,无论如何

我发现了一些相似的主题,但没有什么是我真正可以建立的。我有如下内容:

<Test()>
  Public Sub TestMockWithReferenceVariable()
   Dim expected As New Dictionary(Of String, Object)
   expected.Add("test", 1)
   Dim pass As New Dictionary(Of String, Object)


   Dim mock = New Moq.Mock(Of ITestDM)()
   mock.Setup(Function(m) m.Load(Of String)("test", pass)).Returns("Test")

   Dim sing As New DMSinglton(mock.Object)
   Dim result As String = sing.Load(Of String)("test", pass)

   Assert.AreEqual("Test", result)
   Assert.AreEqual(expected, pass)
  End Sub



 Public Interface ITestDM
  Function Load(Of T)(ByVal sp As String, ByVal params As Dictionary(Of String, Object)) As T
 End Interface

有没有办法让我使用 Moq 将传入的字典更改为不同的字典,从而允许这些测试通过?

【问题讨论】:

  • 我不明白你的例子,因为不清楚“DMSinglton”类做什么以及测试到底想要断言什么。请编辑。顺便说一句:如果“DMSinglton”真的是一个单例(根据设计模式),则不能调用“new”。

标签: vb.net unit-testing mocking moq


【解决方案1】:

您可以使用单元测试框架中的集合支持在 MOQ 之外执行此操作。我至少可以想到两种使用 MsTest 或使用 SequenseEquals Linq 方法来实现此目的的方法。

Dictionary<string, string> dict = new Dictionary<string, string> { { "test", "test" } };
Dictionary<string, string> dict2 = new Dictionary<string, string> { { "test", "test" } };
//MsTest CollectionAssert tests if two collections contain the same elements
CollectionAssert.AreEquivalent(dict, dict2);
//Another way to do the same thing - using SequenceEquals
Assert.IsTrue(dict.SequenceEqual(dict2));

假设字典中使用的引用类型覆盖Equals 方法,这将起作用(值类型将开箱即用)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-17
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    • 2021-10-26
    • 2020-04-02
    相关资源
    最近更新 更多