c# - How to unittest value depends on MessageBox? -
i use nunit test unit , have method:
class abc { private int a; public void mymethod() { if(messagebox.show("sure?", "title", messageboxbuttons.yesno) == dialogresult.yes) = 1; else = 0; } }
how write nunit test method? sorry english. thank much.
the usual solution mock messagebox
class , simulate show
method returns. since it's static method, requires additional work , modifications in code. here's possible solution:
create class encapsulates show
method:
public class mymessagebox { public virtual dialogresult show(string text, string caption, messageboxbuttons buttons) { return messagebox.show(text, caption, buttons); } }
then modify code use class:
class abc { internal int a; private readonly mymessagebox messagebox; public abc(mymessagebox messagebox) { this.messagebox = messagebox; } public void mymethod() { if (messagebox.show("sure?", "title", messageboxbuttons.yesno) == dialogresult.yes) = 1; else = 0; } }
after that, can write tests mock mymessagebox
class. i'm using nsubstitute in example below:
[test] public void test() { mymessagebox messagebox = substitute.for<mymessagebox>(); messagebox.show("sure?", "title", messageboxbuttons.yesno).returns(dialogresult.yes); abc abc = new abc(messagebox); abc.mymethod(); assert.areequal(1, abc.a); }
that's 1 way it. it's decide if it's worth effort or not.
Comments
Post a Comment