Unit Testing with C# | Code Example

In computer programming, unit testing is a software testing method by which individual units of source code, sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures, are tested to determine whether they are fit for use. Learn more here

Mosh Hamedani made a very useful free YouTube video to describe how to write unit test code in C#. Check it out here

Code Example | Unit Testing using NUnit and C#,

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTest
{
    [TestClass]
    public class UnitTesting
    {
        [TestMethod]
        public void CanBeCancelledBy_UserIsAdmin_ReturnsTrue()
        {
            //Arrange
            var reservation = new Reservation();
            //Act
            var result = reservation.CanBeCancelledBy(new User { IsAdmin = true });
            //Assert
            Assert.IsTrue(result);
        }
    }

    public class User
    {
        public bool IsAdmin { get; set; }
    }

    public class Reservation
    {
        public User MadeBy { get; set; }
        public bool CanBeCancelledBy(User user)
        {
            if (user.IsAdmin)
                return true;
            if (MadeBy == user)
                return true;
            return false;
        }
    }
}
 

This is a open-source international community to improve software testing practices, send your post here

Advertisements

Leave a Reply