Konstantin Chernov
Konstantin Chernov

Reputation: 1936

Right way to Unit-test Repository.Update Method

Suppose we have typical repository

 public class Repository:IRepository<Entity>
    {
            public Entity GetById(int id)
            {
                //blah
            }

            public IEnumerable<Entity> All()
            {
                //blah
            }

            public void Insert(Entity entity)
            {

            }

            public void Update(Entity entity)
            {
                //blah
            }

            public void Delete(Entity entity)
            {
                //blah
            }
    }

Using MSTest, I want to test repository's ability to insert and update entities. As soon as it's concrete Repository, I'm testing against a real DB.

So, when I test Insert method - the strategy is clear

  1. Create new entity
  2. Save it
  3. Fetch entity by id
  4. Assert entity is returned by Repository

But when I'm thinking of Update method test it all gets somewhat tricky. The main questions are

Looks like workaround would require some not necessary code and test will get bloated. Is there any gracious solution?

Upvotes: 3

Views: 2590

Answers (1)

Ivan Karajas
Ivan Karajas

Reputation: 1101

Use ClassInitialize TestInitialize, along with ClassCleanup and TestCleanup to pre-populate the database with well-known entities. Then run your Update() tests against them.

Not sure how to interpret "not necessary code"... It looks like you are going to have to do something to populate your database in order to test the Update() method; at least the use of the attributes listed above allow you to implement the logic required to initialize and clean-up the database without polluting the actual test methods.

Upvotes: 3

Related Questions