Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing Legacy C# Code

How to write a NUnit test for a method like this. Does this method itself warrant refactoring? What is the best approach to deal with scenarios like this in leagacy code?

         public bool DoXYZ()
            {
                ABC abc= new ABC()
                XYZ xyz = new XYZ();
                if (xyz .IsSomeCondition(Session.SessionID))
                { return false; }
                else
                { return abc.IsSomeOtherCondition(SessionID.SessionID); }
            }
like image 939
GilliVilla Avatar asked Oct 17 '25 14:10

GilliVilla


2 Answers

You will probably need to refactor it to introduce hooks for dependency injection. For example, the class that contains the DoXYZ method can get new properties for ABC and XYZ. These properties could default to instances of ABC and XYZ, but in the unit tests could be replaced by mock versions.

And if you prefer to use IoC, this approach supports that as well

like image 82
Joel Martinez Avatar answered Oct 20 '25 03:10

Joel Martinez


I would definitely refactor to inject the session id via a parameter - otherwise you'll have to create the session manually.

Can it be made static? Looks like it, particularly if you inject sessionid.

Also, you're implementing a (short) command dispatcher, which is generally considered an anti-pattern, compared to IoC (see Joel Martinez' answer above).

like image 41
Chris B. Behrens Avatar answered Oct 20 '25 04:10

Chris B. Behrens