Saturday, July 24, 2010

FakeItEasy Login Service Example Series – Part 7

This is the seventh and last part in the series of posts where I’m porting Brett Schucherts excelent demo of Mockito in Java to C# and FakeItEasy.

The source for this example series can be found in a Mercurial repository at Google code. Each test implementation and following code update is a separate commit so you can easily update your repository to look at the full code at any given state. Find the repository here.

Part 1 can be found here.

Part 2 can be found here.

Part 3 can be found here.

Part 4 can be found here.

Part 5 can be found here.

Part 6 can be found here.

Test 7 – Should not be able to log in to revoked account

The next test is similar to the previous test. A revoked account does not allow logins:

The test

[Test]
public void Should_throw_when_account_has_been_revoked()
{
    // Arrange
    A.CallTo(() => this.account.IsRevoked).Returns(true);

    // Act, Assert
    Assert.Throws<AccountRevokedException>(() =>
        this.service.Login("username", "password"));
}

 

Test Description

This test is a repeat of the previous test, checking for a different result from a different starting condition.

Things Created for Compilation

You'll need to add another exception, AccountRevokedException  and a new property, IsRevoked, to IAccount.

Code Updated to get Test to turn Green

The only update to get to green is adding a check - a guard clause - similar to the previous test:

public void Login(string username, string password)
{
    var account = this.accountRepository.Find(username);

    if (account == null)
    {
        throw new AccountNotFoundException();
    }

    if (account.IsRevoked)
    {
        throw new AccountRevokedException();
    }

    if (account.IsLoggedIn)
    {
        throw new AccountLoginLimitReachedException();
    }

    if (account.PasswordMatches(password))
    {
        account.SetLoggedIn(true);
    }
    else
    {
        if (this.previousUsername.Equals(username))
        {
            this.numberOfFailedAttempts++;
        }
        else
        {
            this.numberOfFailedAttempts = 1;
            this.previousUsername = username;
        }
    }

    if (this.numberOfFailedAttempts == 3)
    {
        account.SetRevoked(true);
    }
}

Summary

This has been a port of Brett’s original tutorial, his tutorial does not end here though no more tests are added. Please continue reading his tutorial.

1 comment:

  1. Tack för FakeItEasy, det har hjälpt mig mycket i mina små försök att förstå TDD! /Johan

    ReplyDelete