I am new to Moq and not quite sure why this will not work.
Repository interface
using System.Collections.Generic;
public interface IRepository
{
IEnumerable<string> list();
}
Service interface
using System.Collections.Generic;
public interface IService
{
IEnumerable<string> AllItems();
}
Class of service
using System.Collections.Generic;
public class Service : IService
{
private IRepository _repository;
public Service(IRepository repository)
{
this._repository = repository;
}
public IEnumerable<string> AllItems()
{
return _repository.list();
}
}
Unit Test Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MoqTest;
using MoqTest.Controllers;
using Moq;
using MoqTest.Models;
[TestClass]
public class Tests
{
private Mock<IRepository> _mockRepository;
private IService _service;
[TestMethod]
public void my_test()
{
List<string> theList = new List<string>();
theList.Add("test3");
theList.Add("test1");
theList.Add("test2");
_mockRepository = new Mock<IRepository>();
_mockRepository.Setup(s => s.list()).Returns(theList);
_service = new Service(_mockRepository.Object);
var myList = _service.AllItems();
Assert.IsNotNull(myList, "myList is null.");
Assert.AreEqual(3, myList.Count());
}
}
I wanted to install this as a very simple unit test. It does not work in a call to _mockRepository.Setup. Any help would be appreciated!
EDIT -
Error message
Test method Tests.my_test threw exception: System.NullReferenceException: Object reference not set to an instance of an object..
Exception stack trace
Moq.MethodCall.SetFileInfo()
Moq.MethodCall..ctor(Mock mock, Expression originalExpression, MethodInfo method, Expression[] arguments)
Moq.MethodCallReturn..ctor(Mock mock, Expression originalExpression, MethodInfo method, Expression[] arguments)
ctor(Mock mock, Expression originalExpression, MethodInfo method, Expression[] arguments)
b__11()
Moq.PexProtector.Invoke[T](Func`1 function)
TResult](Mock mock, Expression`1 expression)
Setup[TResult](Expression`1 expression)
Tests.my_test() in C:\Users\xxx\Documents\Visual Studio 2008\Projects\MoqTest\MoqTest.Tests\Controllers\Tests.cs: line 28
source
share