mercredi 24 mai 2017

EF Moq Unit Test, unsure verify

I am totally new to unit tests. I read many "tutorials" from different people and I decided to use msdn solutions.

I use this http://ift.tt/2hFWHft as my test, I am interested in "Testing non-query scenarios" there.

According to this article, I tried to test my simple CRUD's Create() action.

Here's my code (FinancialAssistantEntities is my DbContext (EF Database First)):

Context:

public partial class FinancialAssistantEntities : DbContext
{
    public FinancialAssistantEntities()
        : base("name=FinancialAssistantEntities")
    {
    }
    .
    .
    .
    public virtual DbSet<FAWallet> FAWallet { get; set; }
}

Repository method: (I commented out my transaction's using, because using it was causing the error "No connection string named 'FinancialAssistantEntities' could be found in the application config file."),

        public async Task<bool> CreateWallet(FAWallet model)
        {
            using (var context = Context)
            {
                // transaction with IsolationLevel
                //using (var tran = context.Database.BeginTransaction(IsolationLevel.ReadUncommitted))
                {
                    try
                    {                       
                        context.FAWallet.Add(model);
                        //context.SaveChanges();
                        await context.SaveChangesAsync();
                        //tran.Commit();
                        return true;
                    }
                    catch (Exception ex)
                    {
                        //tran.Rollback();
                        throw ex;
                    }
                }
            }
        }

TestMethod:

        [TestMethod]
        public void CreateWalletTest()
        {
            var wallet = new FAWallet()
            {
                WalletId = Guid.NewGuid(),
                //WalletName = StringHelper.GenerateRandomString(12),
                // admin ID
                WalletUserId = "e6888245-1d9b-431c-a068-aa62932e47ec",
                WalletCreateDate = DateTime.Now,
                WalletEnabled = true
            };

            var mockSet = new Mock<DbSet<FAWallet>>();

            var mockContext = new Mock<FinancialAssistantEntities>();
            mockContext.Setup(x => x.FAWallet).Returns(mockSet.Object);

            var walletRepository = new FAWalletRepository(mockContext.Object);
            walletRepository.CreateWallet(wallet).Wait();

            mockSet.Verify(x => x.Add(It.IsAny<FAWallet>()), Times.Once());
            mockContext.Verify(x => x.SaveChangesAsync(), Times.Once()); 
        }

First of all, I don't know if commenting transaction's using out is good idea, though I don't know much about testing yet.

Secondly, my test always passes. I event commented out the WalletName property's set, since this field is not-nullable, so it seems I made sth wrong.

Aucun commentaire:

Enregistrer un commentaire