Detailed explanation. Net unit test method

  • 2021-10-25 06:23:04
  • OfStack

1. Test exceptions

The method can be tested for exception directly, and the simulation object can be tested for exception. However, the simulation object is rarely used for exception testing, so here we introduce the method for exception testing. Look at the following code, which throws an exception when the user name is empty.

For example


 
public bool Valid(string userName, string passWord)
 
  {
 
    if (string.IsNullOrEmpty(userName)) throw new ArgumentNullException("userName is null");
 
    var isValid = userName == "admin" && passWord == "123456";
 
    Log.Write(userName);
 
    return isValid;
 
  }

The test code is as follows


 
 [ Test]
 
 [ExpectedException(typeof(ArgumentNullException))]
 public void Vaild_Throw_Test()
 {
   MyLogin l = new MyLogin();
   l.Valid("", "123456");
 }

2. Test the return value

Here used a LastCall 1 class, more commonly used, 1 some auxiliary testing functions, are in the class.

The test code is as follows


[Test]
public void Valid_Return()
{
  MockRepository mock = new MockRepository();
  var log = mock.DynamicMock<ILog>();
  using (mock.Record())
  {
    log.WriteLog("admin");
    LastCall.Return(0);
  }
  var returnValue = log.WriteLog("admin");
  Assert.AreEqual(returnValue, 0);
}     


Related articles: