Using Moq can you verify a method call with an anonymous type?

前端 未结 3 1826
萌比男神i
萌比男神i 2021-02-18 17:50

I\'m trying to verify a method call using Moq, but I can\'t quite get the syntax right. Currently I\'ve go this as my verify:

repository.Verify(x => x.Execute         


        
3条回答
  •  鱼传尺愫
    2021-02-18 18:39

    This Passes

            public class Class1
        {
            private Class2 _Class2;
            public Class1(Class2 class2)
            {
                _Class2 = class2;
            }
    
            public void DoSomething(string s)
            {
                _Class2.ExecuteNonQuery(s, new { fid = 123,  inputStr = "000456" });
            }
        }
    
        public class Class2
        {
            public virtual void ExecuteNonQuery(string s, object o)
            {
            }
        }
    
        /// 
        ///A test for ExecuteNonQuery
        ///
        [TestMethod()]
        public void ExecuteNonQueryTest()
        {
            string testString = "Hello";
            var Class2Stub = new Mock();
            Class1 target = new Class1(Class2Stub.Object);
            target.DoSomething(testString);
            Class2Stub.Verify(x => x.ExecuteNonQuery(testString, It.Is(o => o.Equals(new { fid = 123, inputStr = "000456" }))), Times.Once());
        }
    
    
    

    Update

    That is strange, it doesn't work in different assemblies. Someone can give us the long definition about why the object.equals from different assemblies behaves differently, but for different assemblies this will work, any variance in the object values will return a different hash code.

            Class2Stub.Verify(x => x.ExecuteNonQuery(testString, It.Is(o => o.GetHashCode() == (new { fid = 123, inputStr = "000456" }).GetHashCode())), Times.Once());
    
        

    提交回复
    热议问题