最小起订量:指定返回值作为期望的一部分 [英] Moq: Specifying return values as part of expectations
本文介绍了最小起订量:指定返回值作为期望的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Moq和学习的新手.
I'm new to Moq and learning.
我需要测试方法是否返回预期的值.我整理了一个点头的例子来解释我的问题. 此操作失败的原因是:
I need to test that a method returns the value expected. I have put together a noddy example to explain my problem. This fails miserably with:
"ArgumentException:表达式不是方法调用:c =>(c.DoSomething("Jo","Blog",1)="OK")"
"ArgumentException: Expression is not a method invocation: c => (c.DoSomething("Jo", "Blog", 1) = "OK")"
您能纠正我做错了吗?
[TestFixtureAttribute, CategoryAttribute("Customer")]
public class Can_test_a_customer
{
[TestAttribute]
public void Can_do_something()
{
var customerMock = new Mock<ICustomer>();
customerMock.Setup(c => c.DoSomething("Jo", "Blog", 1)).Returns("OK");
customerMock.Verify(c => c.DoSomething("Jo", "Blog", 1)=="OK");
}
}
public interface ICustomer
{
string DoSomething(string name, string surname, int age);
}
public class Customer : ICustomer
{
public string DoSomething(string name, string surname, int age)
{
return "OK";
}
}
简而言之:如果我想测试上述方法,并且知道要返回"OK",我将如何使用Moq编写它?
In a nutshell: if I wanted to test a method like the one above, and I know that I am expecting back an "OK", how would I write it using Moq?
谢谢您的建议.
推荐答案
- 您需要一个与模拟对象进行交互的测试主题(除非您正在为Moq编写学习者测试.)我在下面写了一个简单的主题
- 您在模拟对象上设置期望值,指定确切的参数(严格-如果您愿意,则使用
Is.Any<string>
接受任何字符串),并指定返回值(如果有) - 您的测试对象(作为测试的行为"步骤的一部分)将调用您的模拟游戏
- 您断言测试对象的行为符合要求.模拟方法的返回值将由测试对象使用-通过测试对象的公共接口对其进行验证.
- 您还验证是否满足您指定的所有期望-实际上已经调用了您希望被调用的所有方法.
- You need a test subject that interacts with mock objects (unless you're writing a learner test for Moq.) I wrote up a simple one below
- You setup expectations on the mock object, specifying the exact arguments (strict - if you wish to ofcourse, else use
Is.Any<string>
to accept any string) and specify return values if any - Your test subject (as part of the Act step of the test) will call onto your mock
- You assert the test subject behaved as required. The return value from the mock methods will be used by the test subject - verify it via the test subject's public interface.
- You also verify that all expectations that you specified were met - all methods that you expected to be called were in fact called.
.
[TestFixture]
public class Can_test_a_customer
{
[Test]
public void Can_do_something()
{
//arrange
var customerMock = new Moq.Mock<ICustomer>();
customerMock.Setup(c => c.DoSomething( Moq.It.Is<string>(name => name == "Jo"),
Moq.It.Is<string>(surname => surname == "Blog"),
Moq.It.Is<int>(age => age == 1)))
.Returns("OK");
//act
var result = TestSubject.QueryCustomer(customerMock.Object);
//assert
Assert.AreEqual("OK", result, "Should have got an 'OK' from the customer");
customerMock.VerifyAll();
}
}
class TestSubject
{
public static string QueryCustomer(ICustomer customer)
{
return customer.DoSomething("Jo", "Blog", 1);
}
}
这篇关于最小起订量:指定返回值作为期望的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文