Home > Articles > Programming > C#

  • Print
  • + Share This
This chapter is from the book

Building a Window

Designing the Add Employee window GUI code was a breeze. With Visual Studio's designer, it's simply a matter of dragging some controls around to the right place. This code is generated for us and is not included in the following listings. Once the window is designed, we have more work to do. We need to implement some behavior in the UI and wire it to the presenter. We also need a test for it all. Listing 38-5 shows AddEmployeeWindowTest, and Listing 38-6 shows AddEmployeeWindow.

Listing 38-5. AddEmployeeWindowTest.cs

using NUnit.Framework;

namespace PayrollUI
{
  [TestFixture]
  public class AddEmployeeWindowTest
  {
    private AddEmployeeWindow window;
    private AddEmployeePresenter presenter;
    private TransactionContainer transactionContainer;

    [SetUp]
    public void SetUp()
    {
      window = new AddEmployeeWindow();
      transactionContainer = new TransactionContainer(null);
      presenter = new AddEmployeePresenter(
        window, transactionContainer, null);

      window.Presenter = presenter;
      window.Show();
    }

    [Test]
    public void StartingState()
    {
      Assert.AreSame(presenter, window.Presenter);
      Assert.IsFalse(window.submitButton.Enabled);
      Assert.IsFalse(window.hourlyRateTextBox.Enabled);
      Assert.IsFalse(window.salaryTextBox.Enabled);
      Assert.IsFalse(window.commissionSalaryTextBox.Enabled);
      Assert.IsFalse(window.commissionTextBox.Enabled);
    }

    [Test]
    public void PresenterValuesAreSet()
    {
      window.empIdTextBox.Text = "123";
      Assert.AreEqual(123, presenter.EmpId);

      window.nameTextBox.Text = "John";
      Assert.AreEqual("John", presenter.Name);

      window.addressTextBox.Text = "321 Somewhere";
      Assert.AreEqual("321 Somewhere", presenter.Address);

      window.hourlyRateTextBox.Text = "123.45";
      Assert.AreEqual(123.45, presenter.HourlyRate, 0.01);

      window.salaryTextBox.Text = "1234";
      Assert.AreEqual(1234, presenter.Salary, 0.01);

      window.commissionSalaryTextBox.Text = "123";
      Assert.AreEqual(123, presenter.CommissionSalary, 0.01);

      window.commissionTextBox.Text = "12.3";
      Assert.AreEqual(12.3, presenter.Commission, 0.01);

      window.hourlyRadioButton.PerformClick();
      Assert.IsTrue(presenter.IsHourly);

      window.salaryRadioButton.PerformClick();
      Assert.IsTrue(presenter.IsSalary);
      Assert.IsFalse(presenter.IsHourly);

      window.commissionRadioButton.PerformClick();
      Assert.IsTrue(presenter.IsCommission);
      Assert.IsFalse(presenter.IsSalary);
    }
    [Test]
    public void EnablingHourlyFields()
    {
      window.hourlyRadioButton.Checked = true;
      Assert.IsTrue(window.hourlyRateTextBox.Enabled);

      window.hourlyRadioButton.Checked = false;
      Assert.IsFalse(window.hourlyRateTextBox.Enabled);
    }

    [Test]
    public void EnablingSalaryFields()
    {
      window.salaryRadioButton.Checked = true;
      Assert.IsTrue(window.salaryTextBox.Enabled);

      window.salaryRadioButton.Checked = false;
      Assert.IsFalse(window.salaryTextBox.Enabled);
    }

    [Test]
    public void EnablingCommissionFields()
    {
      window.commissionRadioButton.Checked = true;
      Assert.IsTrue(window.commissionTextBox.Enabled);
      Assert.IsTrue(window.commissionSalaryTextBox.Enabled);

      window.commissionRadioButton.Checked = false;
      Assert.IsFalse(window.commissionTextBox.Enabled);
      Assert.IsFalse(window.commissionSalaryTextBox.Enabled);
    }

    [Test]
    public void EnablingAddEmployeeButton()
    {
      Assert.IsFalse(window.submitButton.Enabled);

      window.SubmitEnabled = true;
      Assert.IsTrue(window.submitButton.Enabled);

      window.SubmitEnabled = false;
      Assert.IsFalse(window.submitButton.Enabled);
    }

    [Test]
    public void AddEmployee()
    {
      window.empIdTextBox.Text = "123";
      window.nameTextBox.Text = "John";
      window.addressTextBox.Text = "321 Somewhere";
      window.hourlyRadioButton.Checked = true;
      window.hourlyRateTextBox.Text = "123.45";

      window.submitButton.PerformClick();
      Assert.IsFalse(window.Visible);
      Assert.AreEqual(1,
        transactionContainer.Transactions.Count);
    }
  }
}

Listing 38-6. AddEmployeeWindow.cs

using System;
using System.Windows.Forms;

namespace PayrollUI
{
  public class AddEmployeeWindow : Form, AddEmployeeView
  {
    public System.Windows.Forms.TextBox empIdTextBox;
    private System.Windows.Forms.Label empIdLabel;
    private System.Windows.Forms.Label nameLabel;
    public System.Windows.Forms.TextBox nameTextBox;
    private System.Windows.Forms.Label addressLabel;
    public System.Windows.Forms.TextBox addressTextBox;
    public System.Windows.Forms.RadioButton hourlyRadioButton;
    public System.Windows.Forms.RadioButton salaryRadioButton;
    public System.Windows.Forms.RadioButton commissionRadioButton;
    private System.Windows.Forms.Label hourlyRateLabel;
    public System.Windows.Forms.TextBox hourlyRateTextBox;
    private System.Windows.Forms.Label salaryLabel;
    public System.Windows.Forms.TextBox salaryTextBox;
    private System.Windows.Forms.Label commissionSalaryLabel;
    public System.Windows.Forms.TextBox commissionSalaryTextBox;
    private System.Windows.Forms.Label commissionLabel;
    public System.Windows.Forms.TextBox commissionTextBox;
    private System.Windows.Forms.TextBox textBox2;
    private System.Windows.Forms.Label label1;
    private System.ComponentModel.Container components = null;
    public System.Windows.Forms.Button submitButton;
    private AddEmployeePresenter presenter;

    public AddEmployeeWindow()
    {
      InitializeComponent();
    }

    protected override void Dispose( bool disposing )
    {
      if( disposing )
      {
        if(components != null)
        {
          components.Dispose();
        }
      }
      base.Dispose( disposing );

    }

    #region Windows Form Designer generated code
    // snip
    #endregion

    public AddEmployeePresenter Presenter
    {
      get { return presenter; }
      set { presenter = value; }
    }

    private void hourlyRadioButton_CheckedChanged(
      object sender, System.EventArgs e)
    {
      hourlyRateTextBox.Enabled = hourlyRadioButton.Checked;
      presenter.IsHourly = hourlyRadioButton.Checked;
    }

    private void salaryRadioButton_CheckedChanged(
      object sender, System.EventArgs e)
    {
      salaryTextBox.Enabled = salaryRadioButton.Checked;
      presenter.IsSalary = salaryRadioButton.Checked;
    }

    private void commissionRadioButton_CheckedChanged(
      object sender, System.EventArgs e)
    {
      commissionSalaryTextBox.Enabled =
        commissionRadioButton.Checked;
      commissionTextBox.Enabled =
        commissionRadioButton.Checked;
      presenter.IsCommission =
        commissionRadioButton.Checked;
    }

    private void empIdTextBox_TextChanged(
      object sender, System.EventArgs e)
    {
      presenter.EmpId = AsInt(empIdTextBox.Text);
    }

    private void nameTextBox_TextChanged(
      object sender, System.EventArgs e)
    {
      presenter.Name = nameTextBox.Text;
    }

    private void addressTextBox_TextChanged(
      object sender, System.EventArgs e)
    {
      presenter.Address = addressTextBox.Text;
    }

    private void hourlyRateTextBox_TextChanged(
      object sender, System.EventArgs e)
    {
      presenter.HourlyRate = AsDouble(hourlyRateTextBox.Text);
    }

    private void salaryTextBox_TextChanged(
      object sender, System.EventArgs e)
    {
      presenter.Salary = AsDouble(salaryTextBox.Text);
    }

    private void commissionSalaryTextBox_TextChanged(
      object sender, System.EventArgs e)
    {
      presenter.CommissionSalary =
        AsDouble(commissionSalaryTextBox.Text);
    }

    private void commissionTextBox_TextChanged(
      object sender, System.EventArgs e)
    {
      presenter.Commission = AsDouble(commissionTextBox.Text);
    }

    private void addEmployeeButton_Click(
      object sender, System.EventArgs e)
    {
      presenter.AddEmployee();
      this.Close();
    }

    private double AsDouble(string text)
    {
      try
      {
        return Double.Parse(text);
      }
      catch (Exception)
      {
        return 0.0;
      }
    }

    private int AsInt(string text)
    {
      try
      {
        return Int32.Parse(text);
      }
      catch (Exception)
      {
        return 0;
      }
    }

    public bool SubmitEnabled
    {
      set { submitButton.Enabled = value; }
    }
  }
}

Despite all my griping about how painful it is to test GUI code, testing Windows Form code is relatively easy. There are some pitfalls, however. For some silly reason, known only to programmers at Microsoft, half of the functionality of the controls does not work unless they are displayed on the screen. It is for this reason that you'll find the call window.Show() in the SetUp of the test fixture. When the tests are executed, you can see the window appearing and quickly disappearing for each test. This is annoying but bearable. Anything that slows down the tests or otherwise makes them clumsy makes it more likely that the tests will not be run.

Another limitation is that you cannot easily invoke all the events on a control. With buttons and buttonlike controls, you can call PerformClick, but events such as MouseOver, Leave, Validate, and others are not so easy. An extension for NUnit, called NUnitForms, can help with these problems and more. Our tests are simple enough to get by without extra help.

In the SetUp of our test, we create an instance of AddEmployeeWindow and give it an instance of AddEmployeePresenter. Then in the first test, StartingState, we make sure that several controls are disabled: hourlyRateTextBox, salaryTextBox, commissionSalaryTextBox, and commissionTextBox. Only one or two of these fields are needed, and we don't know which ones until the user chooses the payment type. To avoid confusing the user by leaving all the fields enabled, they'll remain disabled until needed. The rules for enabling these controls are specified in three tests: EnablingHourlyFields, EnablingSalaryField, and EnablingCommissionFields. EnablingHourlyFields, for example, demonstrates how the hourlyRateTextBox is enabled when the hourlyRadioButton is turned on and disabled when the radio button is turned off. This is achieved by registering an EventHandler with each RadioButton. Each EventHandler enables and disables the appropriate text boxes.

The test, PresenterValuesAreSet, is an important one. The presenter know what to do with the data, but it's the view's responsibility to populate the data. Therefore, whenever a field in the view is changed, it calls the corresponding property on the presenter. For each TextBox in the form, we use the Text property to change the value and then check to make sure that the presenter is properly updated. In AddEmployeeWindow, each TextBox has an EventHandler registered on the TextChanged event. For the RadioButton controls, we call the PerformClick method in the test and again make sure that the presenter is informed. The RadioButton's EventHandlers take care of this.

EnablingAddEmployeeButton specifies how the submitButton is enabled when the SubmitEnabled property is set to true, and reverse. Remember that in AddEmployeePresenterTest, we didn't care what this property did. Now we do care. The view must respond properly when the SubmitEnabled property is changed; however, AddEmployeePresenterTest was not the right place to test it. AddEmployee-WindowTest focuses on the behavior of the AddEmployeeWindow, and it is the right place to test this unit of code.

The final test here is AddEmployee, which fills in a valid set of fields, clicks the Submit button, asserts that the window is no longer visible, and makes sure that a transaction was added to the transactionContainer. To make this pass, we register an EventHandler, on the submitButton, that calls AddEmployee on the presenter and then closes the window. If you think about it, the test is doing a lot of work just to make sure that the AddEmployee method was called. It has to populate all the fields and then check the transactionContainer. Some might argue that instead, we should use a mock presenter so we can easily check that the method was called. To be honest, I wouldn't put up a fight if my pair partner were to bring it up. But the current implementation doesn't bother me too much. It's healthy to include a few high-level tests like this. They help to make sure that the pieces can be integrated properly and that the system works the way it should when put together. Normally, we'd have a suite of acceptance tests that do this at an even higher level, but it doesn't hurt to do it a bit in the unit tests—just a bit, though.

With this code in place, we now have a working form for creating AddEmployeeTransactions. But it won't get used until we have the main Payroll window working and wired up to load our AddEmployeeWindow.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020