Given the code below:
public class Employee
{
public void CalculateEmpSal(int empId,int salary)
{
// local varibles
int Basic;
int HRA;
// Calculate employee salary
Basic = salry * (0.40);
HRA = Basic * (0.50);
}
}
Is it possible to write a unit test for the CalculateEmpSal
method that can access the Basic
and HRA
local variables? I couldn't access these variables using reflection. Is there another way to access them from my unit tests?
You can't... and you shouldn't want to.
You should be testing the side effects / state changes caused by your methods, not the low level implementation details. As it stands, your method has no side effects, so there's nothing to test.
If you change it to return something useful (possibly HRA
), then you'd have something to test outside the method.
public int CalculateEmpSal(int empId,int salary)
{
// local varibles
int Basic;
int HRA;
// Calculate employee salary
Basic = salry * (0.40);
HRA = Basic * (0.50);
return HRA;
}
If you're just trying to inspect the values, then you should step through the code with your debugger..
As an aside, you're using floating point numbers, with integers... are you sure you want to do that?
In your class you are setting the values of the variables which are then disposed of without being used. Given this fact what difference does it make if the values are wrong? You are not using them for anything anyway. Given the example you have I can replace it with this and the result is exactly the same:
public class Employee
{
public void CalculateEmpSal(int empId,int salary)
{
}
}
Tests are about testing side effects and/or interactions. your method has no side effects or interactions and so is effectively an inefficient noop method and cannot be tested.
You must be doing something other than what you have shown in the example for you to know what the salary you have calculated is. That result is what you should be testing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With