Note that there are some explanatory texts on larger screens.

plurals
  1. POC# + Mock service layer?
    primarykey
    data
    text
    <p>I have just started playing with unit testing / mocks using Moq, and ran into a problem..</p> <p>I have a Service layer named "CustomerService" which have following code:</p> <pre><code>public interface ICustomerService { Customer GetCustomerById(int id); } public class CustomerService : ICustomerService { private IRepository&lt;Customer&gt; customerRepository; public CustomerService(IRepository&lt;Customer&gt; rep) { customerRepository = rep; } public Customer GetCustomerById(int id) { var customer = customerRepository.Get(x =&gt; x.CustomerId == id); if (customer == null) return null; return customer; } } </code></pre> <p>My repository class is generic, and are following:</p> <pre><code>public interface IRepository&lt;T&gt; : IDisposable where T : class { T Get(Expression&lt;Func&lt;T, bool&gt;&gt; predicate); } public class Repository&lt;T&gt; : IRepository&lt;T&gt; where T : class { private ObjectContext context; private IObjectSet&lt;T&gt; objectSet; public Repository() : this(new demonEntities()) { } public Repository(ObjectContext ctx) { context = ctx; objectSet = context.CreateObjectSet&lt;T&gt;(); } public T Get(Expression&lt;Func&lt;T, bool&gt;&gt; predicate) { T entity = objectSet.Where&lt;T&gt;(predicate).FirstOrDefault(); if (entity == null) return null; return objectSet.Where&lt;T&gt;(predicate).FirstOrDefault(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { if (context != null) { context.Dispose(); context = null; } } } } </code></pre> <p>Now is my question.. How can I make unit test to check whether my GetCustomerById returns null or not?</p> <p>Already tried:</p> <pre><code>[TestMethod] public void GetCustomerTest() { const int customerId = 5; var mock = new Mock&lt;IRepository&lt;Customer&gt;&gt;(); mock.Setup(x =&gt; x.Get(z =&gt; z.CustomerId == customerId)) .Returns(new Customer()); var repository = mock.Object; var service = new CustomerService(repository); var result = service.GetCustomerById(customerId); Assert.IsNotNull(result); } </code></pre> <p>without luck...</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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