DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Stojan Anastasov
Stojan Anastasov

Posted on

What is a Unit in unit testing

What is a unit in unit testing? Is it a class, a function, a method, all of the above?

Is it considered a unit test if we are testing a class without mocking all of the collaborators?

Top comments (5)

Collapse
 
vlasales profile image
Vlastimil Pospichal
  1. All
  2. No
Collapse
 
s_anastasov profile image
Stojan Anastasov

I agree on point 1.

Can you elaborate on point 2?

Collapse
 
vlasales profile image
Vlastimil Pospichal

You must isolate dependencies.

When test failed, where is the error? This is in the unit or in the dependency? When you use a mock, you will know where it is.

You may use more mocks for more test scenarios too.

Collapse
 
quii profile image
Chris James • Edited on

I like to think of "units" as lego bricks. We like to create useful lego bricks that we can stick together to create systems.

These lego bricks could be a single class/function with a few lines of code but it might have a bunch of private stuff inside and maybe creates instances of other classes to do its job.

Unit test the boundaries of your lego bricks.

For me the acid test with unit tests is i ask myself if something is clearly implementation detail. If it is, you're testing too low level, move up the abstraction tree a bit.

If you're testing something that expresses an important business rule, that's probably a good unit test.

In respect to TDD a lot of people make a mistake in thinking that you must write a new test for each new class/function you write. That was never the intention. You write a new test for each new captured behaviour. If you stick to this rule your unit tests will document and verify real things... or units (e.g when I deposit Β£10 into an empty account the balance should be Β£10)

I speak about this here youtube.com/watch?v=Kwtit8ZEK7U (or you can read here quii.dev/The_Tests_Talk)

Collapse
 
peter279k profile image
peter279k • Edited on

I think it's all. The unit is possible to be a function, a class or a method.

Here is a post you might want to check out:

Regex for lazy developers

regex for lazy devs

Sorry for the callout πŸ˜†