21

I am currently writing a C# project and I need to do unit testing for the project. For one of the methods that I need to unit test I make use of an ICollection which is normally populated from the selected items of a list box.

When I create a unit test for the method it creates the line

ICollection icollection = null; //Initialise to an appropriate value

How can I create an instance of this ICollection and an item to the collection?

4

5 に答える 5

35

ICollectionはインターフェイスであるため、直接インスタンス化することはできません。を実装するクラスをインスタンス化する必要がありますICollection。たとえば、List<T>. また、ICollectionインターフェイスにはメソッドがありません。実装するか、そのためにAdd何かが必要です。IListIList<T>

例:

List<object> icollection = new List<object>();
icollection.Add("your item here");
于 2011-10-18T14:20:47.693 に答える
5
List<Object> list = new List<Object>();
list.Add(object1);
list.Add(object2);
// etc...

ICollection collection = list;
// further processing of collection here.

いくつかのコメントに反して、少なくとも私が知る限り、IList<T>実装します。ICollection

于 2011-10-18T14:38:09.953 に答える
3

文字列のコレクションがあるとしましょう。コードは次のようになります。

ICollection<string> test = new Collection<string>();
test.Add("New Value");
于 2011-10-18T14:20:33.373 に答える
0

ICollectionインターフェイスを使用する前に、インターフェイスを新しいクラスに継承する必要があると思います。

ICollection の実装方法

于 2011-10-18T14:22:27.113 に答える
0

できることは、ICollection を実装する型を作成し、そこからテストで使用することです。リストまたはコレクションは、オブジェクトのインスタンスを作成するために機能します。別の質問は、リスト ボックスの項目がどのようなタイプかということでしょう。List または Collection への項目の追加は、.Add(...) メソッドを使用するだけで簡単です。

List<T> list = new List<T>();
list.Add(item_from_your_list_box);
list.Add(item2_from_your_list_box);

このコレクションで行う必要がある具体的なことはありますか?

于 2011-10-18T14:24:13.867 に答える