c# - Write a test method to determine, if code have risk of getting null reference exception -
i trying write generic test method in c#, tell me if, target method have risk of getting null reference exception.
i want run method against functions in class , determine methods have risk of getting null reference exception.
something below,
[testmethod] public void testreferencevulnarability() { try { myclass _myclass = new myclass(); //do target = _myclass.dosomething(); } catch (nullreferenceexception ex) { throw ex; } } public class myclass { public void dosomething() { // here } }
the manual process use determine if code have vulnerability of null refrence exeption. want automate this.
while writing code, @ objects if, there risk of getting null reference exception. if so, add null checks cover risk. however, in runtime, still null refrence exeption, manual checking overlooked risk.
how can write test method/functionality, automate process, , tell me if function have risk of getting null reference exception.
i recommend restructure test. in unit testing, try , catches not needed much, exception raise failure. if handle exception, risk suppressing failing tests.
[testmethod] public void testreferencevulnarability() { myclass _myclass = new myclass(); //do assert.notnull(myclass.dosomething); } public class myclass { public void dosomething() { // here } }
from tests point of view, can exercise code paths within method being targeted based on inputs method. should target common areas of failure, think edge cases etc. @ requirements.
at moment, 'dosomething' method accepts no arguments, reduces ability test it.
if method required accept numbers between 100 , 500, first test values work, add more tests verify negative scenarios. when comes unit testing, there no such thing 'too many tests', long keep unit tests clean , concise.
[testmethod] public void testreferencefor100() { //eg: if invalid number returns null, test valid numbers myclass class = new myclass(); assert.notnull(class.dosomething(100)); } [testmethod] public void testreferencefor500() { //eg: if invalid number returns null, test valid numbers myclass class = new myclass(); assert.notnull(class.dosomething(500)); } [testmethod] public void testreferencefor99() { //eg: test negative edge cases myclass class = new myclass(); assert.isnull(class.dosomething(99)); } [testmethod] public void testreferencefor501() { //eg: test negative edge cases myclass class = new myclass(); assert.isnull(class.dosomething(501)); } public class myclass { public void dosomething(int i) { // here } }
so bringing original question. in order test potential of getting null reference method, need give test ability provide new inputs method. need create test each possible input can provide method. if have access reflector (.net vs extension), can identify @ code time, if code has potential null reference (it highlight , offer fix you.)
Comments
Post a Comment