I have the following classes
namespace Foo.Bar.Services
{
public abstract class Service
{
public Service(IUnitOfWork unitOfWork)
{
this.UnitOfWork = unitOfWork;
}
protected IUnitOfWork UnitOfWork { get; private set; }
}
}
using...
namespace Foo.Bar.Services
{
public class ControlService : Service
{
...
private readonly IRepository<GroupStructure> groupStructures = null;
public ControlService(IUnitOfWork uow) : base(uow)
{
...
this.agencyGroupStructures = this.UnitOfWork.GetRepository<AgencyGroupStructure>();
}
public Tuple<bool, int> HasExternalImage(int branchId)
{
var externalResultList = from a in this.Structures.Table
where a.GroupID == branch.GroupID
&& (a.AreExternalRequired == true)
&& (a.ProductTypeID == ETourType.Trailer)
&& !a.Deleted
select a;
return (some logic based on above...)
}
}
and test
namespace ControlTests
{
[TestFixture]
public class Control
{
//unable to create service due to being abstact
[Test]
public void TestMethod1()
{
******Changed here******
var Mock = new Mock<GroupStructureService> { CallBase = true };
var fakeControl = new ControlService(Mock.Object)
var sut = fakeControl.HasExternalImage(1249);
Assert.That(sut.Item1, "true");
}
}
}
Running the above with NUnit and Moq gives the following message:
Castle.DynamicProxy.InvalidProxyConstructorArgumentsException : Can
not instantiate proxy of class: Foo.Bar.Services.ControlService.
Could not find a parameterless constructor.
I've tried a few things but I can't get this previously untested app to create a mock object to test
Edit, thanks. So I've changed it to use the ControlService and mock 1
dependancy. But its error is that it cant convert from
....GroupStructure to Foo.Bar.IUnitOfWork
Normally, the system under test is not mocked. Mock its dependencies and inject that into an instance of the class under test
[TestFixture]
public class Control {
[Test]
public void TestMethod1() {
//Arrange
var repository = new Mock<IRepository<GroupStructure>>();
//...Set up the repository behavior to satisfy logic
var uow = new Mock<IUnitOfWork>();
uow.Setup(_ => _.GetRepository<AgencyGroupStructure>())
.Returns(repository.Object);
var sut = new ControlService(uow.Object);
var expected = true;
//Act
var actual = sut.HasExternalImage(1249);
//Assert
Assert.AreEqual(actual.Item1, expected);
}
}
Reference Moq Quickstart to get a better understanding of how to use the mocking framework.
Related
I am creating Unit Tests for existing .NET Framework 4.5 API project. The existing project has parameterless constructor by design and dependency injection was implemented as per the class below using Ninject.
I would like to Mock the interface and create an instance of the class for testing as shown below but the constructor is parameterless. I can't figure out how to inject my Mock member.Object. The main goal is I don't want to change the design of existing classes unless there is no other way.
public class MemberController : ApiController
{
StandardKernel DependencyKernel;
private IMember member;
public MemberController()
{
DependencyKernel = new StandardKernel();
DependencyKernel.Load(Assembly.GetExecutingAssembly());
member = DependencyKernel.Get<IMember>();
}
[HttpPost]
public HttpResponseMessage AddMember(MemberRequest model)
{
try
{
int memberRecords;
member.SaveMember(model, out memberRecords);
if (memberRecords > 0)
return new HttpResponseMessage { StatusCode = HttpStatusCode.Conflict, Content = new StringContent("Member with same reference exists") };
else
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent("Member added successfully") };
}
catch (Exception ex)
{
return new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(ex.Message) };
}
}
}
//Test Class
public class MemberControllerTests
{
StandardKernel DependencyKernel;
private MemberController memberController;
Mock<IMember> member = new Mock<IMember>();
public MemberControllerTests()
{
DependencyKernel = new StandardKernel();
DependencyKernel.Load(Assembly.GetExecutingAssembly());
}
[SetUp]
public void Setup()
{
}
[Test]
public void should_AddMember()
{
//Arrange
MemberRequest member = new MemberRequest{ };
int memberRecords;
member.Setup(x => x.SaveMember(member, out memberRecords));
memberController = new MemberController(member.Object); //This will obviously not work, the MemberController has parameterless constructor
//Act
var result = MemberController.AddMember(member);
//Assert
Assert.AreEqual(result.StatusCode, HttpStatusCode.OK);
}
}
This post has the answer to the question. If IMember member property is made public in MemberController, I can new up the MemberController class and set the value of its member property to the MOCK.
I am needing to set up a Unit Test for our project. In our Controllers we are using a Unit of Work which holds all the repositories and calling the repository in our IHttpActionResult to get the data.
So far I have set up a Mock of the Interfaces and this is calling the correct IHttpActionResult in the Controller but there is no data coming back.
[TestMethod]
public void TestMethod1()
{
var unitOfWork = new Mock<IUnitOfWork>();
var repo = new Mock<IAuditReleaseRepository>();
unitOfWork.Setup(e => e.AuditReleaseRepository).Returns(repo.Object);
var auditReleaseController = new AuditReleaseController(unitOfWork.Object);
var result = auditReleaseController.Get() as ViewResult;
var model = result.ViewData.Model as IQueryable<AuditReleas>;
Assert.AreEqual(12, model.Count());
}
public class AuditReleaseController : BaseController
{
private IAuditReleaseRepository _auditReleaseRepository;
private IUnitOfWork _unitOfWork;
public AuditReleaseController(IUnitOfWork unitOfWork)
{
this._unitOfWork = unitOfWork;
this._auditReleaseRepository = unitOfWork.AuditReleaseRepository;
}
[HttpGet, Route("audit-releases")]
public IHttpActionResult Get()
{
var query = this._auditReleaseRepository.GetAll();
return Ok(query);
}
}
public class AuditReleaseRepository : RepositoryBase<AuditReleas>, IAuditReleaseRepository
{
private readonly RetailAssignmentEntities _entities;
public AuditReleaseRepository(RetailAssignmentEntities entities) : base(entities)
{
this._entities = entities;
}
IEnumerable<AuditReleaseDto> IDtoRepository<AuditReleaseDto>.GetAll()
{
return base.GetAll().Where(x=>x.IsReleaseEnabled).Select(AuditReleaseMapping.All).OrderByDescending(x => x.Id);
}
}
This is the Mapping that is taking place to get the data in the GetAll method:
public class AuditReleaseMapping
{
public static Expression<Func<AuditReleas, AuditReleaseDto>> All = (auditRelease) => new AuditReleaseDto()
{
EndDate = auditRelease.AuditReleaseEndDate,
Id = auditRelease.AuditReleaseId,
Name = auditRelease.AuditReleaseName,
StartDate = auditRelease.AuditReleaseStartDate,
AuditPeriodId = auditRelease.AuditPeriod.AuditPeriodId,
AuditYearId = auditRelease.AuditPeriod.AuditYear.AuditYearId,
AuditEndDate = auditRelease.AuditPeriod.AuditEndDate,
AuditStartDate = auditRelease.AuditPeriod.AuditStartDate
};
}
What would be ideal is to call the Controller, which would call the repository, which would then call the Mapping but so far it's not even calling the Repository to get the data. I need help getting that functionality set up.
It looks like you need to Setup the behavior for your Mock repo.GetAll(). You will need to create a list of AuditReleaseDto's for your Mocked repo to return. Call it TestAuditReleaseDtos. You can create this TestData in the beginning of your TestMethod or in the TesstClass initialization. Then use it in a line right after creating your Mock:
var repo = new Mock<IAuditReleaseRepository>();
repo.Setup(r => r.GetAll()).Returns(TestAuditReleaseDtos);
unitOfWork.Setup(e => e.AuditReleaseRepository).Returns(repo.Object);
I'm trying to test my project. I have never used tests before and I am starting to learn I would like a help, in the simplest case I want test this public ActionResult Index() but I don't know how to Inject those dependencies.
Controller:
Controller:
public class WorkPlacesController : Controller
{
private readonly IWorkPlaceService workPlaceService;
public WorkPlacesController(IWorkPlaceService workPlaceService)
{
this.workPlaceService = workPlaceService;
}
// GET: WorkPlaces
public ActionResult Index()
{
var workPlaces = workPlaceService.GetWorkPlaces(includedRelated:
true);
return View(workPlaces);
}
}
Here is my Service
Service
public class WorkPlaceService : IWorkPlaceService
{
private readonly IWorkPlaceRepository workPlacesRepository;
private readonly IUnitOfWork unitOfWork;
public WorkPlaceService(IWorkPlaceRepository workPlacesRepository, IUnitOfWork unitOfWork)
{
this.workPlacesRepository = workPlacesRepository;
this.unitOfWork = unitOfWork;
}
}
public interface IWorkPlaceService
{
IEnumerable<WorkPlace> GetWorkPlaces(string workPlaceDescription = null, bool includedRelated = true);
}
And my Repository
Repository
public class WorkPlaceRepository : RepositoryBase<WorkPlace>, IWorkPlaceRepository
{
public WorkPlaceRepository(IDbFactory dbFactory)
: base(dbFactory) { }
public WorkPlace GetWorkPlaceByDescription(string workPlaceDescription)
{
var workPlace = this.DbContext.WorkPlaces.Where(c => c.Description == workPlaceDescription).FirstOrDefault();
return workPlace;
}
}
public interface IWorkPlaceRepository : IRepository<WorkPlace>
{
WorkPlace GetWorkPlaceByDescription(string workPlaceDescription);
}
Factory
public class DbFactory : Disposable, IDbFactory
{
AgendaEntities dbContext;
public AgendaEntities Init()
{
return dbContext ?? (dbContext = new AgendaEntities());
}
protected override void DisposeCore()
{
if (dbContext != null)
dbContext.Dispose();
}
}
I tried to do something like this:
public void BasicIndexTest()
{
// Arrange
var mockRepository = new Mock<IWorkPlaceService>();
var controller = new WorkPlacesController(mockRepository.Object);
// Act
ActionResult actionResult = controller.Index() as ViewResult;
// Assert
Assert.IsInstanceOfType(actionResult, typeof(List<WorkPlace>));
}
How do I inject in this controller the data needed to go in the database and bring the results?
I Want test this public ActionResult Index() but I don't know how to Inject those dependencies.
Mock the behavior of required dependencies of the controller for the test and assert the desired behavior when the test is exercised.
For example, based on what you have done so far
public void BasicIndexTest() {
// Arrange
var mockService = new Mock<IWorkPlaceService>();
var workPlaces = new List<WorkPlace>() {
new WorkPlace()
};
mockService
.Setup(_ => _.GetWorkPlaces(It.IsAny<string>(), It.IsAny<bool>()))
.Returns(workPlaces);
var controller = new WorkPlacesController(mockService.Object);
// Act
var actionResult = controller.Index() as ViewResult;
// Assert
Assert.IsNotNull(actionResult);
var model = actionResult.Model;
Assert.IsNotNull(model)
Assert.IsInstanceOfType(model, typeof(List<WorkPlace>));
Assert.AreEqual(workPlaces, model);
}
Only the IWorkPlaceService was needed for the testing of Index action, but fake data was needed for the invocation of the GetWorkPlaces method. So the mock was configured to return a list of objects when called and pass it to the view result.
I have implemented generic repository in my project. Now I am writing test cases for my consumer. I am trying to mock database function through Moq but I am getting values from database rather than the one I faked through Moq. Below I am sharing my implementation. Hoping someone will help me in pointing out the mistake I made.
My interface:
public interface IEventsRepository<T> : IRepository<T> {
T GetEventsByEventId(int eventId); }
My class:
public class EventsTableRepository : EFDBRepository<EventsModel>, IEventsRepository<EventsModel> {
public EventsModel GetEventsByEventId(int eventId)
{
return _dbSet.Where(x => x.EventID == eventId).FirstOrDefault();
}
}
My Consumer:
public static Response<string> EventsAccept(EventsAlertsRequest logMsgId)
{
IEventsRepository<EventsModel> eventsRepo = (IEventsRepository<EventsModel>)RepositoryLocator.GetRepositoryObject(STMEnums.RepositoryName.EventsTableRepository.ToString());
EventsModel eventmodel = new EventsModel();
eventmodel = eventsRepo.GetEventsByEventId(eachlogMsgId);
return EventStatusChangeResponse;
}
Test Method:
public void EventsAcceptSuccessTest()
{
EventsModel eventmodel = new EventsModel();
eventmodel.Message = "TEST";
Mock<IEventsRepository<EventsModel>> obj = new Mock<IEventsRepository<EventsModel>>();
obj.Setup(m => m.GetEventsByEventId(Moq.It.IsAny<int>())).Returns(eventmodel);
EventStatusChangeResponse = Diagnostics_.EventsAccept(logMsgId);
Assert.AreEqual(eventmodel.Status, EventStatus.ACCEPTED);
}
No where in the provided example is the mock being injected into the subject under test. Also it looks like the subject method under test is using static Service Locator anti-pattern to get the desired model. Making an assumption here as the rest of the class is not shown in relation to that variable.
The locator would need to have been an injected abstraction to allow an opportunity to mock its expected behavior
public class Consumer {
private IRepositoryLocator RepositoryLocator;
public Consumer(IRepositoryLocator RepositoryLocator) {
this.RepositoryLocator = RepositoryLocator;
}
public Response<string> EventsAccept(EventsAlertsRequest logMsgId) {
IEventsRepository<EventsModel> eventsRepo = (IEventsRepository<EventsModel>)RepositoryLocator.GetRepositoryObject(STMEnums.RepositoryName.EventsTableRepository.ToString());
EventsModel eventmodel = new EventsModel();
eventmodel = eventsRepo.GetEventsByEventId(eachlogMsgId);
return EventStatusChangeResponse;
}
}
This would then mean that the locator would also have to be mocked properly for the test to be exercised to completion.
public void EventsAcceptSuccessTest() {
//Arrange
var eventmodel = new EventsModel() {
Message = "TEST"
};
var repositoryMock = new Mock<IEventsRepository<EventsModel>>();
repositoryMock
.Setup(_ => _.GetEventsByEventId(It.IsAny<int>()))
.Callback((int id) => {
eventmodel.EventID = id;
eventmodel.Status = EventStatus.ACCEPTED;
})
.Returns(eventmodel);
var locatorMock = new Mock<IRepositoryLocator>();
locatorMock.Setup(_ => _.GetRepositoryObject(It.IsAny<string>())).Returns(repositoryMock.Object);
var subject = new Consumer(locatorMock.Object);
//Act
var response = subject.EventsAccept(logMsgId);
//Assert
Assert.AreEqual(eventmodel.Status, EventStatus.ACCEPTED);
}
In a few words. Wpf app, ef used. I need to test model behavior using mock and unity. Unity and mock seem to me to be clear.
The question is following:
Model doesn't get the context through it constructor. It uses the context while execute the methods like this:
public Toys[] Get()
{
using (Context context = new Context())
{
return context.Toys.ToArray();
}
}
This is how I try to test:
[TestClass]
public class TestToyModel
{
[TestMethod]
public void TestToyCreate()
{
List<Toy> toys = new List<Toy>();
toys.Add(new Toy{ Id = "1234", Name = "Toy1" });
DbSet<Toy> dbToys = GetQueryableMockDbSet(toys);
Mock<ToyModel> model = new Mock<ToyModel>();
Mock<Context> context = new Mock<Context>();
context.Setup(x => x.Toys).Returns(dbToys);
//it' s all for now
}
private static DbSet<T> GetQueryableMockDbSet<T>(List<T> sourceList) where T : class
{
var queryable = sourceList.AsQueryable();
var dbSet = new Mock<DbSet<T>>();
dbSet.As<IQueryable<T>>().Setup(m => m.Provider).Returns(queryable.Provider);
dbSet.As<IQueryable<T>>().Setup(m => m.Expression).Returns(queryable.Expression);
dbSet.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(queryable.ElementType);
dbSet.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(() => queryable.GetEnumerator());
dbSet.Setup(d => d.Add(It.IsAny<T>())).Callback<T>((s) => sourceList.Add(s));
return dbSet.Object;
}
}
How can I supply my mock model with mock context ?
The context is being created manually so the class is tightly coupled to context which makes it difficult to unit test in isolation.
context is a dependency. abstract it out so that it can be mocked and injected into the subject under test.
public interface IContext : IDisposable {
public DbSet<Toy> Toys { get; }
//...other properties and methods
}
public class Context : DbContext, IContext {
public Context() { ... }
public DbSet<Toy> Toys { get; set; }
//...other properties and methods
}
Assuming system under test
public class ToyModel {
private readonly IContext context;
public MyClass(IContext context) {
this.context = context;
}
public Toys[] Get() {
return context.Toys.ToArray();
}
public void Create(Toy toy) {
context.Toys.Add(toy);
context.SaveChanges();
}
}
The class is no longer responsible for creating the dependency. That responsibility is now passed/delegated out to another class. Also note that your classes should depend on abstractions and not on concretions. This allows for more flexibility when swapping implementations. Like mocking for unit tests.
Now the context can be mocked and injected into the dependent class. Here is a simple example based on what you have done so far.
[TestClass]
public class TestToyModel {
[TestMethod]
public void TestToyCreate() {
//Arrange
var toys = new List<Toy>();
toys.Add(new Toy { Id = "1234", Name = "Toy1" });
var dbToys = GetQueryableMockDbSet(toys); //DbSet<Toy>
var contextMock = new Mock<IContext>();
contextMock.Setup(x => x.Toys).Returns(dbToys);
var sut = new ToyModel(contextMock.Object);
//Act
sut.Create(new Toy { Id = "5678", Name = "Toy2" });
//Assert
var expected = 2;
var actual = toys.Count;
Assert.AreEqual(expected, actual);
}
//...other code removed for brevity
}
If the ToyModel is the system under test, there is no need to mock it. Create an instance and pass the mocked dependencies to satisfy the test.