Note that there are some explanatory texts on larger screens.

plurals
  1. POTesting a service using mock repository objects
    text
    copied!<p>I am testing a service within a framework. </p> <p>In order to initialize the service, I am using mock repository objects.</p> <p><strong>ServiceTest.cs</strong></p> <pre><code>private IRepository _repository; private IService _service; private List&lt;Object&gt; _objects; [TestInitialize] public void Initialize() { _repository = new Mock&lt;IRepository&gt;().Object; _service = new Service(repository); _objects = new List&lt;Object&gt;() { new Object { Name = "random", ID = 1 }, new Object { Name = "not so random", ID = 1}, new Object { Name = "random", ID = 2 }, new Object { Name = "not so random", ID = 2} }; //attempt at mocking the repository _repository.Setup(r =&gt; r.GetObjects(It.IsAny&lt;string&gt;(), It.IsAny&lt;int&gt;())).Returns(_objects.Where(o =&gt; o.Name == _objects.Name &amp;&amp; o.ID == _objects.ID).ToList()); } [TestMethod] public void GetObjects_ReturnObjectsList() { //Arrange var name = "random"; //Act var objects = _service.RetrieveObjects(name, 2); //Assert Assert.AreEqual(name, objects.Single().Name); } </code></pre> <p>However, when I test the service, I get <code>ArgumentNullExceptions</code>. The variables set to the repository method calls return <code>null</code>, and eventually throws an error when business logic is run.</p> <p><strong>Service.cs</strong></p> <pre><code> public List&lt;Objects&gt; RetrieveObjects(string name, int id) { var getObjects = repository.GetObjects(name, id); //getObjects return null DoLogic(getObjects); //ArgumentNullException is thrown here return getObjects; } </code></pre> <p>I have looked up information on mocking repositories, but seems like I will have a lot to setup just to test. I am wondering if the setup is worth it.</p> <p>Why am I getting <code>ArgumentNullExceptions</code>? Is there a way to test methods that call repositories?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload