user2580179
user2580179

Reputation: 259

How to mock a Class with IEnumerable

I am using Moq for unit testing in C# and want to put some fake data in the following class.

 public class UserResponse
 {

       public IEnumerable<usertab> userlist{get;set;}
       public string Name {get;set;}
       public string state {get;set;}
       public string country {get;set}

 }

  public class usertab
  {
    public string tname {get;set;}

    public string fname {get;set;}

   }

Please correct me if below code is correct to fake a class wtih IEnumerable

            var userdata = new usertab[]{

               new usertab{tName="Employee",fName="abc"},
               new usertab{tName="Employee",fName="xyz"},

            };

Upvotes: 0

Views: 326

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503459

Well you're not "faking" it at all - you're just using an array as the implementation. There's nothing wrong with doing that - personally I like using real code within tests, so long as:

  • You have confidence in the other code you're relying on (arrays in this case) either because it's supplied from a trustworthy source (the BCL in this case) or you have tests
  • You don't need to perform interaction testing - for example, if you want to check that you only iterate over the collection once, arrays won't help you do that
  • The real code doesn't slow down the testing (e.g. by making network connections, requiring a database etc). Not a problem with arrays.

Upvotes: 3

Related Questions