1

The data fields of our column based database are mapped into a DataField class. On each data field object the GetValue<T>() method can be invoked.

If T is an illegal type an exception gets thrown. What type should I pass in my unit test, where I test if an exception gets thrown if I pass an illegal type? The next known illegal type which comes in my mind? Or is there an approach with some more abstraction?

public object GetValue<T>()
{
    if (typeof(T) == typeof(string)) return ValueString;
    if (typeof(T) == typeof(int?)) return ValueInt;
    if (typeof(T) == typeof(double?)) return ValueDouble;
    if (typeof(T) == typeof(DateTime?)) return ValueDateTime;
    if (typeof(T) == typeof(bool)) return ValueBoolean == true;

    var ex = new Exception("Following type is not supported: " + typeof(T));
    Log.Error(ex);
    throw ex;
}

So every type but those should throw this exception if they get passed. So I'd need a kind of dummy type, right?

At the moment my unit test looks like this:

[Fact]
public void If_T_is_illegal_type_an_exception_gets_thrown()
{
    _dataField = new DataField(_params);
    Assert.Throws<Exception>(() => _dataField.GetValue<Type>());
}
4

3 に答える 3

2

Remember that unit testing is trying to get through all code paths and ensuring correct behaviour. You should have 6 tests in total: one for each of the 5 valid types, and one with any other type (as you currently have) to cover the final code path. Not sure why you'd need something more abstract.

You may prefer to use explicit conversions and casting so that this becomes a compile time test rather than run time: http://msdn.microsoft.com/en-us/library/xhbhezf4(v=vs.100).aspx

于 2012-04-25T09:44:41.240 に答える
0

現在GetValue<bool>()、コードを呼び出すと、typeof(T)5回呼び出され、5回の比較が行われます。次に、ボックス化されたブール値をオブジェクトとして返します。そして最悪のことは、このメソッドのシグニチャは、どのタイプが許可され、どのタイプが例外をスローするかについて何も述べていないことです。電話してもGetValue<decimal>()いいですか?わからない。許可されていない場合は、ランタイム例外を試してみてください。

必要なタイプのオーバーロードされたメソッドを作成することを検討してください。

bool GetBooleanValue()
decimal GetDecimalValue()

これは、どのタイプを返すことができるかを完全に説明しています。チェーンが入っていれば長くはありません。呼び出し元はオブジェクトを受け取りません。そして、あなたは質問なしでこの方法のそれぞれのためにテストをするでしょう。

于 2012-04-25T10:04:41.963 に答える
0

上記のように、サポートされているタイプごとに1つのテストと、サポートされていないタイプごとに1つのテストで十分です。

ただし、私が注意していることの1つは、エラーの予想される結果は例外だけではないということです。エラーがログに記録されていることをどのように確認していますか?
これを行う方法はありますか?
そうでない場合、あなたはそれが欲しい/必要ですか?

また、完全に一方的なコードレビューポイント...なぜ

if (typeof(T) == typeof(bool)) return ValueBoolean == true; 

それ以外の

if (typeof(T) == typeof(bool)) return ValueBoolean; 

アラン。

于 2012-04-25T10:07:01.090 に答える