[ACCEPTED]-Testing code that executes in a loop-tdd
You're correct about testing the loop in 19 that way. I don't have much context around 18 the functionality your trying to test drive 17 other than "no one logged in", so I'll take 16 some liberties on my suggestions.
Firstly, for 15 the loop testing, you can do it a couple 14 of ways, depending on your preference. the 13 first way is to extract the loop condition 12 into a method that can be overridden in 11 a subclass used for testing.
// In your AtmMachine
public void Start()
{
_shouldContinue = true;
while (stillRunning())
{
// Do some ATM type stuff
}
}
protected virtual bool stillRunning() {
return _shouldContinue;
}
Inside your 10 test you can create a special test class 9 that overrides stillRunning()
.
// Inside your test
[TestMethod]
public void no_one_should_be_logged_in()
{
_atm = new AtmThatImmediatelyShutsDown();
this.SetupForCancelledUser();
_atm.Start();
Assert.IsNull(_atm.CurrentUser);
}
class AtmThatImmediatelyShutsDown : AtmMachine {
protected override bool stillRunning() {
return false;
}
}
Another option is to inject 8 the condition as an class/interface that 7 can be mocked. The choice is yours.
Secondly, for 6 simplicity sake, I would extract the guts 5 of that loop into a method with increased 4 visibility to allow for testing of the code 3 in the loop.
// In your AtmMachine
public void Start()
{
_shouldContinue = true;
while (stillRunning())
{
processCommands();
}
}
public void processCommands() {
...
}
Now, you can directly call the 2 processCommands()
method and skip all of the looping.
Hope 1 that helps!
Brandon
Seems like a place to apply SingleResponsibilityPrinciple.
- A Daemon or Service that wait/loops for a trigger
- SomeClass that services the AtmUser / handles a transaction.
If 3 you split these unrelated responsibilities 2 into 2 roles, it becomes much easier to 1 test both of them.
public void Start()
{
while (_shouldContinue)
{
_output.Clear();
_output.Write(WELCOME_MSG);
if (HasUserLoggedIn)
SomeOtherType.ProcessTransaction();
}
}
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.