CS0266 - 无法隐式转换类型"系统IList"到" System ArrayList" - 软件测试

时间:2017-05-17 02:39:25

标签: c# testing moq

我正在尝试为我的软件测试任务创建一些模拟单元测试,而我的GUI.cs文件有一个错误,表明它无法隐式转换类型" System.Collections.IList"到" System.Collection.ArrayList"

this.accounts = database.GetAccounts();

然而该文件未受影响。我的意思是我没有修改它。我修改的唯一文件是单元测试,文件数据库和下面列出的Idatabase,通过更改一些变量类型,例如将我的所有ArrayList重命名为IList。

但是我的GUI有错误,而且我无法确定哪个文件是它的原因以及哪行代码。

以下是GUI.cs文件

错误是" this.accounts ..."线。

两个" dataGridView1"当我在Visual Studio上将鼠标悬停在它上面时,行有一些System.NullReferenceException错误。这可能与我遇到的错误有关,我不太确定。

private void InitBankRead()
        {
            try
            {
                //database = new FileDatabase();
                database = IoC.GetInstance().Resolve<IDatabase>();

                this.accounts = database.GetAccounts();
                this.dataGridView1.DataSource = accounts;

                dataGridView1.Columns["Balance"].DefaultCellStyle.Format = "C";

                foreach (DataGridViewColumn column in dataGridView1.Columns)
                {
                    dataGridView1.Columns[column.Name].SortMode = DataGridViewColumnSortMode.Automatic;
                }
            }

=============================================== ==

=============================================== ==

编辑:

对于想要深入挖掘的人来说,我的其余文件还有以下内容。它是可选的,但它就在那里。我的尝试不是用我的作品压倒你们,而是要确保你理解我所说的。

IDatabase.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using Banking;


namespace Banking
{
    public interface IDatabase
    {
        //IList<Account> FindAll();
        //Account FindByAccount(int accountId);
        //Account FindByName(int firstName, int lastName);
        //bool Save(Account target);

        bool AddNewCustomer(int customerId, string firstName, string lastName, decimal openingDeposit, Account.ACCOUNTTYPE type);
        bool UpdateExistingAccount(char transactionType, Account account, decimal amount);
        IList GetAccounts();

    }
}

FileDatabase.cs

using System;
using System.Collections;
using System.IO;
using Banking;

namespace Banking
{
    public class FileDatabase : IDatabase
    {
        private string filename;
        private StreamWriter outFile;
        private StreamReader inFile;
        public const string DELIMETER = ",";

        public FileDatabase()
        {
            this.filename = @"..\..\..\Banking\Data\Database.txt";
        }

        public bool AddNewCustomer(int customerID, string firstName, string lastName, decimal openingDeposit, Account.ACCOUNTTYPE type)
        {
            int accountID = GetAccounts().Count + 1;
            using (outFile = File.AppendText(filename))
            {
                string output = accountID + DELIMETER + customerID + DELIMETER + firstName + DELIMETER + lastName + DELIMETER + openingDeposit + DELIMETER + Convert.ToInt32(type);
                outFile.WriteLine(output);

                outFile.Close();
            }
            return true;
        }
        public bool UpdateExistingAccount(char transactionType, Account account, decimal amount)
        {
            bool success = false;
            try
            {
                switch (transactionType)
                {
                    case 'D':
                        //account.Balance += amount;
                        account.deposit(amount);
                        break;
                    case 'W':
                        //account.Balance -= amount;
                        account.withdrawl(amount);
                        break;
                }

                IList accounts = GetAccounts();
                int accountID = account.AccountID;

                // Find and replace the account
                for (int i = 0; i < accounts.Count; ++i)
                {
                    if (accountID == ((Account) accounts[i]).AccountID)
                    {
                        accounts[i] = account;
                    }
                }

                using (outFile = new StreamWriter(filename))
                {
                    foreach (Account acct in accounts)
                    {
                        outFile.WriteLine(acct.AccountID + DELIMETER + acct.Customer.CustomerID + DELIMETER + acct.Customer.FirstName + DELIMETER + acct.Customer.LastName + DELIMETER + acct.Balance + DELIMETER + Convert.ToInt32(acct.AccountType));
                    }
                    outFile.Close();
                }
                success = true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                success = false;
            }
            return success;
        }

        public IList GetAccounts()
        {
            IList accounts = new ArrayList();

            using (inFile = new StreamReader(filename))
            {
                int customerID;
                int accountID;
                string firstName;
                string lastName;
                decimal balance;
                int accountType;
                string line = string.Empty;

                while ((line = inFile.ReadLine()) != null)
                {
                    string [] data = line.Split(DELIMETER.ToCharArray()[0]);

                    customerID = Convert.ToInt32(data[0]);
                    accountID = Convert.ToInt32(data[1]);
                    firstName = Convert.ToString(data[2]);
                    lastName = Convert.ToString(data[3]);
                    balance = Convert.ToDecimal(data[4]);
                    accountType = Convert.ToInt32(data[5]);

                    Customer customer = new Customer(customerID, firstName, lastName);
                    Account account;

                    Account.ACCOUNTTYPE type = (Account.ACCOUNTTYPE) accountType;
                    if (type == Account.ACCOUNTTYPE.CHECKING)
                    {
                        account = new Checking(customer, accountID, Convert.ToDecimal(balance));
                    }
                    else
                    {
                        account = new Savings(customer, accountID, Convert.ToDecimal(balance));
                    }

                    accounts.Add(account);
                }
                inFile.Close();
            }
            return accounts;
        }
    }
}

UnitTest.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Banking;
using Moq;


namespace UnitTestsWithMoQ
{
    [TestClass]
    public partial class UnitTest1
    {
        public TestContext TestContext { get; set; }
        public readonly IDatabase MockDatabase;

        private IList accounts = new List<Account>
        {
            new Checking( new Customer(1, "Alex", "Parrish"), 12, 30.00M ),
            new Savings( new Customer(2, "Alex", "Russo"), 12, 29.00M ),
            new Checking( new Customer(3, "Emma", "Swan"), 12, 30.00M ),
            new Savings( new Customer(4, "Henry", "Mills"), 12, 30.00M )
        };
        Mock<IDatabase> dataMock = new Mock<IDatabase>();


        private string filename;
        private StreamWriter outFile;
        private StreamReader inFile;
        public const string DELIMETER = ",";

        public UnitTest1()
        {
            // Return all accounts
            dataMock.Setup(repository => repository.GetAccounts()).Returns(accounts);
            dataMock.Setup(repository => repository.UpdateExistingAccount(It.IsAny<char>(), It.IsAny<Account>(),
                It.IsAny<decimal>())).Returns((char transactionType, Account account, decimal amountDecimal) =>
            {
                bool success = false;
                try
                {
                    switch (transactionType)
                    {
                        case 'D':
                            //account.Balance += amount;
                            account.deposit(amountDecimal);
                            break;
                        case 'W':
                            //account.Balance -= amount;
                            account.withdrawl(amountDecimal);
                            break;
                    }

                    var accounts = MockDatabase.GetAccounts();
                    int accountID = account.AccountID;

                    // Find and replace the account
                    for (int i = 0; i < accounts.Count; ++i)
                    {
                        if (accountID == ((Account) accounts[i]).AccountID)
                        {
                            accounts[i] = account;
                        }
                    }
                    // Find and replace the account
                    for (int i = 0; i < accounts.Count; ++i)
                    {
                        MockDatabase.GetAccounts()[i] = accounts[i];
                    }

                }

                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                    success = false;

                }

                return success;

            });

            dataMock.Setup(repository => repository.AddNewCustomer(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<decimal>(),
                It.IsAny<Account.ACCOUNTTYPE>())).Returns((int customerID, string firstName, string lastName, decimal openingDeposit, Account.ACCOUNTTYPE type) =>
            {
                int accountID = MockDatabase.GetAccounts().Count + 1;
                using (outFile = File.AppendText(filename))
                {
                    string output = accountID + DELIMETER + customerID + DELIMETER + firstName + DELIMETER + lastName + DELIMETER + openingDeposit + DELIMETER + Convert.ToInt32(type);
                    outFile.WriteLine(output);

                    outFile.Close();
                }
                return true;

            });


            MockDatabase = dataMock.Object;
        }

    }
}

1 个答案:

答案 0 :(得分:0)

如果错误显示为cannot implicitly convert type "System.Collections.IList" to "System.Collection.ArrayList",那么您可能正在为IList变量分配ArrayList变量。

请注意,IList是一个比具体类型ArrayList更通用的接口,因此编译器不知道如何隐式转换它。

this.accounts = database.GetAccounts();

如何定义accounts

如果它被定义为:ArrayList accounts,那么您将无法进行该分配。

尝试将其更改为:IList accounts