Carrot
Carrot

Reputation: 3

Nsubstitute line I don't understand and even if removed still works fine

There is this line that ChatGPT put down when I asked it how to throw an exception with nsubstitute:

var exception = await Assert.ThrowsAsync<NullReferenceException>(() => _controller.Post(categoryNull));

I removed it and it still worked fine if not faster, any clue on how this should work and what was the purpose of it?

Upvotes: -2

Views: 53

Answers (1)

iakobski
iakobski

Reputation: 1274

The point of a unit test is not that the test passes. It also has to fail when the code changes and does something unexpected.

You say it "worked fine" when removed, but really, it didn't. After all, you could remove every single assertion for all your tests and they would all pass. The other half of "worked fine" is that you can change the code and prove that it fails, then make the code correct (without changing the test) and if it passes then, you are good.

Imagine a test like this:

DateTime testDate = MyApp.GetDate();
Assert.That(testDate, Is.Not.Null);

The test passes, that's a good thing, right? Well, no. If you try and make it fail, you can't because DateTimes are value types and can never be null. So your test runs every day but it never fails, because you never proved that it can fail.

Upvotes: 3

Related Questions