-1

I am using Visual Studio 2013 and MsTest for unit test and Rhino Mocks for mocking an object.

Is there any way, we can mock other class object

public class Organization 
{
    public DataSet GetUsers()
    {
       DataSet ds = new DataSet();

// Added some columns and rows here
// This class is interacting with the database. That's why I want to create 
// mock of this class.

       return ds;
    }
}

My Main class is as below

public class Users 
{
    public DataSet GetUsers(Organization org)
    {
        DataSet ds = org.GetUsers();

        return ds;
    }
}

My Test method is as below

[TestMethod]
public void GetUsersTest()
{
     DataSet ds = new DataSet();
     //added some mock rows and columns to this dataset

     var objOrg = MockRepository.GenerateMock<Organization>();
     objOrg.Expect(x => x.GetUsers()).Return(ds);

     Users obj = new Users();
     DataSet dsResult = obj.GetUsers(objOrg);
}

It is giving me error. Can anyone help me to write unit test for above class's GetUsers method please?

Old Fox
  • 8,629
  • 4
  • 34
  • 52
Dream
  • 11
  • 1
  • 1
  • 3

1 Answers1

0

Your method is not a virtual method. When you mock a class using RhinoMocks, each method you want to override must be a virtual method.

Change your method to:

public virtual DataSet GetUsers()
{
     DataSet ds = new DataSet();

        // Added some columns and rows here
        // This class is interacting with the database. That's why I want to create 
        // mock of this class.

     return ds;
}
Old Fox
  • 8,629
  • 4
  • 34
  • 52
  • Hello Old Fox, Is there any other way I can mock Organization class's GetUsers method? – Dream Aug 19 '15 at 13:58
  • @Dream not using a proxy tools such as `RhinoMocks` or `Moq`. You need a special tools like [TypeMock Isolator](http://www.typemock.com/isolator-product-page), [MsFakes](https://msdn.microsoft.com/en-us/library/hh549175.aspx) and etc... – Old Fox Aug 19 '15 at 14:12
  • If you have any link, can you provide it to me please? – Dream Aug 19 '15 at 15:01
  • @Dream my previous comment has the links – Old Fox Aug 19 '15 at 15:09
  • @Dream What is the problem with making the method `virtual`? – Old Fox Aug 24 '15 at 22:47
  • If we had implemented that class on some other class then will it impact it? I want to know the impact of virtual keyword in different scenario. If you can show us scenario where if we implement method as virtual, then it will not impact the other code, it will be great. Thanks for your reply OldFox – Dream Aug 28 '15 at 13:36
  • @Dream I don't understand you... From which "impact" do you afraid from? The time performance of `virtual table` is negligible... And the security is not an issue... (In the last 7 years I worked in the security companies... If someone has an access to your computer he can do whatever he wants...) – Old Fox Aug 28 '15 at 23:19