Unit testing in visual studio

Aaron soggi 246 Reputation points
2021-03-27T12:22:08.123+00:00

Hi, for my project i have to do unit testing in visual studio. I'm using the baked in SQL server. How would i do this?

I've tried creating a unitTest project and then create an instance of of my SQLDataFunction class which includes all of the references to my SQL operations but it just takes forever when loading. I'm stuck, and don't know what to do.

How would i test something like this:

string query = " SELECT cs.coachScheduleId, cs.stationDeparture, cs.stationArrival, cs.timeOfDeparture, cs.timeOfArrival, cs.dateOfDeparture, c.numberOfSeats FROM coachSchedule cs JOIN Coach c ON cs.coachId = c.CoachId WHERE cs.dateOfDeparture BETWEEN @dateFrom AND @dateTo AND cs.stationDeparture= @travelFrom AND cs.stationArrival= @travelTo";

                    cmd = new SqlCommand(query, _IsqlDataFunctions.GetConnection());
                    cmd.Parameters.AddWithValue("@dateFrom", dateFromPicker.Value);
                    cmd.Parameters.AddWithValue("@dateTo", dateTooPicker.Value);
                    cmd.Parameters.AddWithValue("@travelFrom", comboBoxTravelFrom.SelectedValue);
                    cmd.Parameters.AddWithValue("@travelTo", comboBoxTravelTo.SelectedValue);

                    _IsqlDataFunctions.displayDataInGrid(cmd, availableBookings);

                    if (availableBookings.Rows.Count == 0) 
                    {
                        MessageBox.Show("Unfortunately no bookings can be found with the information you have entered. Please try again.");
                    }
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,654 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,205 questions
0 comments No comments
{count} votes

Accepted answer
  1. Duane Arnold 3,211 Reputation points
    2021-03-27T12:54:41.4+00:00

    @Aaron soggi

    You should understand when a test is not a unit test, becuase accessing of a database is not a unit test, and you should not be trying to unit test code that is doing it.

    https://www.artima.com/weblogs/viewpost.jsp?thread=126923

    If that code is executed that you have it is considered integration testing, which means you're executing the code in a test that is doing something for real.

    If this is being done for a company you work for, then the company should provide some unit testing classes for a basic understanding by the developer trying to do unit testing, IMHO.

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Williom Koi 0 Reputation points
    2023-02-23T08:53:06.93+00:00
    To unit test your SQLDataFunction class, you can create a test project in Visual Studio and add a reference to your SQLDataFunction class. Then, you can create unit tests for each of the public methods in your class.
    
    For the method you provided in your question, you can create a unit test that does the following:
    
        Create an instance of your SQLDataFunction class
        Call the method that contains the query you provided, passing in appropriate values for the parameters
        Assert that the result of the query is what you expect it to be
    
    Here is an example of how you can write the unit test:
    
    [TestClass]
    public class SQLDataFunctionTests
    {
        private SQLDataFunction _sqlDataFunction;
    
        [TestInitialize]
        public void Initialize()
        {
            _sqlDataFunction = new SQLDataFunction();
        }
    
        [TestMethod]
        public void Test_GetAvailableBookings_Returns_Data()
        {
            // Arrange
            var dateFrom = new DateTime(2023, 02, 01);
            var dateTo = new DateTime(2023, 02, 28);
            var travelFrom = "Station A";
            var travelTo = "Station B";
    
            // Act
            var availableBookings = _sqlDataFunction.GetAvailableBookings(dateFrom, dateTo, travelFrom, travelTo);
    
            // Assert
            Assert.IsNotNull(availableBookings);
            Assert.AreEqual(1, availableBookings.Rows.Count); // Replace with the expected number of rows
        }
    }
    
    In this example, I assumed that the method containing the query you provided is called "GetAvailableBookings". You can replace the method name in the test code with the actual method name you are using.
    I hope this helps you get started with 
    
    
    0 comments No comments

  2. Karen Payne MVP 35,031 Reputation points
    2021-03-27T13:10:33.927+00:00

    A unit test is done in a unit test project and one does not use things like MessageBox, instead you assert what is expected to what is returned.

    Here is super simple example for some unit test that is in this case reference a class project with data operations which reads from a live development environment. Alternate is to mock-up data but that is not truly testing the database such as indexes and permissions for instance.

    Now if things are running slow in unit test such as these examples, open SQL-Profiler to assist in learning why there is a slow response or in SSMS and look at the query plan to see if indexes are needed etc..

    Random discussion on mocking

    81988-f1.png

    namespace DataUnitTestProject  
    {  
        [TestClass]  
        public class UnitTest1  
        {  
              
            [TestMethod]  
            public void ReadAllRecordsFromMessagesTest()   
            {  
                var operations = new ClaimMessagesOperations();  
                  
                Assert.IsNotNull(operations.BasicReadAllMessages(),  
                    "Expected to read OCS_MESSAGE data");  
            }  
      
      
            [TestMethod]  
            public void GetRecordByFieldNameAndLanguageTest()  
            {  
                var fieldValue = "PIN4";  
                var languageCode = "EN";  
      
                var operations = new ClaimMessagesOperations();  
                var messageResult = operations.GetRecordByColumnNameAndLanguage(fieldValue, languageCode);  
      
                Assert.AreEqual(messageResult.MessageTxt, "PIN needs to have 4 digits.");  
            }  
    
            [TestMethod]  
            public void GetAllRecordByFieldNameAndLanguageTest()   
            {  
                var operations = new ClaimMessagesOperations();  
                var fieldValue = "PIN4";  
                var test = operations.GetRecordsByColumnName(fieldValue);  
      
                Assert.IsTrue(test.Count == 4);  
            }  
            [TestMethod]  
            public void GetClaimByPrimaryKey()  
            {  
    
                decimal primaryKey = 1043;  
      
                var operations = new ClaimsOperations();  
                var claimRecord = operations.GetById(primaryKey);  
      
                Assert.IsTrue(claimRecord  
                    .MessageTxt  
                    .StartsWith("You are claiming this week before restarting your claim."),  
                    $"Expected to find {primaryKey} for GetById on ClaimMessage");  
            }  
        }  
    }  
      
    
    0 comments No comments