如何使用 Rhino Mocks 和 MSpec 测试抽象类上的虚拟属性?
我在抽象类 Foo
上有一个虚拟属性 FirstName
。我需要测试虚拟财产的行为。当执行此测试时,该方法永远不会触发(因此测试总是失败,无论方法体内有什么)。我怎样才能使这个方法成为我的被测系统?我该如何测试这个方法?
[Subject(typeof(Foo))]
public class When_whatever
{
Establish context = () =>
{
_fooSut = _mockRepository.PartialMock<Foo>(argumentOne, argumentTwo);
};
Because of = () => _result = _fooSut.FirstName;
It should_return_not_null = () => _result.ShouldNotBeNull();
private static string _result;
private static Foo _fooSut;
}
我正在使用 Rhino Mocks 3.5 和 mspec。
I have a virtual property, FirstName
, on an abstract class, Foo
. I need to test the virtual property's behavior. The method never fires when this test executes (and so the test always fails, no matter what's in the method's body). How can I make this method my system under test? How can I test this method?
[Subject(typeof(Foo))]
public class When_whatever
{
Establish context = () =>
{
_fooSut = _mockRepository.PartialMock<Foo>(argumentOne, argumentTwo);
};
Because of = () => _result = _fooSut.FirstName;
It should_return_not_null = () => _result.ShouldNotBeNull();
private static string _result;
private static Foo _fooSut;
}
I'm using Rhino Mocks 3.5 and mspec.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您尝试过
PartialMock
功能吗? 参见此处Are you tried
PartialMock
feature? See here我认为你应该在使用模拟之前执行
_mockRepository.ReplayAll()
。但在这种情况下,它应该被执行。顺便说一句,你想测试什么行为?
我不认为拥有抽象的公共财产是一个好的设计。您也可以发布您的
Foo
类吗?I think you should do
_mockRepository.ReplayAll()
before using mock. But in this case it should be just executed.BTW what behavior do you want to test?
I don't think that having abstract public property is a good design. Could you post your
Foo
class as well?如何构建部分模拟
您正在创建一个部分模拟,一个实现抽象类并为类的虚拟和抽象部分提供模拟功能的模拟。
您正在调用您所说的虚拟属性,
FirstName
。但是,您没有存根虚拟调用,因此它返回默认值!在本例中,为
null
。您需要将此调用添加到您的上下文中。如何测试行为
兰斯,我要鹦鹉学舌the_joric 的问题...您要测试的行为是什么?您上面编写的测试只是测试您是否可以设置模拟。
我只能开始猜测你是如何实现这个抽象的具体类的。那么,也许您想要做的是测试每个实现是否都为此属性提供非空值?在这种情况下,您需要使用行为。
并且
Foo
的每个实现都可以针对这些行为进行测试。How to Build a Partial Mock
You're creating a partial mock, a mock that implements the abstract class and provides mock capabilities for virtual and abstract parts of the class.
And you're calling the property that you said was virtual,
FirstName
.But, you're not stubbing the virtual call, so it's returning the default value! In this case,
null
. You would need to add this call to your context.How to Test Behavior
Lance, I'm going to parrot the_joric's question... what is the behavior you're trying to test? The test you are writing above is only testing that you can setup a mock.
I can only begin to guess how you're implementing concrete classes for this abstract. So, maybe what you want to do is test that every implementation provides a non-null value for this property? In which case, you would want to use a behavior.
And each implementation of
Foo
can be tested against those behaviors.