开发者

How many assert do you put in a test?

开发者 https://www.devze.com 2023-03-22 01:44 出处:网络
I am of the Idea that a test should only have one assert.However at times is difficult to decide if i need to be strict 开发者_如何学编程about it or depends.

I am of the Idea that a test should only have one assert.However at times is difficult to decide if i need to be strict 开发者_如何学编程about it or depends.

Lets take an example I have a customer with address. The Address Class has City-Street-PostCode-Country etc... properties

I would like to test if when Creating a customer the address gets populated.

Shall I create one test per property or many asserts

Assert.That(customer.Address.City,Is.EqualTo("London"));
Assert.That(customer.Address.Street, Is.EqualTo("StreetOne"));
Assert.That(customer.Address.Postcode, Is.EqualTo("MyPostCode"));

What do you normally do when testing a method and is important that you know that properties have been filled as they are going to a third party ?

thanks for any suggestions


I would say, it depends. In your case I don't really see a problem with it as your are basically testing a single piece of functionality (creating a customer). Even NUnit has a shortcut for this type of thing via the TestCase attribute.


In that case you can get away with many Asserts, one big reason being if one fails in a test your test will fail but you will also know which Assert failed. It depends on the testing granularity you want to have. If you want to test the code that maybe fills in that object with info from a database you might want to have multiple asserts. If a major part of your code is getting the address through some other means then maybe you want to test the address section separately. It all really depends on the situation. Usually you want to see where the majority of your logic is and what needs to be tested.


The most important thing with testing is that there is testing. Any test is better than no test. If some fancy rules dictate you the exact way how to do it nifty, what's its worth if it annoys you so much that you soon don't write [real] anymore?


I'm also having idea "One test" -> "One assert".. but!

If the asserts are related to the same Test case, there are no issue to put more. Like your example above, I don't see if you just check the Full address line in one case with 3 asserts;

0

精彩评论

暂无评论...
验证码 换一张
取 消