Web Api Repository/ValueController problem - c#

I develop web application. I started from Web Api with Entity Framework. I want realize CRUD function.
Read function works fine
But problem with Create, Update, Delete, could you check it and tell me, what I do wrong?
I attach 2 blocks of code, I don't know how I can realize 1st repository (Mistake in C,U,D - function) in controller.
I don't have enough experience with web api, could you tell me, how I need setting Repository(only for realize create, delete, update) file and after realize it in Value Controller
I need your advice about create, update, delete - function
Customer Repos
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace WebAPI
{
public class CustomerRepository
{
public IQueryable<Customer> GetAllCustomers()
{
DevelopersEntities dev = new DevelopersEntities();
return dev.Customers;
}
public IQueryable<Customer> GetAllCustomers(int id)
{
DevelopersEntities dev = new DevelopersEntities();
return dev.Customers.Where(c=>c.Id==id).Select(e=>e);
}
public IQueryable<Customer> DeleteCustomer(int id)
{
DevelopersEntities dev = new DevelopersEntities();
var cus = dev.Customers.Where(s => s.Id == id).FirstOrDefault();
dev.Entry(cus).State = System.Data.Entity.EntityState.Deleted;
dev.SaveChanges();
return cus;
}
}
public IQueryable<Customer> CreateCustomer(Customer customer)
{
DevelopersEntities dev = new DevelopersEntities();
dev.Customers.Add(new Customer()
{
Id = customer.Id,
Name = customer.Name
});
dev.SaveChanges();
return Ok();
}
public IQueryable<Customer> UpdateCustomer(Customer customer)
{
DevelopersEntities dev = new DevelopersEntities();
var cus = dev.Customers.Where(s => s.Id == customer.Id).FirstOrDefault();
cus.Id = customer.Id;
cus.Name = customer.Name;
dev.SaveChanges();
return Ok();
}
}
Values Controller
using DevelopersWeb.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebAPI;
namespace DevelopersWeb.Controllers
{
public class ValuesController : ApiController
{
ModelFactory _modelFactory;
public ValuesController()
{
_modelFactory = new ModelFactory();
}
// GET api/values
public IEnumerable<CustomerModel> Get()
{
CustomerRepository cr = new CustomerRepository();
return cr.GetAllCustomers().ToList().Select(c=> _modelFactory.Create(c));
}
// GET api/values/5
public string Get(int id)
{
return "xxx";
}
// POST api/values
public void Post([FromBody] CustomerModel customerModel)
{
CustomerRepository cr = new CustomerRepository();
cr.CreateCusomer(customer);
return Ok();
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}

Related

How can I get this DB entity method to work with .NET 6?

I am attempting to create a web application that is capable of searching an itunes API. It will require a database so I am using Entity framework and have a context file called SearchCountContext.cs. Inside this file I have a constructor which I need to use inside of my controller to manipulate data, the problem I am having is that I do not know how to call this method since it takes in 1 parameter DbContextOptions<ItunesSearchDBEntities> options and do not know what argument I need to pass in when invoking. Can someone help me figure this out?
SearchCountContext.cs:
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace ItunesMVC.DataAccess
{
public partial class ItunesSearchDBEntities : DbContext
{
public ItunesSearchDBEntities(DbContextOptions<ItunesSearchDBEntities> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.UseCollation("utf8mb4_0900_ai_ci")
.HasCharSet("utf8mb4");
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
public DbSet<SearchCount> SearchCounts { get; set; }
}
}
HomeController.cs:
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using ItunesMVC.Models;
namespace ItunesMVC.Controllers;
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public ActionResult Index()
{
ViewBag.SearchCounts = new DataAccess.ItunesSearchDBEntities().SearchCounts.OrderByDescending(a => a.Count).Take(25).ToList(); //Error here
return View();
}
public IActionResult Privacy()
{
return View();
}
[HttpGet]
public ActionResult Search(string Term)
{
try
{
var result = API.ItunesSearchAPI.Search(Term);
ViewBag.value = Term;
return View(result);
}
catch (Exception)
{
throw;
}
}
[HttpGet]
public ActionResult CountAndGO(string URL, string SearchTerm)
{
DataAccess.ItunesSearchDBEntities db = new DataAccess.ItunesSearchDBEntities();
//Finding the term in database.
var _term = db.SearchCounts.Where(a => a.Term == SearchTerm.ToLower()).FirstOrDefault();
if (_term != null)
{
//If term is present Count is added
_term.Count++;
db.Entry(_term).State = System.Data.EntityState.Modified;
}
else
{
//Term is saved in database
db.SearchCounts.Add(new SearchCount() { Term = SearchTerm.ToLower(), Count = 1 });
}
db.SaveChanges();
if (URL == null || URL == "")
return RedirectToAction("NoURL");
return Redirect(URL);
}
public ActionResult NoURL()
{
return View();
}
}
In your startup.cs or where you are registering your dependencies you may want to register an instance of your context (ItunesSearchDBEntities) by calling
services.AddDbContext<SimulationsDbContext>(d =>
{
d.UseSqlServer(simulationsDbConnectionString);
});
Then you would be able to inject your ItunesSearchDBEntities context into the homecontroller, or even at the method level by using the [FromServices] attribute https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/dependency-injection?view=aspnetcore-6.0

Unit testing - mocking service which has a List as a data storage

I'm new to Unit testing and I'm trying to learn how to do it.
I'm using Moq to Mock the dependencies.
Here's my Testing class:
using Microsoft.AspNetCore.Mvc;
using Moq;
using scholarship.Controllers;
using scholarship.Services.Interface;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using Xunit;
namespace Testing
{
public class InternControllerTests
{
private Mock<IInternService> _internService = new Mock<IInternService>();
[Theory]
[InlineData("00000000-0000-0000-0000-000000000001")]
[InlineData("00000000-0000-0000-0000-000000000002")]
public void Delete_Intern(Guid id)
{
InternsController internsController
= new InternsController(_internService.Object);
var actual = internsController.DeleteIntern(id) as ObjectResult;
Assert.True(actual is OkObjectResult);
}
[Theory]
[InlineData("00000000-0000-0000-0000-000000000000")]
[InlineData("00000000-0000-0000-0000-000000000005")]
public void Delete_Intern_NotFound(Guid id)
{
InternsController internsController
= new InternsController(_internService.Object);
var actual = internsController.DeleteIntern(id) as ObjectResult;
Assert.True(actual is NotFoundObjectResult);
}
}
}
the service:
using scholarship.Models;
using scholarship.Services.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace scholarship.Services.Class
{
public class InternCollectionService : IInternService
{
public static List<Intern> _interns = new List<Intern>
{
new Intern { ID = new Guid("00000000-0000-0000-0000-000000000001"), FirstName = "Octavian", LastName = "Niculescu", DateOfBirth=new DateTime(2001,01,01)},
new Intern { ID = new Guid("00000000-0000-0000-0000-000000000002"), FirstName = "Andrei", LastName = "Popescu", DateOfBirth=new DateTime(2002,01,01)},
new Intern { ID = new Guid("00000000-0000-0000-0000-000000000003"), FirstName = "Calin", LastName = "David", DateOfBirth=new DateTime(2003,01,01)},
};
public bool Create(Intern model)
{
_interns.Add(model);
return true;
}
public bool Delete(Guid id)
{
int index = _interns.FindIndex(intern => intern.ID == id);
if (index == -1)
{
return false;
}
_interns.RemoveAt(index);
return true;
}
public Intern Get(Guid id)
{
return (from intern in _interns
where intern.ID == id
select intern).FirstOrDefault();
}
public List<Intern> GetAll()
{
return _interns;
}
public bool Update(Guid id, Intern model)
{
int index = _interns.FindIndex(intern => intern.ID == id);
if (index == -1)
{
return false;
}
model.ID = id;
_interns[index] = model;
return true;
}
}
}
the controller
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using scholarship.Models;
using scholarship.Services.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace scholarship.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class InternsController : ControllerBase
{
IInternService _internService;
public InternsController(IInternService internService)
{
_internService = internService ?? throw new ArgumentNullException(nameof(internService));
}
[HttpGet]
public IActionResult GetInterns()
{
return Ok(_internService.GetAll());
}
[HttpGet("{Id}", Name = "GetIntern")]
public IActionResult GetIntern([FromRoute] Guid Id)
{
Intern? intern = _internService.Get(Id);
if(intern == null)
{
return NotFound();
}
return Ok(intern);
}
[HttpPost]
public IActionResult AddIntern([FromBody] Intern intern)
{
intern.ID = Guid.NewGuid();
_internService.Create(intern);
return CreatedAtRoute("GetIntern", new { ID = intern.ID }, intern);
}
[HttpPut("{id}")]
public IActionResult UpdateIntern([FromBody] Intern intern, Guid id)
{
if (intern == null)
{
return BadRequest("Intern cannot be null");
}
_internService.Update(id, intern);
return Ok();
}
[HttpDelete("{id}")]
public IActionResult DeleteIntern(Guid id)
{
bool deleted = _internService.Delete(id);
if (deleted == false)
{
return NotFound("Intern cannot be found");
}
return Ok();
}
}
}
The project is a very small one, I used it to start learning .net.
Now I want to learn Unit Testing, and I'm trying to learn Unit Testing.
The Delete tests fail.
I think this happens because by mocking the service, there is no list with data like in the service.
So, how should I make the Delete tests work? Should I somehow mock that list too? (I don't know how)
Thanks.
Although it is not best practice to test everything in one shoot, you can change your code as per below and test by status code with your inline data and hardcoded return type:
[Theory]
[InlineData("00000000-0000-0000-0000-000000000001", true, 200)]
[InlineData("00000000-0000-0000-0000-000000000002", true, 200)]
[InlineData("00000000-0000-0000-0000-000000000000", false, 404)]
[InlineData("00000000-0000-0000-0000-000000000005", false, 404)]
public void Delete_Intern(Guid id, bool expectedReturn, int expectedStatusCode)
{
InternsController internsController
= new InternsController(_internService.Object);
_internService.Setup(x => x.Delete(It.Is<Guid>(x => x.Equals(id)))).Returns(expectedReturn);
var actual = internsController.DeleteIntern(id) as ObjectResult;
Assert.True(actual.StatusCode == expectedStatusCode);
}
However, you can read the How to use Moq and xUnit for Unit Testing Controllers in ASP.NET Core which I think is a good practice.

Web API PUT Return Object with Proper HTTP Status Code

First, I want to say [HttpGet], [HttpGet("{id}")], and [HttpPost] is working correctly. However I'm running into a challenge with [HttpPut], and almost everywhere I look, the solution is to return without a status code.
I'm using visual studio 2019 with a project type of "ASP.NET Core Web Application" and "API" (ASP.NET Core 3.1).
I'm also using a secondary project in the same visual studio solution with the type(C#) "Class Library (.NET Standard)".
I'm using Postman to test the http request calls.
The following (Additional) NuGet Packages are required to be installed:
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.InMemory
System.ComponentModel.Annotations
The Solution Explorer:
There is a lot of code to cover with the .net core, and I will show it all here (as far as what has changed).
The Project "CoreStudy.Api" Code:
Startup.cs
using CoreStudy.Data.Context;
using CoreStudy.Data.Repository;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace CoreStudy.Api
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddScoped<PeopleRepository>(); // add this line
services.AddDbContext<PersonContext>(opt => opt.UseInMemoryDatabase("PeopleInventory")); // add this line, requires NuGet package "Microsoft.EntityFrameworkCore.InMemory"
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
PeopleController.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using CoreStudy.Data.Repository;
using CoreStudy.Data.Models;
using Microsoft.AspNetCore.Http;
namespace CoreStudy.Api.Controllers
{
[Route("people")]
[ApiController]
public class PeopleController : ControllerBase
{
private readonly PeopleRepository _repository;
public PeopleController(PeopleRepository repository)
{
_repository = repository;
}
[HttpGet]
[ProducesResponseType(typeof(List<PersonModel>), StatusCodes.Status200OK)]
public IActionResult GetPeople()
{
return Ok(_repository.GetPeople());
}
[HttpGet("{id}")]
[ProducesResponseType(typeof(PersonModel), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult GetPersonById(int id)
{
var person = _repository.GetPersonById(id);
if (person == null)
{
return NotFound();
}
return Ok(person);
}
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> AddPersonAsync([FromBody] PersonModel person)
{
if((_repository.GetPersonById(person.id) != null) || String.IsNullOrWhiteSpace(person.name))
{
return BadRequest();
}
int peopleAdded = await _repository.AddPersonAsync(person);
return CreatedAtAction(nameof(GetPersonById), new { person.id }, person);
}
[HttpPut]
[ProducesResponseType(typeof(PersonModel), StatusCodes.Status202Accepted)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ChangePersonNameByIdAsync([FromBody] PersonModel person)
{
if (_repository.GetPersonById(person.id) == null)
{
return NotFound();
}
else if (String.IsNullOrWhiteSpace(person.name))
{
return BadRequest();
}
PersonModel updatedPerson = await _repository.ChangePersonNameAsync(person);
return Ok(updatedPerson);
}
}
}
The Project "CoreStudy.Data" Code:
PersonContext.cs
using Microsoft.EntityFrameworkCore;
using CoreStudy.Data.Models;
namespace CoreStudy.Data.Context
{
public class PersonContext : DbContext
{
public PersonContext(DbContextOptions<PersonContext> options) : base(options)
{
}
public DbSet<PersonModel> people { get; set; }
}
}
PersonModel.cs
using System.ComponentModel.DataAnnotations;
namespace CoreStudy.Data.Models
{
public class PersonModel
{
public int id { get; set; }
[Required]
public string name { get; set; }
public string position { get; set; }
public PersonModel() { }
public PersonModel(string name, string position)
{
this.name = name;
this.position = position;
}
public PersonModel(int id, string name, string position)
{
this.id = id;
this.name = name;
this.position = position;
}
}
}
PeopleRepository.cs
using System.Collections.Generic;
using CoreStudy.Data.Models;
using CoreStudy.Data.Context;
using System.Linq;
using System.Threading.Tasks;
namespace CoreStudy.Data.Repository
{
public class PeopleRepository
{
private readonly PersonContext context;
public PeopleRepository(PersonContext context)
{
this.context = context;
if (context.people.Count() == 0)
{
context.people.AddRange(
new PersonModel
{
name = "shaggy",
position = "screwball"
},
new PersonModel
{
name = "scooby",
position = "screwball dog"
},
new PersonModel
{
name = "fred",
position = "leader"
},
new PersonModel
{
name = "velma",
position = "smart one"
},
new PersonModel
{
name = "daphne",
position = "popular one"
});
context.SaveChanges();
}
}
public List<PersonModel> GetPeople()
{
return context.people.ToList();
}
public PersonModel GetPersonById(int id)
{
PersonModel person = context.people.Find(id); // null if not found
return person;
}
public async Task<int> AddPersonAsync(PersonModel person)
{
int rowsAffected = 0;
context.people.Add(person);
rowsAffected = await context.SaveChangesAsync();
return rowsAffected;
}
public async Task<PersonModel> ChangePersonNameAsync(PersonModel person)
{
context.people.Update(person);
await context.SaveChangesAsync();
return GetPersonById(person.id);
}
}
}
When trying to make a PUT request with postman, I get the following error:
The problem is either in one of these two snippets:
public async Task<PersonModel> ChangePersonNameAsync(PersonModel person)
{
context.people.Update(person); // I thought Update() would be best used here, but not sure
await context.SaveChangesAsync();
return GetPersonById(person.id);
}
[HttpPut]
[ProducesResponseType(typeof(PersonModel), StatusCodes.Status202Accepted)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ChangePersonNameByIdAsync([FromBody] PersonModel person)
{
if (_repository.GetPersonById(person.id) == null)
{
return NotFound();
}
else if (String.IsNullOrWhiteSpace(person.name))
{
return BadRequest();
}
PersonModel updatedPerson = await _repository.ChangePersonNameAsync(person);
return Ok(updatedPerson); // not sure if I should be using Ok() for a PUT
}
If anyone could help me resolve this, myself (and I'm sure much of the internet) would thank you.
This already gets the entity:
if (_repository.GetPersonById(person.id) == null) { ... }
So you need to take that result:
var personDB = _repository.GetPersonById(person.id);
Then check if the variable is null
if(personDB != null) { ... }
Then you will need to change the personDB properties values with the person (from the PUT parameter) values.
After the line
if (_repository.GetPersonById(person.id) == null)
The person entity is already being tracked by the DbContext.
You don't need the extra repository layer at all. Your PersonContext already is a perfectly good repository. Just run:
context.people.Update(person);
await context.SaveChangesAsync();
return Ok(person);
in your controller.

Unable to resolve service for type while attempting to activate a service in startup.cs

Have spent way too much time trying to figure this out. Thanks for any help. .Net Core 3.1 trying to register a service in Startup.cs
Error CS0311: The type 'Apex.UI.MVC.ProjectService' cannot be used as type parameter 'TImplementation' in the generic type or method ServiceCollectionServiceExtensions.AddScoped<TService, TImplementation>(IServiceCollection). There is no implicit reference conversion from 'Apex.UI.MVC.ProjectService' to 'Apex.EF.Data.IProjects'. (CS0311) (Apex.UI.MVC)
services.AddScoped<IProjects, ProjectService>();
using System;
using Apex.EF.Data;
using Microsoft.AspNetCore.Mvc;
using System.Text.Encodings.Web;
using System.Linq;
using Apex.UI.MVC.Models.Projects;
namespace Apex.UI.MVC.Controllers
{
public class ProjectController : Controller
{
private IProjects _projects;
public ProjectController(IProjects projects)
{
_projects = projects;
}
public IActionResult Index()
{
var projectModels = _projects.GetAll();
var listingResult = projectModels
.Select(result => new ProjectIndexListingModel
{
Id = result.Id,
ProjectName = result.ProjectName,
ProjectImage = result.ProjectImage
});
var model = new ProjectIndexModel()
{
Project = listingResult
};
return View(model);
}
}
}
using System;
using System.Collections.Generic;
using Apex.EF.Data;
using Apex.EF.Data.Models;
namespace Apex.EF.Data
{
public interface IProjects
{
IEnumerable<Project> GetAll();
Project GetById(int id);
void Add(Project newProject);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using Apex.EF.Data;
using Apex.EF.Data.Models;
using Microsoft.EntityFrameworkCore;
namespace ApexServices
{
public class ProjectService : IProjects
{
private ApexContext _context;
public ProjectService(ApexContext context)
{
_context = context;
}
public void Add(Project newProject)
{
_context.Add(newProject);
_context.SaveChanges();
}
public IEnumerable<Project> GetAll()
{
return _context.Projects
.Include(project => project.Status.IsInShop == true);
}
public Project GetById(int id)
{
return _context.Projects
.Include(project => project.Status.IsInShop==true)
.FirstOrDefault(project => project.Id == id);
}
}
}
The namespaces shown in the exception are different to the example code shown. There are probably conflicting types in the project (not shown).
If that is really the case, then include the full namespace when registering the type with the container to avoid conflicts.
Based on the shown code, that would be
services.AddScoped<IProjects, ApexServices.ProjectService>();

UnitTest add item to list and check if exists

I want to test if my code works properly so I am writing some unit tests for it.
I want to check when and item in my list with the same values is added again it should return false.
I do not really understand how to set this up. I hope some can help me out.
Below my code
GuestResponseRepository
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PartyInvites.Abstract;
namespace PartyInvites.Models
{
public class GuestResponseRepository : IRepository
{
private static List<GuestResponse> responses = new List<GuestResponse>();
IEnumerable<GuestResponse> IRepository.GetAllResponses()
{
return responses;
}
bool IRepository.AddResponse(GuestResponse response)
{
if (responses.Any(x => x.Email == response.Email)) //here
{
if (responses.Any(x => x.WillAttend == response.WillAttend)) //here
{
return false;
}
var attend = responses.First(x => x.Email == response.Email && x.WillAttend != response.WillAttend);
attend.WillAttend = response.WillAttend;
return true;
}
responses.Add(response);
return true;
}
}
}
My interface which communicates with the GuestResponseRepository
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PartyInvites.Models;
namespace PartyInvites.Abstract
{
public interface IRepository
{
IEnumerable<GuestResponse> GetAllResponses();
bool AddResponse(GuestResponse response);
}
}
A piece of my Homecontroller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PartyInvites.Models;
using PartyInvites.Abstract;
namespace PartyInvites.Controllers {
public class HomeController : Controller {
private IRepository repository;
public HomeController(IRepository iRepository)
{
this.repository = iRepository;
}
[HttpGet]
public ViewResult RsvpForm() {
return View();
}
[HttpPost]
public ViewResult RsvpForm(GuestResponse guestResponse) {
if (ModelState.IsValid) {
bool result = repository.AddResponse(guestResponse);
ViewBag.Response = result;
repository.AddResponse(guestResponse);
return View("Thanks", guestResponse);
}
else
{
// there is a validation error
return View();
}
}
}
}
My UnitTest what I got so far
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PartyInvites.Abstract;
using PartyInvites.Controllers;
using PartyInvites.Models;
using Moq;
namespace Aanmelden
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void FirstResponse()
{
//Arange
Mock<IRepository> mock = new Mock<IRepository>();
mock.Setup(m => m.AddResponse()).Returns(new GuestResponse[] {
new GuestResponse {Name = "Valheru", Email = "valheru#hotmail.com", Phone = "12345678", WillAttend = true}
});
HomeController controller = new HomeController(mock.Object);
//Act
new GuestResponse
{
Name = "Valheru",
Email = "valheru#hotmail.com",
Phone = "12345678",
WillAttend = true
};
//Assert
if viewbag.response = result == false test succeeded
}
}
}
for some reason mock.Setup(m => m.**AddResponse**()).Returns(new GuestResponse[] {...
"AddResponse" aint right says Visual Studio ->
there is no argument given that corresponds to the required formal
parameter 'response' of IRepository.AddResponse(GuestReponse)
I am also no sure about my Act piece of code and I lost it totally with the Assert part. I hope someone can help me out!
you should It.IsAny<GuestResponse>() as a paramater in order to match the signature of your interface
Mock<IRepository> mock = new Mock<IRepository>();
mock.Setup(m => m.AddResponse(It.IsAny<GuestResponse>())).Returns(true);
Based on
I want to check when an item in my list with the same values is added
again it should return false.
You should actually be testing the GuestResponseRepository implementation itself and not the controller.
[TestMethod]
public void Duplicate_Added_Should_Return_False {
//Arrange
var sut = new GuestResponseRepository();
var model = new GuestResponse
{
Name = "Valheru",
Email = "valheru#hotmail.com",
Phone = "12345678",
WillAttend = true
};
sut.AddResponse(model);
var expected = false;
//Act
var actual = sut.AddResponse(model);
//Assert
Assert.AreEqual(expected, actual);
}

Categories