Often, the interviewers write to me that in the test tasks I do not do validation.
Previously for me, the concept of юнит-тестирование , валидация , try...catch somehow was the same. And only in the last year I have “mastered” unit testing and now I can’t present my code without tests and encode it via TDD (without fanaticism).
try ... catch for me is also a little dark forest, namely: I did not understand exactly when to use it.
But today I want you to help me deal with validation.
Right now I am writing code, implementing the factory method pattern, where a TResultDTO object is created to transfer its AngularJS to View. The TResultDTO object is formed based on the EF-entity TestResult. And I'm trying to organize a validation:
public TResultDTO FactoryMethod(TestResult entity) { //Валидация if(entity != null) { var dto = new TResultDTO { ExamCode = entity.TestPlan.Test.NumberCode, ExamName = entity.TestPlan.Test.Name, ExamDate = entity.TestDate.ToShortDateString(), ParticipCode = entity.ParticipCode }; return dto; } } Question
- Well first VS now writes:
and what should I do about it? I see no way out, except that at the end of the method specify return null . Well then, in general, something incomprehensible comes out.
- Is it enough to check the
entityfor null? Or, ideally, you should check its properties (entity.TestPlan.Test.NumberCode,entity.TestPlan.Test.Name...), directly to the values that the method refers to?
I also understand that there are no ready-made formulas for the fish and a lot (maybe) will depend on the subject area. The only thing that I could find on this account in the network: a colleague on the forum writes that the incoming parameters of public methods must necessarily be subjected to the validation process.
Update
Having listened to the answers and comments, I do validation as follows:
namespace Monit95App.Models { public class TResultDTOcreator : ITResultDTOcreator { public TResultDTO FactoryMethod(TestResult entity) { if (String.IsNullOrEmpty(entity.TestPlan.Test.NumberCode)) throw new ArgumentException("Property cannot be null or empty", nameof(entity.TestPlan.Test.NumberCode)); if (String.IsNullOrEmpty(entity.TestPlan.Test.Name)) throw new ArgumentException("Property cannot be null or empty", nameof(entity.TestPlan.Test.Name)); if (entity.TestPlan.TestDate == null || entity.TestPlan.TestDate == DateTime.MinValue) throw new ArgumentException("Property cannot be null or empty", nameof(entity.TestPlan.TestDate)); if (String.IsNullOrEmpty(entity.ParticipCode)) throw new ArgumentException("Property cannot be null or empty", nameof(entity.ParticipCode)); var dto = new TResultDTO { ExamCode = entity.TestPlan.Test.NumberCode, ExamName = entity.TestPlan.Test.Name, ExamDate = entity.TestDate.ToShortDateString(), ParticipCode = entity.ParticipCode }; return dto; } } } What can colleagues say now?
Previously forgot to note that the project uses the database first approach .
