Thursday 15 July 2010

c# - How to write testmethods for methods without parameters? -



c# - How to write testmethods for methods without parameters? -

i'm trying understand tdd examples i've seen, shows methods add(), substract() etc. understand how test through unittest. how test method without parameters?

how you, example, write testmethod method?

public list<string> testmethod() { list<string> ret = new list<string>(); using (sqlconnection conn = new sqlconnection(constring)) using (sqlcommand cmd = conn.createcommand()) { sqldatareader reader; cmd.commandtext = "select * users"; conn.open(); reader = cmd.executereader(); while (reader.read()) { ret.add(reader["name"].tostring()); } conn.close(); } homecoming ret; }

i mean, have test against?

technically wouldn't unit test method. since code coupled database integration test. (if want test logic separately info access you'd break 2 components, 1 logic , 1 info access.)

aside little nitpick though, pattern same. repeatable automated test should have 3 steps:

arrange act assert

assuming "act" step this:

var result = testmethod();

what, then, "assert" step? how can know method did it's supposed do? returns result, imagine you'd examine result see if it's expect given known conditions.

what conditions? that's "arrange" step. thought set known scenario expect known result. execute code. check if result expect.

for example, instead of illustration of add(1, 1) know how test, consider object:

public class adder { public int augend { get; set; } public int addend { get; set; } public int add() { homecoming augend + addend; } }

(it's silly object know, bear me.)

how test method itself? first setting environment:

// arrange var adder = new adder(); adder.augend = 1; adder.addend = 1; // deed var result = adder.add(); // assert assert.areequal(2, result);

in case "arrange" step might pretty involved, since there's direct access database. concept same. test first creates known state of system, performs action, examines new state of system. (if creation of state , exam of state, side-effects left afterward, bit cumbersome that's indication there's much coupling in code , you'd want break things apart bit.)

c# tdd

No comments:

Post a Comment