简体   繁体   中英

Unit Test & try catch for method returning a list of objects c#

I have the following method in my WCF service. I need to do a unit test for it, but am unsure how to do this since it returns a list of objects Mountain.

The method takes in a grid reference eg NN - and searches the list mountslist for those mountains with grid reference starting with NN.

Also can anyone help me as to how I can do a try catch for this? I am confused as to what to return since it expects a Mountain object. (If not found return - mountain not in list for example).

public IEnumerable<Mountain> GetMountainLoc(string mtloc)
{    
  IEnumerable<Mountain> resultMts = 
       mountsList
       .Where(x => x.Grid_ref.Substring(0, 2) == mtloc)
       .ToList();
  return resultMts;    
}

In this case your method is simply applying a filter againsts a list of type IEnumerable<Mountain> , held in a variable named mountsList .

So one way to test this, then, is to make assertions against the filtered list returned by the method. However, in order to do this, you need to know the state of the variable mountsList at the time the unit test runs.

So how does this variable get set in the containing class? Is it passed in? Is it constructed by some other means? Whichever, unless you know the state of this list at test time, you will need to supplant or otherwise inject a known representation of this list so that you can make accurate assertions against it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM