Tag: moq

如何使用Moq存根接口方法

有没有办法使用Moq存根方法? 我看到了很多类似头衔的问题,但实际上没有一个回答我的问题。 这是我给出的unit testing示例,我发现使用Moq进行测试非常困难。 我想做的是unit testingEmailTask​​s.UserIsValidForNotice()方法: public class User { public DateTime JoinDate { get; set; } public bool Active { get; set; } } public class EmailTasks { IUserRepository repo; public EmailTasks(IUserRepository repo) { this.repo = repo; } public IList UserIsValidForNotice(DateTime minDate) { return repo.FindAll(u => u.Active && u.JoinDate > minDate); } } public […]

Moq多界面问题

这可能是也可能不是多接口问题,但我做的是这样的: var mockInterface1 = new Mock(); var mockInterface2 = mockInterface1.As(); mockInterface1.Expect( foo => foo.Foo(It.IsAny() ) ); … otherObject.DoSomething( (IInterface1)mockInterface2.Object ); 在运行时的DoSomething行上,我得到: MyTest(TestFixtureSetUp):System.Reflection.TargetInvocationException:调用目标抛出了exception。 —-> System.TypeInitializationException:’IInterface1Proxy184f83d417624e05b450fa40c2c5d35c’的类型初始值设定项引发exception。 —-> System.BadImageFormatException:尝试加载格式不正确的程序。 (HRESULTexception:0x8007000B) 这是否与我没有正确的Expect代码有关,或者它与我的模拟中的多个接口有关,还是其他什么?

模拟一种测试方法

试图模拟在另一个方法中调用的方法。 public virtual bool hello(string name, int age) { string lastName = GetLastName(); } public virtual string GetLastName() { return “xxx”; } Mock name= new Mock(); name.Setup(x => x.GetLastName()).Returns(“qqq”); 我希望方法GetLastName始终返回“qqq”。

在CRM 2011插件中模拟IOrganizationService.Execute的问题

我仍然是嘲笑的新手,我遇到了这段代码的问题: //create the request SendEmailFromTemplateRequest emailUsingTemplateReq = new SendEmailFromTemplateRequest { Target = email, TemplateId = new Guid(“07B94C1D-C85F-492F-B120-F0A743C540E6”), RegardingId = toParty[0].PartyId.Id, RegardingType = toParty[0].PartyId.LogicalName }; //retrieve response SendEmailFromTemplateResponse emailUsingTemplateResponse = (SendEmailFromTemplateResponse)service.Execute(emailUsingTemplateReq); var emailId = emailUsingTemplateResponse.Id; 到目前为止,我没有遇到过模拟IOrganizationService的问题,但我对execute方法做错了。 根据sdk,Execute方法返回一个需要转换为正确响应类的OrganizationResponse对象。 这是我到目前为止所尝试的: var idResults = new ParameterCollection(); idResults.Add(“Id”, Guid.NewGuid()); mockOrganizationService .Setup(os => os.Execute(It.IsAny())) .Returns(new OrganizationResponse { Results = idResults, ResponseName […]

Moq和reflection,将动态生成的表达式树/ lambda传递给moq

是否可以编写如下代码。 我正在尝试将Moq与我正在反思的对象一起用作测试框架的一部分。 下面的代码从Moq引出了一个“Unhandled expression type:’Goto’”exception,我猜这个exception会有所不同。 它看起来应该工作了! private void button1_Click(object sender, EventArgs e) { Ifoo = foo Foo(); // Create input parameter for lambda ParameterExpression value = Expression.Parameter(typeof(IFoo), “value”); // create return statement for lambda Expression setupProperty = Expression.Return(Expression.Label(), Expression.Property(value, “Bar”), typeof(string)); // convert expression to lambda (should now be the equivalent of “v => v.Bar”) […]

当从匿名函数调用It.Is …()时,为什么Moq设置/validation匹配器失败

当尝试简化为与Moq匹配的Setup / Verify匹配创建相当复杂的表达式树时,我遇到了一些奇怪的行为。 假设我在嘲笑下面定义的简单接口 public interface IService { int Send(int value); } 以下代码表示5个测试。 每个mockSender.Setup(…)一个测试。 任何人都可以解释为什么标记为失败的测试失败了吗? [Test] public void TestInlineSetup() { const int expected = 5; var mockSender = new Mock(MockBehavior.Loose); //passes mockSender.Setup(s => s.Send(It.IsAny())).Returns(expected); //fails var sendMatch = It.IsAny(); mockSender.Setup(s => s.Send(sendMatch)).Returns(expected); //passes mockSender.Setup(s => s.Send(SendMatchFromMethod())).Returns(expected); //fails var sendMatch = SendMatchFromMethod(); mockSender.Setup(s => s.Send(sendMatch)).Returns(expected); //fails […]

如何使用Moq测试ServiceStack服务

我有一个使用ServiceStack创建的rest服务,使用nHibernate作为从SqlCe数据库获取数据的方法。 我一直在尝试使用nUnit和Moq编写一些unit testing – 我已经成功地模拟了nHibernate实现以返回null,无效对象等等 – 但我的测试总是在调用基类来设置HttpStatus等时抛出NullReferenceException 。 public List Get (ParameterAll parameterAll) { List parameterResponseList = new List (); try { List parameterDomainObjectList = _ParameterDao.getAllParameters (); foreach (ParameterDomainObject parameterDomainObject in parameterDomainObjectList) { parameterResponseList.Add (parameterDomainObject.ToDto ()); } } catch (WebServiceException webEx) { Debug.WriteLine (“WebServiceException.ErrorCode ” + webEx.ErrorCode); Debug.WriteLine (“WebServiceException.ErrorMessage ” + webEx.ErrorMessage); Debug.WriteLine (“WebServiceException.ResponseStatus ” […]

Moq – 如何模拟Web服务调用?

下面的using命中了我不想实际命中的外部资源。 我想测试someResult和使用它的代码,但每次运行我的unit testing时,这段代码仍然试图点击真正的Web服务。 我如何使用moq来伪造对Web服务的真实调用,但不使用模拟其他代码? public IMyInterface.SomeMethod() { // hits a web service using ( mySoapClient client = new mySoapClient() ) { var someResult = client.DoSomething(); … … } } [TestMethod()] public void SomeMethodTest() { IMyInterface target = new MyInterface(); target.SomeMethod(); // Assert…. }

Moq是派生类的基类函数

我是Moq的新手,我刚观看了莫青的复数video,所以我觉得有权去写一些测试。 我有一个基类让我们说Sheet实现了一个接口ISheet。 Sheet是页面的基类: abstract class Sheet: ISheet { public virtual void CreateSheet() // Defined in ISheet { } public virtual void BuildSheet() // Defined in ISheet { } //and some abstract methods, etc. } public class Page : Sheet { public override void CreateSheet() { BuildSheet(); // Base class implementation } } 我从基类CreateSheet()覆盖了其中一个方法,但我想测试从派生类调用基类中的BuildSheet()方法: 所以在我的测试类中,我将SQ替换为接口而不是接口 var […]

我如何模拟HttpResponseBase.End()?

我正在使用Moq来创建HttpResponseBase的模拟对象。 我需要能够测试在我的库中调用HttpResponseBase.End()。 为此,我在调用之前指定了一些文本,之后指定了一些文本。 然后我检查在HttpResponseBase.Output中是否只有调用End()之前的文本。 问题是,我无法弄清楚如何模拟HttpResponseBase.End()以便它停止处理,就像在ASP.NET中一样。 public static HttpResponseBase CreateHttpResponseBase() { var mock = new Mock(); StringWriter output = new StringWriter(); mock.SetupProperty(x => x.StatusCode); mock.SetupGet(x => x.Output).Returns(output); mock.Setup(x => x.End()) /* what do I put here? */; mock.Setup(x => x.Write(It.IsAny())) .Callback(s => output.Write(s)); return mock.Object; }