jeudi 9 juillet 2015

Moq and DbSet without interfaces

I have a problem with unit tests in work(I'm new in unit test world). I have to test Provider who operates on ApplicationDbContext and DbSets but there aren't any interfaces of that and they are not virtual members. I can't create them becouse application is to big to make changes.

So, I need to work on classes. Now i have problem.

I need to test somethink like that:

    public bool AddOrUpdateSomeDbSet(SomeClass doc)
    {
        this.db.SomeDbSet.AddOrUpdate(doc);

        try
        {
            this.db.SaveChanges();
            return true;
        }
        catch (Exception)
        {
            //TODO: logging
            return false;
        }
    }

So firsty I want to test a success try.

  1. db; is ApplicationDbContext.
  2. I need to mock db.
  3. db.SomeDbSet.AddOrUpdate(doc) must return some stuff to don't crash test.

  4. db.SaveChanges() must return stuff too And I have problem with point 3 and 4.

About point number 3: I have somethink like that:

// That doesnt work because there is no .Return after that code. I dont know why.
contextMock.Setup(x => x.SomeDbSet.AddOrUpdate(It.IsAny<SomeClass>())).Returns(SomeStuff)

About point number 4:

In context are two methods SaveChanges() and SaveChanges(string value)

contextMock.Setup(x => x.SaveChanges("a")).Returns(1); // WORK

contextMock.Setup(x => x.SaveChanges()).Returns(1); // dont work

// An expression tree may not contain a call or invocation that uses optimal arguments - hmm?

Can anyone help me with it?

Aucun commentaire:

Enregistrer un commentaire