I have a method in my repository that I’m trying to test
public User UpdateUserManyToMany(User user, List<Guid> manyToManyds)
{
var dbContext = _databaseContext as DbContext;
dbContext?.TryUpdateManyToMany(user.ManyToMany, manyToManyds
.Select(x => new ManyToMany{
OtherEntityId = x,
UserId = user.Id,
}), x => x.OtherEntityId);
return user;
}
My ManyToMany Entity :
public class ManyToMany
{
public Guid OtherEntityId { get; set; }
public OtherEntity OtherEntityId { get; set; }
public Guid UserId { get; set; }
public User User { get; set; }
}
My TryUpdateManyToMany :
public static class ManyToManyExtensions
{
public static void TryUpdateManyToMany<T, TKey>(this DbContext db, IEnumerable<T> currentItems, IEnumerable<T> newItems, Func<T, TKey> getKey) where T : class
{
db.Set<T>().RemoveRange(currentItems.Except(newItems, getKey));
db.Set<T>().AddRange(newItems.Except(currentItems, getKey));
}
public static IEnumerable<T> Except<T, TKey>(this IEnumerable<T> items, IEnumerable<T> other, Func<T, TKey> getKeyFunc)
{
return items
.GroupJoin(other, getKeyFunc, getKeyFunc, (item, tempItems) => new { item, tempItems })
.SelectMany(t => t.tempItems.DefaultIfEmpty(), (t, temp) => new { t, temp })
.Where(t => ReferenceEquals(null, t.temp) || t.temp.Equals(default(T)))
.Select(t => t.t.item);
}
}
Here’s my unit test :
using (var context = new InMemoryDataBaseContext())
{
// Arrange
var repository = new UserRepository(context);
await context.Users.AddRangeAsync(GetUser());
await context.SaveChangesAsync();
// Act
var manyIds = new List<Guid>();
manyIds.Add(Guid.Parse("855d1a64-a707-40d5-ab93-34591a923abf"));
manyIds.Add(Guid.Parse("855d1a64-a787-40d9-ac93-34591a923abf"));
manyIds.Add(Guid.Parse("855d1a64-a707-41d9-ab93-39591a923abf"));
var user = new User();
var expected = repository.UpdateUserManyToMany(GetUser(), manyIds);
// Assert
}
But I get the following error in my test :
Message:
System.InvalidOperationException : The instance of entity type 'ManyToMany' cannot be tracked because another instance with the same key value for {'UserId', 'OtherEntityId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
Arborescence des appels de procédure:
IdentityMap`1.ThrowIdentityConflict(InternalEntityEntry entry)
IdentityMap`1.Add(TKey key, InternalEntityEntry entry, Boolean updateDuplicate)
IdentityMap`1.Add(TKey key, InternalEntityEntry entry)
NullableKeyIdentityMap`1.Add(InternalEntityEntry entry)
StateManager.StartTracking(InternalEntityEntry entry)
InternalEntityEntry.SetEntityState(EntityState oldState, EntityState newState, Boolean acceptChanges, Boolean modifyProperties)
InternalEntityEntry.SetEntityState(EntityState entityState, Boolean acceptChanges, Boolean modifyProperties, Nullable`1 forceStateWhenUnknownKey)
EntityGraphAttacher.PaintAction(EntityEntryGraphNode`1 node)
EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode`1 node, Func`2 handleNode)
EntityGraphAttacher.AttachGraph(InternalEntityEntry rootEntry, EntityState targetState, EntityState storeGeneratedWithKeySetTargetState, Boolean forceStateWhenUnknownKey)
DbContext.SetEntityState(InternalEntityEntry entry, EntityState entityState)
DbContext.RemoveRange(IEnumerable`1 entities)
InternalDbSet`1.RemoveRange(IEnumerable`1 entities)
ManyToManyExtensions.TryUpdateManyToMany[T,TKey](DbContext db, IEnumerable`1 currentItems, IEnumerable`1 newItems, Func`2 getKey) ligne 24
UserRepository.UpdateUserManyToMany(User user, List`1 manyToManyds) ligne 59
MyRepoUnitTest.MyTestMethod() ligne 102
--- End of stack trace from previous location where exception was thrown ```
The following sample program, that is based on the code you provided, works without issues:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace IssueConsoleTemplate
{
public class User
{
public Guid Id { get; set; }
public string Name { get; set; }
public ICollection<ManyToMany> ManyToMany { get; set; } = new HashSet<ManyToMany>();
}
public class OtherEntity
{
public Guid Id { get; set; }
public string Name { get; set; }
public ICollection<ManyToMany> ManyToMany { get; set; } = new HashSet<ManyToMany>();
}
public class ManyToMany
{
public Guid OtherEntityId { get; set; }
public Guid UserId { get; set; }
public OtherEntity OtherEntity { get; set; }
public User User { get; set; }
}
public class Context : DbContext
{
public DbSet<OtherEntity> OtherEntities { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<ManyToMany> ManyToMany { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseSqlServer(#"Data Source=.\MSSQL14;Integrated Security=SSPI;Initial Catalog=So63077461")
.UseLoggerFactory(
LoggerFactory.Create(
b => b
.AddConsole()
.AddFilter(level => level >= LogLevel.Information)))
.EnableSensitiveDataLogging()
.EnableDetailedErrors();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<OtherEntity>(
entity =>
{
entity.HasKey(e => e.Id);
entity.HasMany(e => e.ManyToMany)
.WithOne(e => e.OtherEntity)
.HasForeignKey(e => e.OtherEntityId);
entity.HasData(
new OtherEntity
{
Id = new Guid("855d1a64-a707-40d5-ab93-34591a923abf"),
Name = "Bicycle"
},
new OtherEntity
{
Id = new Guid("855d1a64-a787-40d9-ac93-34591a923abf"),
Name = "Bus"
},
new OtherEntity
{
Id = new Guid("855d1a64-a707-41d9-ab93-39591a923abf"),
Name = "Plane"
});
});
modelBuilder.Entity<User>(
entity =>
{
entity.HasKey(e => e.Id);
entity.HasMany(e => e.ManyToMany)
.WithOne(e => e.User)
.HasForeignKey(e => e.UserId);
});
modelBuilder.Entity<ManyToMany>(
entity =>
{
entity.HasKey(e => new {e.OtherEntityId, e.UserId});
});
}
}
public static class ManyToManyExtensions
{
public static void TryUpdateManyToMany<T, TKey>(this DbContext db, IEnumerable<T> currentItems, IEnumerable<T> newItems, Func<T, TKey> getKey) where T : class
{
db.Set<T>().RemoveRange(currentItems.Except(newItems, getKey));
db.Set<T>().AddRange(newItems.Except(currentItems, getKey));
}
public static IEnumerable<T> Except<T, TKey>(this IEnumerable<T> items, IEnumerable<T> other, Func<T, TKey> getKeyFunc)
{
return items
.GroupJoin(other, getKeyFunc, getKeyFunc, (item, tempItems) => new { item, tempItems })
.SelectMany(t => t.tempItems.DefaultIfEmpty(), (t, temp) => new { t, temp })
.Where(t => ReferenceEquals(null, t.temp) || t.temp.Equals(default(T)))
.Select(t => t.t.item);
}
}
internal class UserRepository
{
private readonly Context _databaseContext;
public UserRepository(Context context)
{
_databaseContext = context;
}
public User UpdateUserManyToMany(User user, List<Guid> manyToManyds)
{
var dbContext = _databaseContext as DbContext;
dbContext?.TryUpdateManyToMany(user.ManyToMany, manyToManyds
.Select(x => new ManyToMany{
OtherEntityId = x,
UserId = user.Id,
}), x => x.OtherEntityId);
return user;
}
}
internal static class Program
{
private static async Task Main()
{
//
// Operations with referential integrity intact:
//
using var context = new Context();
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
// Arrange
var repository = new UserRepository(context);
await context.Users.AddRangeAsync(GetUser());
await context.SaveChangesAsync();
// Act
var manyIds = new List<Guid>
{
new Guid("855d1a64-a707-40d5-ab93-34591a923abf"),
new Guid("855d1a64-a787-40d9-ac93-34591a923abf"),
new Guid("855d1a64-a707-41d9-ab93-39591a923abf")
};
var expected = repository.UpdateUserManyToMany(GetUser(), manyIds);
}
private static User GetUser()
=> User;
private static readonly User User = new User
{
Id = new Guid("30c35d2e-77fd-480b-9974-6ebf037a8f86"),
Name = "John"
};
}
}
System.InvalidOperationException : The instance of entity type 'ManyToMany' cannot be tracked because another instance with the same key value for {'UserId', 'OtherEntityId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
The error message says, that at least one of your ManyToMany entries already exists in the database (there is an entry with the same UserId and OtherEntityId combination).
You can verify this, by running the following code directly after your filled the manyIds variable with the 3 IDs:
var user = GetUser();
var alreadyExistingManyToMany = context.ManyToMany
.Where(m => m.UserId == user.Id &&
manyIds.Contains(m.OtherEntityId))
.ToList();
Debug.Assert(alreadyExistingManyToMany.Count == 0);
Related
I have sealed a class with no constructor which is I am referred using SDK to my project. I want to create fixture data for the class to write test but AutoFixture is giving an expectation like below.
AutoFixture was unable to create an instance from SealedTypeclass, most likely because it has no public constructor, is an abstract or non-public type.
Please find the below code example for which I am trying to create a fixture.
public sealed class TokenCacheItem
{
public string Authority { get; }
public string ClientId { get; }
public DateTimeOffset ExpiresOn { get; }
public string FamilyName { get; }
public string GivenName { get; }
public string IdentityProvider { get; }
public string TenantId { get; }
}
With the above-sealed class i am referring through SDK and I am trying to create fixture data. I am getting the below error message.
Message:
AutoFixture.ObjectCreationExceptionWithPath : AutoFixture was unable to create an instance from ***, most likely because it has no public constructor, is an abstract or non-public type.
Any generic solution?
Given that it's sealed and reporting that it doesn't have a public constructor, you're going to have to provide a way to create an instance and it's probably going to be a reflection based solution. The read only properties add another complexity for AutoFixture as well.
Without seeing the constructor, or whether there are any backing fields for the read only properties I'm going to make some assumptions with the following working example.
Create something that can create a TokenCacheItem and set its properties:
public class MutableTokenCacheItem
{
private TokenCacheItem _tokenCacheItem;
public string Authority { get => _tokenCacheItem.Authority; set => SetPropertyValue(x => x.Authority, value); }
public string ClientId { get => _tokenCacheItem.ClientId; set => SetPropertyValue(x => x.ClientId, value); }
public DateTimeOffset ExpiresOn { get => _tokenCacheItem.ExpiresOn; set => SetPropertyValue(x => x.ExpiresOn, value); }
public string FamilyName { get => _tokenCacheItem.FamilyName; set => SetPropertyValue(x => x.FamilyName, value); }
public string GivenName { get => _tokenCacheItem.GivenName; set => SetPropertyValue(x => x.GivenName, value); }
public string IdentityProvider { get => _tokenCacheItem.IdentityProvider; set => SetPropertyValue(x => x.IdentityProvider, value); }
public string TenantId { get => _tokenCacheItem.TenantId; set => SetPropertyValue(x => x.TenantId, value); }
public MutableTokenCacheItem()
{
var ctor = typeof(TokenCacheItem).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic).Single();
_tokenCacheItem = (TokenCacheItem)ctor.Invoke(null);
}
private void SetPropertyValue<P>(Expression<Func<TokenCacheItem, P>> expression, object value)
{
var body = expression.Body as MemberExpression;
var backingField = typeof(TokenCacheItem).GetRuntimeFields().Where(a => Regex.IsMatch(a.Name, $"\\A<{body.Member.Name}>k__BackingField\\Z")).Single();
backingField.SetValue(_tokenCacheItem, value);
}
public TokenCacheItem AsImmutableTokenCacheItem()
{
return _tokenCacheItem;
}
}
Create a specimen builder to bolt it into AutoFixture nicely:
public class TokenCacheItemSpecimenBuilder : ISpecimenBuilder
{
public object Create(object request, ISpecimenContext context)
{
var t = request as Type;
if (typeof(TokenCacheItem).Equals(t))
{
var mutableTokenCacheItem = context.Create<MutableTokenCacheItem>();
return mutableTokenCacheItem.AsImmutableTokenCacheItem();
}
return new NoSpecimen();
}
}
Add the customization and off you go:
var fixture = new Fixture();
fixture.Customizations.Add(new TokenCacheItemSpecimenBuilder());
fixture.Create<TokenCacheItem>();
Working LINQPad example:
void Main()
{
var fixture = new Fixture();
fixture.Customizations.Add(new TokenCacheItemSpecimenBuilder());
Console.Write(fixture.Create<TokenCacheItem>());
}
public class TokenCacheItemSpecimenBuilder : ISpecimenBuilder
{
public object Create(object request, ISpecimenContext context)
{
var t = request as Type;
if (typeof(TokenCacheItem).Equals(t))
{
var mutableTokenCacheItem = context.Create<MutableTokenCacheItem>();
return mutableTokenCacheItem.AsImmutableTokenCacheItem();
}
return new NoSpecimen();
}
}
public class MutableTokenCacheItem
{
private TokenCacheItem _tokenCacheItem;
public string Authority { get => _tokenCacheItem.Authority; set => SetPropertyValue(x => x.Authority, value); }
public string ClientId { get => _tokenCacheItem.ClientId; set => SetPropertyValue(x => x.ClientId, value); }
public DateTimeOffset ExpiresOn { get => _tokenCacheItem.ExpiresOn; set => SetPropertyValue(x => x.ExpiresOn, value); }
public string FamilyName { get => _tokenCacheItem.FamilyName; set => SetPropertyValue(x => x.FamilyName, value); }
public string GivenName { get => _tokenCacheItem.GivenName; set => SetPropertyValue(x => x.GivenName, value); }
public string IdentityProvider { get => _tokenCacheItem.IdentityProvider; set => SetPropertyValue(x => x.IdentityProvider, value); }
public string TenantId { get => _tokenCacheItem.TenantId; set => SetPropertyValue(x => x.TenantId, value); }
public MutableTokenCacheItem()
{
var ctor = typeof(TokenCacheItem).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic).Single();
_tokenCacheItem = (TokenCacheItem)ctor.Invoke(null);
}
private void SetPropertyValue<P>(Expression<Func<TokenCacheItem, P>> expression, object value)
{
var body = expression.Body as MemberExpression;
var backingField = typeof(TokenCacheItem).GetRuntimeFields().Where(a => Regex.IsMatch(a.Name, $"\\A<{body.Member.Name}>k__BackingField\\Z")).Single();
backingField.SetValue(_tokenCacheItem, value);
}
public TokenCacheItem AsImmutableTokenCacheItem()
{
return _tokenCacheItem;
}
}
public sealed class TokenCacheItem
{
public string Authority { get; }
public string ClientId { get; }
public DateTimeOffset ExpiresOn { get; }
public string FamilyName { get; }
public string GivenName { get; }
public string IdentityProvider { get; }
public string TenantId { get; }
private TokenCacheItem() { }
}
Result:
YMMV depending on the actual TokenCacheItem implementation though it's probably not far off.
I am writing test for Web API application written in .NET CORE 3.1. I am using xUnit, AutoFixture & Moq for testing. I have a class that creates a new school instance in the database using Entity Framework/ DbContext. My question is how to mock dbContext & save changes, further my School DataModel has one: many relationships with SchoolBranch DataModel. I have followed this tutorial https://learn.microsoft.com/en-us/ef/ef6/fundamentals/testing/mocking
Error
Message:
Moq.MockException :
Expected invocation on the mock once, but was 0 times: m => m.Add<School>(It.IsAny<School>())
Performed invocations:
Mock<SchoolDbContext:1> (m):
No invocations performed.
Stack Trace:
Mock.Verify(Mock mock, LambdaExpression expression, Times times, String failMessage)
Mock`1.Verify[TResult](Expression`1 expression, Times times)
CreateSchoolCommandTest.ExecuteMethod_ShouldReturnNewGuidId_IfSuccess() line 50
School
public class School
{
public School()
{
this.SchoolBranches = new HashSet<SchoolBranch>();
}
public Guid SchoolID { get; set; }
public string Name { get; set; }
public ICollection<SchoolBranch> SchoolBranches { get; set; }
}
SchoolBranch
public class SchoolBranch
{
public SchoolBranch()
{
}
public Guid SchoolBranchID { get; set; }
public Guid SchoolID { get; set; }
public string Address { get; set; }
public int PhoneNumber { get; set; }
public School School { get; set; }
}
CreateSchool Class
public class CreateSchool : BaseCommand<Guid>, ICreateSchool
{
public SchoolDto SchoolDtos { get; set; }
public CreateSchool(IAppAmbientState appAmbient) : base(appAmbient) { }
public override Guid Execute()
{
try
{
var schoolId = Guid.NewGuid();
List<SchoolBranch> schoolBranches = new List<SchoolBranch>();
foreach(var item in SchoolDtos.SchoolBranchDtos)
{
schoolBranches.Add(new SchoolBranch()
{
SchoolBranchID = Guid.NewGuid(),
SchoolID = schoolId,
Address = item.Address,
PhoneNumber = item.PhoneNumber
});
}
var school = new School()
{
SchoolID = schoolId,
Name = SchoolDtos.Name,
SchoolBranches = schoolBranches
};
schoolDbContext.Schools.Add(school);
schoolDbContext.SaveChanges();
return school.SchoolID;
}
catch(Exception exp)
{
appAmbientState.Logger.LogError(exp);
throw;
}
}
}
Test Class
public class CreateSchoolCommandTest
{
private readonly ICreateSchool sut;
private readonly Mock<IAppAmbientState> appAmbientState = new Mock<IAppAmbientState>();
[Fact]
public void ExecuteMethod_ShouldReturnNewGuidId_IfSuccess()
{
//Arrange
var fixture = new Fixture();
var schoolDtoMock = fixture.Create<SchoolDto>();
var schoolDbSetMock = new Mock<DbSet<School>>();
var schoolBranchDbSetMock = new Mock<DbSet<SchoolBranch>>();
var schoolDbContextMock = new Mock<SchoolDbContext>();
//schoolDbSetMock.Setup(x => x.Add(It.IsAny<School>())).Returns((School s) => s); // this also did not work
schoolDbContextMock.Setup(m => m.Schools).Returns(schoolDbSetMock.Object);
//Act
sut.SchoolDtos = schoolDtoMock;
var actualDataResult = sut.Execute();
// Assert
Assert.IsType<Guid>(actualDataResult);
schoolDbContextMock.Verify(m => m.Add(It.IsAny<School>()), Times.Once());
schoolDbContextMock.Verify(m => m.SaveChanges(), Times.Once());
}
BaseCommand (DbContext is created here)
public abstract class BaseCommand<T>
{
protected SchoolDbContext schoolDbContext;
protected IAppAmbientState appAmbientState { get; }
public BaseCommand(IAppAmbientState ambientState)
{
this.schoolDbContext = new SchoolDbContext();
this.appAmbientState = ambientState;
}
public abstract T Execute();
}
For fix Error
You made just a little mistake. Insted of
schoolDbContextMock.Verify(m => m.Add(It.IsAny<School>()), Times.Once());
schoolDbContextMock.Verify(m => m.SaveChanges(), Times.Once());
You should have
schoolDbSetMock.Verify(m => m.Add(It.IsAny<School>()), Times.Once());
schoolDbContextMock.Verify(m => m.SaveChanges(), Times.Once());
Because you use method Add() on schoolDbContext.Schools not on schoolDbContext
For injecting dbContext
Your BaseCoommand class constructor should look like this:
public BaseCommand(IAppAmbientState ambientState, SchoolDbContext schoolDbContext)
{
this.schoolDbContext = schoolDbContext;
this.appAmbientState = ambientState;
}
Your CreateSchool class constructor:
public CreateSchool(IAppAmbientState appAmbient, SchoolDbContext schoolDbContext) : base(appAmbient, schoolDbContext) { }
And next in test you should initialize CreateSchool in test like this:
var sut = new CreateSchool(ambientState, schoolDbContextMock.Object);
And it will work
What is the best way to mock below code in unit testing:
public ActionResult Products()
{
ViewBag.Title = "Company Product";
IEnumerable<ProductDetailDto> productList = ProductService.GetAllEffectiveProductDetails();
ProductModels.ProductCategoryListModel model = new ProductModels.ProductCategoryListModel
{
//the type of ProductDetails => IEnumerable<productDetailDto>
ProductDetails = ProductService.GetAllEffectiveProductDetails(),
//the type of ProductCategoryList => IEnumerable<selectlistitem>
ProductCategoryList = productList.Select(x => new SelectListItem
{
Value = x.FKProductId.ToString(),
Text = x.Name
})
};
return View(model);
}
FYI, I am working on VS 2012, MVC 4.0, Unit Testing with MOQ object and TFS setup.
Can anyone help me out on this what is the best test method with mock object for above method?
If you want to mock ProductService first you need to inject this dependency.
Constructor injection is the most common approach for controllers in ASP.NET MVC.
public class YourController : Controller
{
private readonly IProductService ProductService;
/// <summary>
/// Constructor injection
/// </summary>
public YourController(IProductService productService)
{
ProductService = productService;
}
/// <summary>
/// Code of this method has not been changed at all.
/// </summary>
public ActionResult Products()
{
ViewBag.Title = "Company Product";
IEnumerable<ProductDetailDto> productList = ProductService.GetAllEffectiveProductDetails();
ProductModels.ProductCategoryListModel model = new ProductModels.ProductCategoryListModel
{
//the type of ProductDetails => IEnumerable<productDetailDto>
ProductDetails = ProductService.GetAllEffectiveProductDetails(),
//the type of ProductCategoryList => IEnumerable<selectlistitem>
ProductCategoryList = productList.Select(x => new SelectListItem
{
Value = x.FKProductId.ToString(),
Text = x.Name
})
};
return View(model);
}
}
#region DataModels
public class ProductDetailDto
{
public int FKProductId { get; set; }
public string Name { get; set; }
}
public class ProductModels
{
public class ProductCategoryListModel
{
public IEnumerable<ProductDetailDto> ProductDetails { get; set; }
public IEnumerable<SelectListItem> ProductCategoryList { get; set; }
}
}
#endregion
#region Services
public interface IProductService
{
IEnumerable<ProductDetailDto> GetAllEffectiveProductDetails()
}
public class ProductService : IProductService
{
public IEnumerable<ProductDetailDto> GetAllEffectiveProductDetails()
{
throw new NotImplementedException();
}
}
#endregion
Then you easily create a mock instance of IProductService, pass it into constructor of YourController, setup GetAllEffectiveProductDetails method and check returned ActionResult and its model.
[TestClass]
public class YourControllerTest
{
private Mock<IProductService> productServiceMock;
private YourController target;
[TestInitialize]
public void Init()
{
productServiceMock = new Mock<IProductService>();
target = new YourController(
productServiceMock.Object);
}
[TestMethod]
public void Products()
{
//arrange
// There is a setup of 'GetAllEffectiveProductDetails'
// When 'GetAllEffectiveProductDetails' method is invoked 'expectedallProducts' collection is exposed.
var expectedallProducts = new List<ProductDetailDto> { new ProductDetailDto() };
productServiceMock
.Setup(it => it.GetAllEffectiveProductDetails())
.Returns(expectedallProducts);
//act
var result = target.Products();
//assert
var model = (result as ViewResult).Model as ProductModels.ProductCategoryListModel;
Assert.AreEqual(model.ProductDetails, expectedallProducts);
/* Any other assertions */
}
}
I have a domain class:
public class Agencia : IEntity
{
public virtual int Id { get; set; }
public virtual string Nome { get; set; }
public virtual string Identificacao { get; set; }
public virtual IList<Pessoa> Gerentes { get; protected set; }
public Agencia()
{
Gerentes = new List<Pessoa>();
}
public virtual void AddGerente(Pessoa gerente)
{
Gerentes.Add(gerente);
}
public virtual void AddGerentes(params Pessoa[] gerentes)
{
Parallel.ForEach(gerentes, (pessoa) => Gerentes.Add(pessoa));
}
}
public class Pessoa: IEntity
{
public virtual int Id { get; set; }
public virtual string Nome { get; set; }
}
With this convention (defined as set AsSet)
public class AgenciaConvention : IAutoMappingOverride<Agencia>
{
public void Override(AutoMapping<Agencia> mapping)
{
mapping.HasManyToMany(a => a.Gerentes).Cascade.AllDeleteOrphan().AsSet().Not.Inverse();
}
}
When I run this test:
[TestMethod]
[Description("Uma agência tem vários gerêntes")]
public void AgenciaTemVariosGerentes()
{
// Arrange
var fix = new Fixture();
var currentUser = GetLoggedUser();
// Create a List<Pessoa>
var gerentes = fix.Build<Pessoa>()
.With(p => p.Nome)
.With(p => p.CPF)
.With(p => p.CreateBy, currentUser)
.OmitAutoProperties()
.CreateMany<Pessoa>(10).ToList();
// Action
new PersistenceSpecification<Agencia>(Session)
.CheckProperty(p => p.Nome, fix.Create<string>().Truncate(80))
.CheckProperty(p => p.Identificacao, fix.Create<string>().Truncate(10))
.CheckReference(p => p.Regional,
fix.Build<Regional>()
.With(p => p.Nome)
.OmitAutoProperties()
.Create()
, new IDEqualityComparer())
.CheckList(p => p.Gerentes, gerentes, new IDEqualityComparer())
.CheckReference(p => p.CreateBy, currentUser, new IDEqualityComparer())
.VerifyTheMappings(); // Assert
}
How can I test this list?
The collection should be AsSet, it necessary that the Parent and Children fields are PK, FK
Full Error:
Test Name: AgenciaTemVariosGerentes
Test FullName: {OMMITED}.Integration.Test.AgenciaTest.AgenciaTemVariosGerentes
Test Source: {OMMITED}.Integration.Test\AgenciaTest.cs : line 22
Test Outcome: Failed
Test Duration: 0:00:02,4093555
Result Message:
Test method {OMMITED}.Integration.Test.AgenciaTest.AgenciaTemVariosGerentes threw exception:
NHibernate.PropertyAccessException: Invalid Cast (check your mapping for property type mismatches); setter of CreditoImobiliarioBB.Model.Regional ---> System.InvalidCastException: Unable to cast object of type 'NHibernate.Collection.Generic.PersistentGenericSet1[CreditoImobiliarioBB.Model.Pessoa]' to type 'System.Collections.Generic.IList1[CreditoImobiliarioBB.Model.Pessoa]'.
Result StackTrace:
at (Object , Object[] , SetterCallback )
at NHibernate.Bytecode.Lightweight.AccessOptimizer.SetPropertyValues(Object target, Object[] values)
at NHibernate.Tuple.Entity.PocoEntityTuplizer.SetPropertyValuesWithOptimizer(Object entity, Object[] values)
--- End of inner exception stack trace ---
at NHibernate.Tuple.Entity.PocoEntityTuplizer.SetPropertyValuesWithOptimizer(Object entity, Object[] values)
at NHibernate.Tuple.Entity.PocoEntityTuplizer.SetPropertyValues(Object entity, Object[] values)
at NHibernate.Persister.Entity.AbstractEntityPersister.SetPropertyValues(Object obj, Object[] values, EntityMode entityMode)
at NHibernate.Event.Default.AbstractSaveEventListener.PerformSaveOrReplicate(Object entity, EntityKey key, IEntityPersister persister, Boolean useIdentityColumn, Object anything, IEventSource source, Boolean requiresImmediateIdAccess)
at NHibernate.Event.Default.AbstractSaveEventListener.PerformSave(Object entity, Object id, IEntityPersister persister, Boolean useIdentityColumn, Object anything, IEventSource source, Boolean requiresImmediateIdAccess)
at NHibernate.Event.Default.AbstractSaveEventListener.SaveWithGeneratedId(Object entity, String entityName, Object anything, IEventSource source, Boolean requiresImmediateIdAccess)
at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.SaveWithGeneratedOrRequestedId(SaveOrUpdateEvent event)
at NHibernate.Event.Default.DefaultSaveEventListener.SaveWithGeneratedOrRequestedId(SaveOrUpdateEvent event)
at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.EntityIsTransient(SaveOrUpdateEvent event)
at NHibernate.Event.Default.DefaultSaveEventListener.PerformSaveOrUpdate(SaveOrUpdateEvent event)
at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.OnSaveOrUpdate(SaveOrUpdateEvent event)
at NHibernate.Impl.SessionImpl.FireSave(SaveOrUpdateEvent event)
at NHibernate.Impl.SessionImpl.Save(Object obj)
at FluentNHibernate.Testing.PersistenceSpecification1.TransactionalSave(Object propertyValue)
at FluentNHibernate.Testing.Values.ReferenceProperty2.HasRegistered(PersistenceSpecification1 specification)
at FluentNHibernate.Testing.PersistenceSpecification1.RegisterCheckedProperty(Property1 property, IEqualityComparer equalityComparer)
at FluentNHibernate.Testing.PersistenceSpecificationExtensions.CheckReference[T](PersistenceSpecification1 spec, Expression`1 expression, Object propertyValue, IEqualityComparer propertyComparer)
at CreditoImobiliarioBB.Repository.Integration.Test.AgenciaTest.AgenciaTemVariosGerentes() in {OMMITED}.Integration.Test\AgenciaTest.cs:line 27
Thanks.
Sets don't implement IList<T>.
Define your properties as ICollection<T> instead.
I have a Apicontroller Which has dependency on unit of work object. How to write a test case for mocking ApiController Which has dependency on unit of work implemented in ApiController constructor.
Here is the code:
ApiController:
public class UserController : ApiController
{
public IUoW UoW { get; set; }
// GET api/user
public UserController(IUoW uow)
{
UoW = uow;
}
public IEnumerable<Users> Get()
{
return UoW.Users.Getall();
}
}
The Test case :
[TestMethod]
public void TestApiController()
{
var userManager = new Mock<IUoW>();
userManager.Setup(s => s.Users);
var controller = new UserController(userManager.Object);
var values = controller.Get();
Assert.IsNotNull(values);
}
The Users Class which has been mentioned here in UoW.Users is
public class UoW:IUoW,IDisposable
{
private MvcWebApiContext DbContext { get; set; }
protected IRepositoryProvider RepositoryProvider { get; set; }
private IRepository<T> GetStandardRepo<T>() where T : class
{
return RepositoryProvider.GetRepositoryForEntityType<T>();
}
public IRepository<Users> Users
{
get { return GetStandardRepo<Users>(); }
}
}
and the Users class itself is
[Table("UserProfile")]
public class Users
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
[DataType(DataType.PhoneNumber)]
public long Mobile { get; set; }
}
When I am trying to debug the test case , the Test case shows the object UoW.Users is null in UserController. Its obvious its not initializing through WebActivator since global.asax isnt invoked here through mock. Now how to write a successful test scenario in this context so that the WebApicontroller returns me the users object with data ?
Are you using Moq?
As I cannot see what type the UoW.Users property is I cannot demo how to mock it properly (updated IRepository) but that should be mocked and the GetAll method stubbed to return a sample list of users.
Updated
var userManager = new Mock<IUoW>();
userManager.Setup(s => s.Users).Returns(()=>
{
var userReposisitory = new Mock<IRepository<Users>>();
userReposisitory.Setup(ur => ur.GetAll()).Returns(()=> {
var listOfUsers = new List<Users>();
listOfUsers.Add(new Users { FirstName = "Example" });
return listOfUsers.AsQueryable();
});
return userReposisitory.Object;
});
var controller = new UserController(userManager.Object);
var result = controller.Get();
Assert.IsNotNull(result);
Assert.IsTrue(result.Count() > 0);