1

Professional.Test.Driven.Development.with.Csharpの例に従って います。コードを C# から VB に変換しています。(この例は第 7 章の始まりです)

今持っている

Public Class ItemType
   Public Overridable Property Id As Integer
End Class

Public Interface IItemTypeRepository
    Function Save(ItemType As ItemType) As Integer
End Interface

Public Class ItemTypeRepository
  Implements IItemTypeRepository

Public Function Save(ItemType As ItemType) As Integer Implements IItemTypeRepository.Save
    Throw New NotImplementedException
End Function
End Class

そしてTestUnitプロジェクトで

<TestFixture>
Public Class Specification
   Inherits SpecBase
End Class

vb.net でテストを作成すると (失敗するはずです)、問題なくパスします (整数値 0 = 0)。

Public Class when_working_with_the_item_type_repository
   Inherits Specification
End Class

Public Class and_saving_a_valid_item_type
   Inherits when_working_with_the_item_type_repository

   Private _result As Integer
   Private _itemTypeRepository As IItemTypeRepository
   Private _testItemType As ItemType
   Private _itemTypeId As Integer

   Protected Overrides Sub Because_of()
       _result = _itemTypeRepository.Save(_testItemType)
   End Sub

   <Test>
   Public Sub then_a_valid_item_type_id_should_be_returned()
       _result.ShouldEqual(_itemTypeId)
   End Sub
End Clas

C# の同じコードを参照するためだけに。テスト失敗

using NBehave.Spec.NUnit;
using NUnit.Framework;
using OSIM.Core;


namespace CSharpOSIM.UnitTests.OSIM.Core
{
    public class when_working_with_the_item_type_repository : Specification
{
}
    public class and_saving_a_valid_item_type : when_working_with_the_item_type_repository
        {
        private int _result;
        private IItemTypeRepository _itemTypeRepository;
        private ItemType _testItemType;
        private int _itemTypeId;

        protected override void Because_of()
        {
            _result = _itemTypeRepository.Save(_testItemType);
        }

        [Test]
        public void then_a_valid_item_type_id_should_be_returned()
        {
            _result.ShouldEqual(_itemTypeId);
        }
    }
}

テストは次の行で失敗します:

_result = _itemTypeRepository.Save(_testItemType);

オブジェクト参照がオブジェクト インスタンスに設定されていません。

4

1 に答える 1

2

VB.NET と C# では、値型変数の動作に微妙な違いがあります。

C# では、変数の作成時に自動的に割り当てられる値はありません。null( Nothing) です。したがって、宣言の直後にそれらを使用することはできません。その変数に対する最初の操作は代入でなければなりません。

一方、VB.NET では、最初の使用時にデフォルト値が割り当てられます。0数値、Falsefor Boolean1/1/0001 12:00 AMfor Date、空文字列 forStringなど。これらは null ではありません。そのため、申告後すぐに利用を開始できます。

例えば

C#:

int i;
i++;        //you can't do this

int j = 0;
j++;        // this works

VB.NET:

Dim i As Integer
i += 1      ' works ok

Dim j As Integer = 0
j += 1      ' this also works

編集:

String型変数の振る舞いについてのコメントを読んでください。

于 2014-08-01T10:26:12.277 に答える