chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
Welcome to Typemock Community! Here you can ask and receive answers from other community members. If you liked or disliked an answer or thread: react with an up- or downvote.
0 votes
Take the following snippet:

public void MethodUnderTest()
{
//...

CustomList custList = new CustomList();

custList.Fill(...);  // Reads from Database, want to mock this call, but still want to "fill" the list with canned data

// Loop through custList and do something

}


Is it possible to populate my custList object as a side effect of the mocekd Fill call? Or, do I need to write a custom test double and use DI?
asked by astafford (600 points)

1 Answer

0 votes
Hi
I see two options here:
If the list is used in the code via property or method you can mock it to
always return your fake list.
the example below assumes that you have public property CustomList.GetList
using (RecordExpectations recorder = RecorderManager.StartRecording())
{
   CustomList mock = new CustomList();
   recorder.ExpectAndReturn(mock.GetList, fakeList).RepeatAlways();
}


If you are not using property or method the other option is to mock the field.

Example:
public class CustomList
{
   private List<int> _list = new List<int>();
   public void Fill()
   {     
             // fill the list ...
   }
}

[Test]
public void Test()
{
   Mock mockCustomList = MockManager.Mock<CustomList>();
   List<int> fakeList = new List<int>();
   fakeList.Add(1);
   fakeList.Add(2);
   fakeList.Add(3);
   mockCustomList.AssignField("_list", fakeList);
}


:arrow: I'm using reflective mocks in order the get access to a private field.
Hope it helps. Please tell me if you have more questions.
answered by ohad (35.4k points)
...