Hello i have a project web api in c# and i want to write unit test to check my controller. But i find an error that i really don't understand. When i run my method in controller
public class TherapistsController : ApiController
{
TherapistService _therapistService = new TherapistService();
GeneralService _generalService = new GeneralService();
//GET: api/Therapists/GetAllTherapists
[HttpGet]
[Route("api/Therapists/GetAllTherapists")]
public IHttpActionResult GetTherapist()
{
var therapists = _therapistService.GetAllTherapist();
if (therapists.Count() > 0)
return Ok(therapists);
return NotFound();
}
}
it give me the result and it is fine

But if i run this method in a unit test
[TestClass]
public class UnitTest1
{
[TestMethod]
public void GetAllTherapistByOutletTest()
{
var therapists = new WebAPI.Controllers.TherapistsController();
IHttpActionResult result = therapists.GetTherapist();
Assert.IsInstanceOfType(result, typeof(OkResult));
}
}
it give me the error
Like u see the error says that i need to update database by migration but it still give me same error after i migrate and update database. But when i run the method by calling API ,it still give me the result like the first picture and no error. I debug both ways and they have same steps until method GetAll() in repository like u see in the above picture. I don't really know what wrong ?
Repository
public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
{
protected readonly SpaDbContext db;
public GenericRepository(SpaDbContext _db)
{
this.db = _db;
}
public void Add(TEntity entity)
{
db.Set<TEntity>().Add(entity);
}
public void AddRange(IEnumerable<TEntity> entities)
{
db.Set<TEntity>().AddRange(entities);
}
public void Detached(TEntity entity)
{
db.Entry<TEntity>(entity).State = EntityState.Detached;
}
public IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> predicate)
{
return db.Set<TEntity>().Where(predicate);
}
public TEntity Get(Expression<Func<TEntity, bool>> predicate)
{
return db.Set<TEntity>().FirstOrDefault(predicate);
}
public TEntity Get(object Id)
{
return db.Set<TEntity>().Find(Id);
}
public IEnumerable<TEntity> GetAll()
{
return db.Set<TEntity>().ToList();
}
public void Remove(TEntity entity)
{
db.Set<TEntity>().Remove(entity);
}
IRepository
namespace Repository
{
public interface IGenericRepository<TEntity> where TEntity : class
{
IEnumerable<TEntity> GetAll();
IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> predicate);
TEntity Get(Expression<Func<TEntity, bool>> predicate);
TEntity Get(object Id);
void Add(TEntity entity);
void AddRange(IEnumerable<TEntity> entities);
void Update(TEntity entity);
//void Remove(object Id);
void Remove(TEntity entity);
void RemoveRange(IEnumerable<TEntity> entities);
void Detached(TEntity entity);
IEnumerable<TEntity> GetByQuery(string query);
}
}
