13

I was looking at the repository method for an ASP.NET MVC app and noticed a static class wasn't used.

Since the repo is CRUD, why not make it static?

cнŝdk
  • 28,676
  • 7
  • 47
  • 67
Darcy
  • 4,780
  • 12
  • 51
  • 76

2 Answers2

29

1) It's difficult to do unit testing with static classes (if you are testing a class that depends on your repository, you want that test to work against a fake 'mocked' repository object instead of your real one)

2) You often want to have 1 repository instance per-request to make it easier to ensure that uncommited changes from one user don't mess things up for another user.

Robert Levy
  • 27,992
  • 6
  • 59
  • 93
  • Ah point number 2 was missing from my brain. Thanks Robert :) – Darcy Apr 11 '11 at 14:25
  • I don't get the second point. Aren't static classes one instance by definition? Please elaborate. – anar khalilov Jul 24 '13 at 18:42
  • 2
    @Anar - the difference is 1-instance vs. 1-instance-per-request – Robert Levy Dec 16 '13 at 14:36
  • I guess I understood that long time ago :). Thank you for answering anyway, Robert. – anar khalilov Dec 16 '13 at 15:00
  • 1
    From my experience static classes are easy to unittest since they are always constructed in a stateless fasion, so only input does affect output. With classes with internal states, it can be nearly impossible to know if all combinations are covered by the tests. – Robert Mar 12 '15 at 12:33
  • actually you cant mock a static class since they cant implement an interface – ColacX Oct 05 '15 at 13:32
  • @Robert you're not doing a unit test at that point, it's an integration test nor are you isolation a block of code. That's why static classes aren't good for unit testing. No mocking or faking – Nick Turner Apr 10 '18 at 14:45
0

Repository pattern increase testability, static classed decreases it.

gandjustas
  • 1,837
  • 12
  • 11