刚从Rhino Mocks开始,我遇到一个非常简单的问题,我该如何模拟一个带有设置属性的void的类?

class SomeClass : ISomeClass
{
    private bool _someArg;

    public bool SomeProp { get; set; }

    public SomeClass(bool someArg)
    {
        _someArg = someArg;
    }

    public void SomeMethod()
    {
        //do some file,wcf, db operation here with _someArg
        SomeProp = true/false;
    }
}


显然,这是一个非常人为的示例,谢谢。

最佳答案

在您的示例中,您不需要RhinoMocks,因为您显然正在测试被测类的功能。简单的单元测试将代替:

[Test]
public void SomeTest()
{
    var sc = new SomeClass();
        // Instantiate SomeClass as sc object
    sc.SomeMethod();
        // Call SomeMethod in the sc object.

    Assert.That(sc.SomeProp, Is.True );
        // Assert that the property is true...
        // or change to Is.False if that's what you're after...
}


当您拥有一个依赖于其他类的类时,对模拟进行测试会更加有趣。在您的示例中,您提到:


  //使用_someArg在此处执行一些文件,wcf,db操作


即您希望其他类可以设置SomeClass的属性,这对于模拟更有意义。例:

public class MyClass {

    ISomeClass _sc;

    public MyClass(ISomeClass sc) {
        _sc = sc;
    }

    public MyMethod() {
        sc.SomeProp = true;
    }

}


所需的测试将如下所示:

[Test]
public void MyMethod_ShouldSetSomeClassPropToTrue()
{
    MockRepository mocks = new MockRepository();
    ISomeClass someClass = mocks.StrictMock<ISomeClass>();

    MyClass classUnderTest = new MyClass(someClass);

    someClass.SomeProp = true;
    LastCall.IgnoreArguments();
        // Expect the property be set with true.

    mocks.ReplayAll();

    classUndertest.MyMethod();
        // Run the method under test.

    mocks.VerifyAll();
}

关于c# - 犀牛Mo,空隙和性质,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/467579/

10-09 13:31