unit testing - Moq object always returns null - why? -
i trying grips moq , using simple example figure out. using google geocode address. have wrapped webclient can mocked. here code:
public class position { public position(double latitude, double longitude) { latitude = latitude; longitude = longitude; } public virtual double latitude { get; private set; } public virtual double longitude { get; private set; } } public interface iwebdownloader { string download(string address); } public class webdownloader : iwebdownloader { public webdownloader() { webproxy wp = new webproxy("proxy", 8080); wp.credentials = new networkcredential("user", "password", "domain"); _webclient = new webclient(); _webclient.proxy = wp; } private webclient _webclient = null; #region iwebdownloader members public string download(string address) { return encoding.ascii.getstring(_webclient.downloaddata(address)); } #endregion } public class geocoder { public position getposition(string address, iwebdownloader downloader) { string url = string.format("http://maps.googleapis.com/maps/api/geocode/xml?address={0}&sensor=false", address); string xml = downloader.download(url); xdocument doc = xdocument.parse(xml); var position = p in doc.descendants("location") select new position( double.parse(p.element("lat").value), double.parse(p.element("lng").value) ); return position.first(); } } all far. here unit test moq:
[testmethod()] public void getpositiontest() { mock<iwebdownloader> mockdownloader = new mock<iwebdownloader>(mockbehavior.strict); const string address = "brisbane, australia"; mockdownloader.setup(w => w.download(address)).returns(resource1.addressxml); iwebdownloader mockobject = mockdownloader.object; geocoder geocoder = new geocoder(); position position = geocoder.getposition(address, mockobject); assert.areequal(position.latitude , -27.3611890); assert.areequal(position.longitude, 152.9831570); } the return value in resource file , xml output google. when run unit test exception:
all invocations on mock must have corresponding setup..
if turn off strict mode, mock object returns null. if change setup to:
mockdownloader.setup(w => w.download(it.isany<string>())).returns(resource1.addressxml); then test runs fine. don't want test string, want test specific address.
please put me out of misery , tell going wrong.
as far can tell, you're having mock return specific value when receives string "brisbane, australia", you're passing value http://maps.googleapis.com/maps/api/geocode/xml?address=brisbane,%20australia&sensor=false (or ends getting formatted).
try in test code:
… const string address = "brisbane, australia"; const string url = string.format("http://maps.googleapis.com/maps/api/geocode/xml?address={0}&sensor=false", address); mockdownloader.setup(w => w.download(url)).returns(resource1.addressxml); …
Comments
Post a Comment