c# - How does one unit test modifying an XML document? -
i'm @ loss how begin creating unit tests method:
public override void modifyxmldocument(foo foo, string nodetochange, string newvalue) { xmldocument xmldocument = new xmldocument(); xmldocument.load(foo.xmlpathandfilename); xmlelement rootelement = xmldocument.documentelement; // rest of method (to modify xml doc) here }
that method finds element/node in xml doc , updates user-supplied value. (the method more complex shown here.)
the part i'm having hard time understanding how have method execute, without relying on hard disk. xmldocument.load()
takes file path , loads file disk. @ end of method, saves updated file disk.
how can make method unit testable?
there couple of ways can this, require refactoring of code. modifyxmldocument
need take xmldocument
parameter, can mock there on.
public void test_that_xml_is_loaded() { var sut = new sut(); var xmldocumentfake = new mock<xmldocument>(){callbase=true}; xmldocumentfake.setup(x=>x.loadxml(it.isany<string>())); sut.modifyxmldocument(foo, nodetochange, newvalue, xmldocumentfake.object); xmldocumentfake.verify(x=>x.loadxml(it.isany<string>()), times.once()); }
you wrap xmldocument
in class can write abstraction can modified. again, have pass in, though.
also, anthony pegram had alluded , mean: careful not breaking single responsibility principle. when tests hard write, scream have broken principle.
Comments
Post a Comment