下面是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);对象引用未设置为对象的实例。
发布于 2014-08-01 10:26:12
在VB.NET和C#中,值类型变量的行为有细微的区别。
在C#中,在创建变量时没有自动分配的值;它是null (Nothing)。因此,您不能在声明后直接使用它们;对该变量的第一个操作必须是赋值。
另一方面,在VB.NET中,第一次使用时会分配默认值。0表示数字,False表示Boolean,1/1/0001 12:00 AM表示Date,空字符串表示String等。它们不是null。因此,您可以在声明后立即开始使用它们。
例如:
C#:
int i;
i++; //you can't do this
int j = 0;
j++; // this worksVB.NET:
Dim i As Integer
i += 1 ' works ok
Dim j As Integer = 0
j += 1 ' this also works编辑:
请阅读有关String类型变量行为的评论。
https://stackoverflow.com/questions/25076994
复制相似问题