A fake view and a driver
The image this course is built in has no xUnit, NUnit or MSTest: a test package is a NuGet download, and the container has no network. That is not a limitation of the lesson, because a test of a presenter needs no framework. A fake view is a class of twenty lines, a check is an if, and the result is the exit status of the program. This lesson writes both and runs them.
The fake view
A fake view implements the same interface the form implements, and it does the two things a test needs: it lets the driver set the values a user would type, and it records the values the presenter writes.
internal sealed class FakeView : ILoginView
{
public string UserName { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
public string ErrorText { get; set; } = string.Empty;
public string Greeting { get; set; } = string.Empty;
public void ResetFields()
{
UserName = string.Empty;
Password = string.Empty;
}
public void Submit() => SignInRequested?.Invoke(this, EventArgs.Empty);
public void Clear() => ClearRequested?.Invoke(this, EventArgs.Empty);
public event EventHandler? SignInRequested;
public event EventHandler? ClearRequested;
}
The two extra methods, Submit and Clear, are the fake's way of pressing a button: a form raises the events from its Click handlers, and the fake raises them from a method the driver calls. The properties are settable here, unlike the read-only ones in the interface, because the driver plays the user.
The driver
The driver owns the checks. Equal takes a name, the expected string and a function that produces the actual one, so a failure names the check and shows both values. Finish prints the summary and returns the number of failures, which the program returns from Main:
internal sealed class Driver
{
private int _checks;
private int _failed;
public void Equal(string name, string expected, Func<string> actual)
{
_checks++;
var value = actual();
if (value == expected)
{
Console.WriteLine($"pass: {name}");
return;
}
_failed++;
Console.WriteLine($"fail: {name}: expected '{expected}', got '{value}'");
}
public int Finish()
{
Console.WriteLine($"{_checks} checks, {_failed} failed");
return _failed;
}
}
The Func<string> parameter is what makes one method serve every check: the driver passes a lambda that reads the fake, and Equal never needs to know where the string came from. A failed check does not stop the driver: the checks after it still run, which is what makes one run report every problem.
A driver that passes
The whole program, with the interface, the presenter, the fake and five checks, built and run in the container:
using System;
Console.WriteLine("login presenter driver");
var driver = new Driver();
var auth = new DemoAuth();
var empty = new FakeView();
var first = new LoginPresenter(empty, auth);
empty.Submit();
driver.Equal("empty fields are rejected", "Both fields are required.", () => empty.ErrorText);
var wrong = new FakeView { UserName = "ada", Password = "guess" };
var second = new LoginPresenter(wrong, auth);
wrong.Submit();
driver.Equal("a wrong password is reported", "Wrong user name or password.", () => wrong.ErrorText);
var good = new FakeView { UserName = "ada", Password = "secret" };
var third = new LoginPresenter(good, auth);
good.Submit();
driver.Equal("a good sign-in clears the error", string.Empty, () => good.ErrorText);
driver.Equal("a good sign-in greets the user", "Welcome, ada.", () => good.Greeting);
good.Clear();
driver.Equal("clear empties the fields", string.Empty, () => good.UserName);
return driver.Finish();
internal sealed class Driver
{
private int _checks;
private int _failed;
public void Equal(string name, string expected, Func<string> actual)
{
_checks++;
var value = actual();
if (value == expected)
{
Console.WriteLine($"pass: {name}");
return;
}
_failed++;
Console.WriteLine($"fail: {name}: expected '{expected}', got '{value}'");
}
public int Finish()
{
Console.WriteLine($"{_checks} checks, {_failed} failed");
return _failed;
}
}
internal interface ILoginView
{
string UserName { get; }
string Password { get; }
string ErrorText { set; }
string Greeting { set; }
void ResetFields();
event EventHandler? SignInRequested;
event EventHandler? ClearRequested;
}
internal interface IAuthService
{
bool SignIn(string user, string password);
}
internal sealed class DemoAuth : IAuthService
{
public bool SignIn(string user, string password) =>
user == "ada" && password == "secret";
}
internal sealed class LoginPresenter
{
private readonly ILoginView _view;
private readonly IAuthService _auth;
public LoginPresenter(ILoginView view, IAuthService auth)
{
_view = view;
_auth = auth;
view.SignInRequested += OnSignIn;
view.ClearRequested += OnClear;
}
private void OnSignIn(object? sender, EventArgs e)
{
if (_view.UserName.Length == 0 || _view.Password.Length == 0)
{
_view.ErrorText = "Both fields are required.";
return;
}
if (!_auth.SignIn(_view.UserName, _view.Password))
{
_view.ErrorText = "Wrong user name or password.";
return;
}
_view.ErrorText = string.Empty;
_view.Greeting = $"Welcome, {_view.UserName}.";
}
private void OnClear(object? sender, EventArgs e)
{
_view.ErrorText = string.Empty;
_view.Greeting = string.Empty;
_view.ResetFields();
}
}
internal sealed class FakeView : ILoginView
{
public string UserName { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
public string ErrorText { get; set; } = string.Empty;
public string Greeting { get; set; } = string.Empty;
public void ResetFields()
{
UserName = string.Empty;
Password = string.Empty;
}
public void Submit() => SignInRequested?.Invoke(this, EventArgs.Empty);
public void Clear() => ClearRequested?.Invoke(this, EventArgs.Empty);
public event EventHandler? SignInRequested;
public event EventHandler? ClearRequested;
}
dotnet run
login presenter driver
pass: empty fields are rejected
pass: a wrong password is reported
pass: a good sign-in clears the error
pass: a good sign-in greets the user
pass: clear empties the fields
5 checks, 0 failed
The output is the real run. Every pass line is a branch of the presenter that executed with no form, no message loop and no display. The program returns 0, which is the status a build server reads as success.
A driver that fails
A test that cannot fail proves nothing, so here is a presenter with the empty-field check missing, driven by a single check. It is the same shape as LoginPresenter and the same fake view:
using System;
Console.WriteLine("a presenter without the empty-field rule");
var view = new FakeView { UserName = "ada", Password = "guess" };
var presenter = new SloppyPresenter(view, new DemoAuth());
view.Submit();
var checks = 1;
var failed = 0;
if (view.ErrorText == "Both fields are required.")
{
Console.WriteLine("pass: empty fields are rejected");
}
else
{
failed++;
Console.WriteLine($"fail: empty fields are rejected: expected 'Both fields are required.', got '{view.ErrorText}'");
}
Console.WriteLine($"{checks} checks, {failed} failed");
return failed;
internal interface ILoginView
{
string UserName { get; }
string Password { get; }
string ErrorText { set; }
event EventHandler? SignInRequested;
}
internal interface IAuthService
{
bool SignIn(string user, string password);
}
internal sealed class DemoAuth : IAuthService
{
public bool SignIn(string user, string password) =>
user == "ada" && password == "secret";
}
internal sealed class SloppyPresenter
{
private readonly ILoginView _view;
private readonly IAuthService _auth;
public SloppyPresenter(ILoginView view, IAuthService auth)
{
_view = view;
_auth = auth;
view.SignInRequested += OnSignIn;
}
private void OnSignIn(object? sender, EventArgs e)
{
if (!_auth.SignIn(_view.UserName, _view.Password))
{
_view.ErrorText = "Wrong user name or password.";
return;
}
_view.ErrorText = string.Empty;
}
}
internal sealed class FakeView : ILoginView
{
public string UserName { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
public string ErrorText { get; set; } = string.Empty;
public void Submit() => SignInRequested?.Invoke(this, EventArgs.Empty);
public event EventHandler? SignInRequested;
}
dotnet run
a presenter without the empty-field rule
fail: empty fields are rejected: expected 'Both fields are required.', got 'Wrong user name or password.'
1 checks, 1 failed
The output is the real run, and it exits with status 1. The check expected the message of the empty-field rule and got the message of the authentication. That is the value of a driver as opposed to a printout: the failure is a line with both values and a status a script can test.
An exit status as the result
The program returns the number of failures from its top-level return, and the runtime turns that into the process exit status: 0 when every check passed, 1 or more when something failed. A build step is then one line, and it needs no test runner:
dotnet run --project tests/Notes.Tests && echo 'the core is sound'
A few rules make such a driver maintainable. One fake per test, so a leftover message cannot pass a later check. Every check compares a string or a number, because an assertion on an object prints nothing useful. The driver prints the failing check with both values, which this one does. And the checks run in a fixed order with no shared state, so a failure tells the whole story.
On a machine with network access the same code runs under xUnit or NUnit: the framework adds discovery, reporting and running tests in parallel, and the driver stays a plain method a test can call. The pattern is the same and the fake view is the same.
Exercises
- Add a check that clears the fields and then signs in, and explain which presenter branch the check reaches.
- Break the presenter on purpose, run the driver and confirm the exit status with the shell.
- Add a True(string name, bool value) check to the driver and use it for a condition that is not a string comparison.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is a fake view?
Answer
A class that implements the view interface and records what the presenter writes
It implements the same interface, so the presenter cannot tell it from the form.
-
How does the fake view simulate a button press?
Answer
It raises the same event the form raises
Submit raises SignInRequested, exactly as the form's Click handler does.
-
What does the Driver.Equal signature take for the actual value?
Answer
A Func of string, so the check can read any source
The lambda defers the read and keeps one method for every check.
-
What does the passing driver return?
Answer
The number of failures, which is 0
Finish returns _failed, so the exit status is 0 when all checks pass.
-
What did the failing run print for the check?
Answer
expected 'Both fields are required.', got 'Wrong user name or password.'
The presenter without the rule reported the authentication failure.
-
What exit status does the failing driver produce?
Answer
1
The top-level return becomes the process exit status, and one check failed.
-
Why is one new fake view created per check?
Answer
So a message left by an earlier check cannot make a later one pass
Shared state between checks hides failures.
-
Which test framework does the image provide?
Answer
None: xUnit, NUnit and MSTest all need a package download
The driver exists because the container has no test package and no network.
-
What does the driver print when a check fails?
Answer
The check name, the expected value and the actual value
Both values are what makes the line actionable.
-
Why does the driver keep the checks in a fixed order with no shared state?
Answer
So a failure reports the whole story without interference
A test run whose result depends on the previous test is not a test.
Every listing on this page is plain .NET code with no window in it: it was built and run with the .NET SDK 10.0.303 on Alpine Linux 3.24.3 (x86_64) in a Docker container, and the output printed below each program is that run. The WinForms pages of this course are built for net10.0-windows against Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed and never run on Linux: WinForms needs Windows.
Article author: Arthur Isaev