简体   繁体   中英

Better way to check the checkbox value

I wrote a piece of code that checks 3 checkboxes from a window if they are all checked or all unchecked.

  1. Is there a better way to write this?

  2. If the checkboxes are not all checked or unchecked at the same time, what is a better way to do my IF statements?

Any suggestions will be appreciated. Thanks in advance :)

The code the calls and compares the checkboxes value:

public void TheCheckboxesShouldBeChecked()
{
   bool estCheckboxStatus = Win1.GetCheckboxstatus();
   bool checkboxStatus = true;
   Assert.AreEqual(checkboxStatus, estCheckboxStatus, "Checkbox values did not match the default.");
}

public void TheCheckboxesShouldBeUnChecked()
{
   bool estCheckboxStatus2 = Win1.GetCheckboxstatus2();
   bool checkboxStatus2 = true;
   Assert.AreEqual(checkboxStatus2, estCheckboxStatus2, "Checkbox values did not match the default.");
}

The code that checks and returns the values of the checkboxes:

public bool GetCheckboxstatus()
{
   bool value = false;
   if (ChkBx1.Checked
      && ChkBx2.Checked 
      && ChkBx3.Checked)
   {
      value = true;
      return value;
   }
   else
   {
      return value;
   }

 public bool GetCheckboxstatus2()
{
   bool value = true;
   if (ChkBx1.Checked
      && ChkBx2.Checked 
      && ChkBx3.Checked)
   {
      value = false;
      return value;
   }
   else
   {
      return value;
   }   

To determine if all are checked:

return ChkBx1.Checked && ChkBx2.Checked && ChkBx3.Checked;

To determine if none are checked then:

return !ChkBx1.Checked && !ChkBx2.Checked && !ChkBx3.Checked;

For anything more detailed - ie, which are checked and unchecked - then logic naturally starts to look a little ugly.

On the first question, yes there is:

In your testing class:

public void TheCheckboxesShouldBeChecked()
{
    AssertCheckState(Win.AreAllCheckboxesChecked());
}

public void TheCheckboxesShouldBeUnChecked()
{
    AssertCheckState(Win.AreAllCheckboxesUnchecked());
}

private void AssertCheckState(bool value)
{
    Assert.AreEqual(true, actual, "Checked state does not match");
}

In your Win1 class:

public bool AreAllCheckboxesChecked
{
    return (ChkBx1.Checked && ChkBx2.Checked && ChkBx3.Checked);
}

public bool AreAllCheckboxesUnchecked()
{
    return (!ChkBx1.Checked && !ChkBx2.Checked && !ChkBx3.Checked);
}

As for your second concern, really it's up to you and what you need. You could expose individual check states encapsulated in the class properties for example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM