Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of creating a unit test with a Fake/ Stub Repository

I have looked a similar questions on here and I think I get the gist of where people answers are heading but I need to confirm whether or not I should create pure unit tests with Stubbed repositories for my solution.

If I have the following Unit Test (created using Microsoft's Fake Assemblies and MSTest):

 [TestMethod]
 public void creating_user_returns_a_valid_id()
 {
     var userId = new Random().Next(1, 1000);

     var userRepository = new StubIDataEntityRepository<User>
     {
         CreateT0 = x =>
             {
                 return userId;
             }
     };

     var user = new User();

     var result = userRepository.CreateT0(user);

     Assert.AreEqual(result, userId);
 }

Now, I have been studying up on Unit Tests and I understand that a pure unit test must not cross any boundaries or responsibilities, hence the Stub. I understand that if I want to test that the creation of a user in my database really does turn a valid user Id, I need to create an integration test. So what, exactly, am I testing here? I know people say application logic and that's all very valid but surely I am creating a test that creates an id, tells the fake repository to return that Id from its Create method and then confirming that the Id returned from the Create method is the same value. It feels like I'm doing a whole lot of work for what is essentially the following:

x = 1, y = 1, assert.areequal(x,y)!!

Is the answer really about training the developer to design their code via TDD? If any of you TDD gurus out there can enlighten me, it would be much appreciated!

Kind Regards

Ben

like image 968
Benjamin Jones Avatar asked Jan 07 '13 15:01

Benjamin Jones


1 Answers

You are not testing anything useful here.

Every unit test has a so-called System Under Test (SUT). That's the class you want to test.
To test the SUT, you must not mock it, because you would than test the mock, not the SUT. And that is kinda pointless.

In your case, it looks like you want to test the repository, but you are also mocking the repository, making the test pointless.

You want to use a mocked repository in tests where the SUT is another class that uses the repository.

Testing the repository is most likely a task for an integration test. Repository methods that directly access the database can't be tested with a unit test.

like image 104
Daniel Hilgarth Avatar answered Oct 20 '22 00:10

Daniel Hilgarth