尝试在简单计算上运行单元测试时,SQLite错误

时间:2018-12-07 13:08:20

标签: c# unit-testing

因此,我试图为一种简单的计算方法创建一个单元测试类,该方法将5个值加在一起并返回总和。它用于计算预订逻辑火车的客户的火车总票价。

但是当我运行测试时,出现错误告诉我:

Error about SQLite

有人知道为什么这么说吗?这对我来说完全没有意义。

这是我设置的测试方法:

namespace FareTest
{
    [TestClass()]
    public class UnitTest1
    {
        //Test method for testing if the fare cost value comes out as expected
        [TestMethod()]
        public void TestFare()
        {
            //Reference customer fare calculator
            Customers fare = new Customers();

            //Expected value of test
            int expected = 80;

            //The value that comes out of the calculation
            int actual;

            //Variables to add up in the test calculation
            int totalCost = 0;
            int travelFare = 50;
            int firstClass = 10;
            int sleeper = 10;
            int cabin = 10;

            //Test the method and store the value returned in an integer for checking if it is as expected
            actual = fare.CalculateFare(totalCost, travelFare, firstClass, sleeper, cabin);

            //Check the value returned from the calculation against the expected value
            Assert.AreEqual(expected, actual);
        }
    }
}

使用该方法进行计算的类如下:

    //Create sql connection variable with the path name of the database required
        private SQLiteConnection con = new SQLiteConnection(@"Data Source=F:\Uni\OOP\Assessment 2\Trains.db;Version=3;Journal Mode=Off;");

        //Create new customer object to hole each customers specific details
        private CustomerDecorator cust = new CustomerDecorator();

        //Decorator for adding First Class attribute to booking
        private FirstClassDecorator firstClassDecorator = new FirstClassDecorator();

        //Decorator for adding cabin attribute to booking
        private CabinDecorator cabinDecorator = new CabinDecorator();

        //Integer variables for holding prices
        private int totalCost = new int();
        private int travelFare = new int ();
        private int firstClass = new int();
        private int sleeper = new int();
        private int cabin = new int();

  private void btnMakeBook_Click(object sender, RoutedEventArgs e)
        {            
            try
            {
                //If no details have been entered
                if (txtCustName.Text == "" && txtCustTrainID.Text == "" && cbxCustDepart.Text == "" && cbxCustArrive.Text == "" && cbxCustCoach.Text == "" &&
                    txtCustSeat.Text == "")
                {
                    throw new Exception();
                }

                //If the character in train ID is not a capital
                if (Regex.IsMatch(txtCustTrainID.Text, "[a-z]"))
                {
                    throw new Exception();
                }

                //sql command variables for validating data
                #region SQL command variables

                //Create sql command variable to create new command for searching if train has cabins for sleeping
                SQLiteCommand chkCabin = new SQLiteCommand("SELECT sleeperBerth FROM Train WHERE sleeperBerth = 1 AND id = @custTID", con);
                chkCabin.Parameters.AddWithValue("@custTID", txtCustTrainID.Text);

                //Create sql command variable to check if the train selected is a sleeper
                SQLiteCommand chkSleeper = new SQLiteCommand("SELECT sleeperBerth FROM Train WHERE sleeperBerth = 1 AND id = @CustTrain", con);
                chkSleeper.Parameters.AddWithValue("@CustTrain", txtCustTrainID.Text);

                //Create sql command variable to create new command for searching if train has cabins for sleeping
                SQLiteCommand chkFirst = new SQLiteCommand("SELECT * FROM Train WHERE firstClass = 1 AND id = @custTRAINID", con);
                chkFirst.Parameters.AddWithValue("@custTRAINID", txtCustTrainID.Text);

                //Create sql command variable for checking seat number booked
                SQLiteCommand chkSeat = new SQLiteCommand("SELECT * FROM Bookings WHERE coach= @Coach AND seat = @Seat AND trainID = @custTid", con);
                chkSeat.Parameters.AddWithValue("@Coach", cbxCustCoach.Text);
                chkSeat.Parameters.AddWithValue("@Seat", txtCustSeat.Text);
                chkSeat.Parameters.AddWithValue("@custTid", txtCustTrainID.Text);

                //Create sql command for checking if departing station selected is not where this train leaves from
                SQLiteCommand chkDepartIsNotDest = new SQLiteCommand("SELECT * FROM Train WHERE departure = @departing AND id = @Tid", con);
                chkDepartIsNotDest.Parameters.AddWithValue("@departing", cbxCustDepart.Text);
                chkDepartIsNotDest.Parameters.AddWithValue("@Tid", txtCustTrainID.Text);

                //Create sql command variable to create new command for checking if depart station exists on the train trying to be booked
                SQLiteCommand chkDepart = new SQLiteCommand("SELECT * FROM Train WHERE departure LIKE @depart OR destination LIKE @depart OR intermediate LIKE @depart AND id = @tID", con);
                chkDepart.Parameters.AddWithValue("@depart", "%" + cbxCustDepart.Text + "%");
                chkDepart.Parameters.AddWithValue("@tID", txtCustTrainID.Text);

                //Create sql command variable to create new command for checking if arrive station exists on the train trying to be booked
                SQLiteCommand chkArrive = new SQLiteCommand("SELECT * FROM Train WHERE departure LIKE @arrive OR destination LIKE @arrive OR intermediate LIKE @arrive AND id = @cTID", con);
                chkArrive.Parameters.AddWithValue("@arrive", "%" + cbxCustArrive.Text + "%");
                chkArrive.Parameters.AddWithValue("@cTID", txtCustTrainID.Text);

                //Create new command variable for checking order of stops
                SQLiteCommand chkStops = new SQLiteCommand("SELECT intermediate, departure, destination FROM Train WHERE id = @train", con);
                chkStops.Parameters.AddWithValue("@train", txtCustTrainID.Text);

                //Create sql command variable to create new command for searching train id
                SQLiteCommand chkTrain = new SQLiteCommand("SELECT id FROM Train WHERE id = @custtID", con);
                chkTrain.Parameters.AddWithValue("@custtID", txtCustTrainID.Text);

                #endregion

                #region arrange list of stops in order

                //Close connection. This is here as I was getting strange exceptions saying the connection was still open when trying to validate specific things one after another
                con.Close();

                //Start the connection
                con.Open();

                //Create a new data table to hold a list of the trains temporarily
                DataTable dt = new DataTable();

                //Execute the command and store the data in the datatable created
                dt.Load(chkStops.ExecuteReader());

                con.Close();


                //String to hold Intermediate stop value obtained from database
                string interStops = dt.Rows[0]["intermediate"].ToString();
                //String to hold depart station value obtained from database
                string depart = dt.Rows[0]["departure"].ToString();
                //String to hold arrive station value obtained from database
                string arrive = dt.Rows[0]["destination"].ToString();

                //split the string value from intermediate obtained from the database into seperate strings and store them in a string array called stops
                string[] stops = interStops.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);

                //Set size of array to 4 if there are not 4 intermediate stops with the specific train
                Array.Resize(ref stops, 4);

                //String array to hold all the possible stops, including adding null if it does not stop at specific intermediate stops
                string[] allStops = new string[6];

                //Set the correct direction order for the stops
                allStops[0] = depart;
                allStops[1] = stops[0];
                allStops[2] = stops[1];
                allStops[3] = stops[2];
                allStops[4] = stops[3];
                allStops[5] = arrive;
                #endregion

             try
                {
 //Stores the details of the textboxes/Combo boxes into the customer details for each customer object
                    #region variable assigning

                    cust.TrainID = txtCustTrainID.Text;
                    cust.Name = txtCustName.Text;
                    cust.DepStation = cbxCustDepart.Text;
                    cust.ArriveStation = cbxCustArrive.Text;
                    cust.Coach = cbxCustCoach.Text;                    
                    cust.Seat = Convert.ToInt32(txtCustSeat.Text);

                    //Set the component the first class decorator will decorate
                    firstClassDecorator.SetComponent(cust);

                    //Set the component the cabin decorator will decorate
                    cabinDecorator.SetComponent(cust);

                    //If first class check box is checked, sets first class to true, else false
                    if (chbCustFirst.IsChecked == true)
                    {
                        //Use decorator to decorate booking with first class
                        firstClassDecorator.FirstClass = true;
                    }
                    else
                    {
                        firstClassDecorator.FirstClass = false;
                    }
                    //If cabin check box is checked, sets cabin to true, else false
                    if (chbCustCabin.IsChecked == true)
                    {
                        //Use decorator to decorate booking with first cabin
                        cabinDecorator.Cabin = true;
                    }
                    else
                    {
                        cabinDecorator.Cabin = false;
                    }

                    #endregion

                    //Set cost variable values
                    #region Set cost variable values

                    //If customer is traveling the full distance, set travel fare to £50, else £25
                    if (cbxCustDepart.Text == "Edinburgh (Waverley)" && cbxCustArrive.Text == "London (Kings Cross)" ||
                        cbxCustDepart.Text == "London (Kings Cross)" && cbxCustArrive.Text == "Edinburgh (Waverley)")
                    {
                        travelFare = 50;
                    }
                    else
                    {
                        travelFare = 25;
                    }

                    //If the train selected is a sleeper, set sleeper value to 10, else nothing
                    if (chkSleeper.ExecuteScalar() != null)
                    {
                        sleeper = 10;
                    }
                    else
                    {
                        sleeper = 0;
                    }

                    //If cabin checkbox is checked, set cabin value to 10, else nothing
                    if (chbCustCabin.IsChecked == true)
                    {
                        cabin = 10;
                    }
                    else
                    {
                        cabin = 0;
                    }

                    //If first class checkbox is selected, set first class value to 10, else nothing
                    if (chbCustFirst.IsChecked == true)
                    {
                        firstClass = 10;
                    }
                    else
                    {
                        firstClass = 0;
                    }                    

                    #endregion

                    //Show messagebox that lists all the surcharges and the total cost of all together
                    MessageBoxResult result = MessageBox.Show("The total cost for your fare is as follows:" +
                                                            "\nTravel Fare: £" + travelFare +
                                                            "\nFirst Class: £" + firstClass +
                                                            "\nSleeper: £" + sleeper +
                                                            "\nCabin: £" + cabin +
                                                            "\nTotal Fare Cost: £" + CalculateFare(totalCost, travelFare, firstClass, sleeper, cabin) +
                                                          "\n\nDo you want to confirm this booking?",
                                                                                 "Fare Cost",
                                                                                             MessageBoxButton.YesNo,
                                                                                             MessageBoxImage.Question);
                    //If the user confirms the booking, adds them to the database
                    if (result == MessageBoxResult.Yes)
                    {
                        //Sequence to create new booking
 }

                    //Else resets entry and returns
                    else
                    {
                        //Clears all textboxes, combo boxes and check boxes back to default
                        txtCustName.Clear();
                        txtCustTrainID.Clear();
                        cbxCustDepart.SelectedIndex = -1;
                        cbxCustArrive.SelectedIndex = -1;
                        cbxCustCoach.SelectedIndex = -1;
                        txtCustSeat.Clear();
                        chbCustCabin.IsChecked = false;
                        chbCustFirst.IsChecked = false;

                        return;
                    }
                }
                catch
                {
                    //Display errors after throwing exceptions
}
            }
            catch
            {
                //If no details have been entered
                if (txtCustName.Text == "" || txtCustTrainID.Text == "" || cbxCustDepart.Text == "" || cbxCustArrive.Text == "" || cbxCustCoach.Text == "" ||
                    txtCustSeat.Text == "")
                {
                    MessageBox.Show("You have left some fields blank!");

                    return;
                }

                //If the character in train ID is not a capital
                if (Regex.IsMatch(txtCustTrainID.Text, "[a-z]"))
                {
                    MessageBox.Show("You must make the letter in the train ID a capital.");

                    //Resets train id textbox
                    txtCustTrainID.Clear();

                    return;
                }
            }
        }

        public int CalculateFare(int a, int b, int c, int d, int e)
        {
            //Add prices together and return the value
            a = b + c + d + e;
            return a;
        }
}

0 个答案:

没有答案