Unit testing 如何嘲笑这个概念
我想用这种方式模拟方法MyValueUnit testing 如何嘲笑这个概念,unit-testing,c#-4.0,moq,Unit Testing,C# 4.0,Moq,我想用这种方式模拟方法MyValue class Test : ITest { public string MyValue { get; } public string Detail {get; set;} } testmytest=newtest(){Detail=“myTest”}; mockrepositorytest=新的MockRepository(MockBehavior.Default); Mock mockTest=repositoryTest.Create(myT
class Test : ITest
{
public string MyValue { get; }
public string Detail {get; set;}
}
testmytest=newtest(){Detail=“myTest”};
mockrepositorytest=新的MockRepository(MockBehavior.Default);
Mock mockTest=repositoryTest.Create(myTest);
Setup(t=>t.MyValue).返回(“一些文本”);
返回myTest;
注意:这个代码不起作用,只是为了理解我想要的
另一种方式是如何模拟现有对象的实例?我使用Google Moq。您可能应该在接口上进行模拟,而不是在实现类上 使用
Mock.Get(T)
从您的T
获取Mock
:
Test myTest = new Test() { Detail = "My Test" };
MockRepository repositoryTest = new MockRepository(MockBehavior.Default);
Mock<Test> mockTest = repositoryTest.Create(myTest);
mockTest.Setup(t => t.MyValue).Returns("Some text");
return myTest;
ITest test=newmock().Object;
Mock mockTest=Mock.Get(测试);
编辑:您可以使用
Moq.stub
名称空间删除属性。查看此页面:问题出在哪里?如果您调用myTest.Object.MyValue
您将得到一些文本
,我认为(从我的头顶上看)可以,但是如何像测试对象的实例一样使用Mock().Object。例如,如果我想设置细节值?@Francis:你是在调用属性设置器(即,特别是说myTestObject.Detail=someValue
),还是仅仅在测试的代码中调用getter?如果您只是在测试代码中访问属性,只需在单元测试中使用mockTest.SetupGet(mock=>mock.Detail)。返回(someValue)
。我只想模拟属性MyValue,属性Detail必须返回的属性MyValue是自己的值;我用一个链接更新了我的答案,该链接指向Moq.Stub
。这可能会对您有所帮助。我想创建一个测试对象集合,并为每个测试对象模拟MyValue属性。我想做的是,我的类是一个域类,具有语言本地化机制。我想要的是创建一个我的域类集合,绕过本地化机制。
ITest test = new Mock<ITest>().Object;
Mock<ITest> mockTest = Mock<ITest>.Get(test);