使用Rhino Mocks如何在传递给模拟对象的参数中检查Struct Field的值?

时间:2011-07-29 11:30:22

标签: c# unit-testing rhino-mocks

在Rhino Mocks中,我正在测试Subject类中的一个名为Store的方法。 Subject.Store(Member)内部调用IStore.Store(Person)。如何检查我在Member上设置的name参数是否与调用IStore.Store(Person)中Person参数中的名称相同。

显然,在结构中实现Equals方法然后调用Arg.Is.Equals将是一个选项。但我无法控制Person或Member结构的源代码。

以下是代码段..

struct Person {
        string name;
        int age;
        char sex;
    }

    struct Member {
        string name;
        string address;
        string departnemt;

        public Member(string name, string address, string departnemt) {
            // TODO: Complete member initialization
            this.name = name;
            this.address = address;
            this.departnemt = departnemt;
        }
        //other methods
    }

    interface IStore {
        void Store(Person p);
        //other methods
    }

    class Subject {
        IStore db;
        public void Store(Member m) {
            //some logic to convert Member to Person
            Person p = GetPersonFromMember(m);
            db.Store(p);
        }

        //other methods
    }

[Test]
        public void TestStore() {
            //Arrange
            Member m = new Member("dave", "crawford Ave", "Physics");

            var mockStore = MockRepository.GenerateMock<IStore>();
            mockStore.Expect(x => x.Store(Arg<Person>.Is.NotNull));
            //here i also want to check that the Person.Name is "dave"
            //how can i do this?

            //Act
            subject.Commit();

            //Assert
            mockStore.VerifyAllExpectation();
        }

1 个答案:

答案 0 :(得分:6)

除了执行Arg<Person>.Is.NotNull之外,您可以执行Arg<Person>.Property.Value("Name", m.Name)

另外假设您正在使用.Net 3.5或更高版本,您可以做一些您可能认为或不认为更好的内容并避免使用属性名称的字符串: Arg<Person>.Matches(p => p != null && p.Name == m.Name)