I am unit testing a method say ABC() like
myclass target = new myclass();
target.ABC();
This ABC() method in turn calls another method XYZ() from a different class like anotherclass.XYZ() and this XYZ() method’s input parameter depends on values from textbox (s).
Since, at test run there is no values from textbox passed I am getting a null referrence exception while running the test (I mean test fails with exception).
Similar situation (another): method fetches id value from querystring like
HttpContext context
id = context.request.querystring["id"]
Since, at test run this id values is null I get a null referrence exception(I mean test fails with exception).
To my understanding, logically this is correct since this is test run and not actual run but still want to confirm once …
Am I doing anything wrong?
OR
My test is functioning correct?
Please suggest. Appreciate your help.
Thanks.
I have no idea what your code looks like but it probably needs to be refactored a little bit to allow unit testing.
For instance, if you have code like this:
You would want to change it to something like this:
You can then use a mocking framework to mock up the IAnotherClass as IceN has show. As for the HttpContext – that becomes a little more complicated, but if it’s only used by the AnotherClass you wont need to mock it since the mock object will just return whatever you like. Obviously when you come to test AnotehrClass it becomes an issue. If you find you do need to mock it then there are a number of examples of what to do – for instance this one.