So, I kinda new to this stuff of unit testing so let's say I have this code:
public string GenerateToken(TbMtUser user)
{
JWTSettings jwtSettings = _jwtSettingsProvider.GetJWTSettings();
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor()
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Sid, user.CdUser.ToString()),
new Claim(ClaimTypes.Email, user.DsMail),
new Claim(ClaimTypes.Name, user.DsUserName),
}),
Expires = _dateTimeProvider.GetTime().AddMinutes(15),
SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSettings.JWTKey)),
SecurityAlgorithms.HmacSha256),
Issuer = jwtSettings.Issuer,
Audience = jwtSettings.Audience
};
SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
As you can see, I'm not throwing exceptions at all. However, let's say CdUser is null, a null object can't have a ToString() method, therefore an exception will be thrown.
Same thing happens to DsMail or DsUsername when trying to use it in a Claim, even user itself might be null, right?
My question is:
Should I check all of these cases by myself (e.g. at the beginning of the code) and throw exceptions or should I just let the code execute and delegate that to the other components inside that block of code?
I'm asking this because if - for instance - Claim throws an exception of type ArgumentNullException why would I do something like:
if (String.IsNullOrEmpty(user.DsMail)) throw ArgumentNullException("DsMail can't be null");
Wouldn't it be the same thing? More importantly, Would it be necessary? The only thought I can think of is in order to have absolutely control over what's going on.
I hope it makes sense what I'm trying to explain.
I know this might be something completely ignorant to the most experienced of you, but what do you think? Please, correct me.
Aucun commentaire:
Enregistrer un commentaire