首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么测试在vb中通过?它应该会失败(在c#版本中失败)

为什么测试在vb中通过?它应该会失败(在c#版本中失败)
EN

Stack Overflow用户
提问于 2014-08-01 09:25:21
回答 1查看 141关注 0票数 1

下面是Professional.Test.Driven.Development.with.Csharp中的示例,我正在将代码从C#转换为VB。(这个例子是第7章的开始)

现在有

代码语言:javascript
复制
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项目中

代码语言:javascript
复制
<TestFixture>
Public Class Specification
   Inherits SpecBase
End Class

当用vb.net编写测试时(应该失败),它很好地通过了(整数值为0= 0)

代码语言:javascript
复制
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#中相同的代码。测试失败

代码语言:javascript
复制
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);
        }
    }
}

测试在这一行上失败:

代码语言:javascript
复制
_result = _itemTypeRepository.Save(_testItemType);

对象引用未设置为对象的实例。

EN

回答 1

Stack Overflow用户

发布于 2014-08-01 10:26:12

在VB.NET和C#中,值类型变量的行为有细微的区别。

在C#中,在创建变量时没有自动分配的值;它是null (Nothing)。因此,您不能在声明后直接使用它们;对该变量的第一个操作必须是赋值。

另一方面,在VB.NET中,第一次使用时会分配默认值。0表示数字,False表示Boolean1/1/0001 12:00 AM表示Date,空字符串表示String等。它们不是null。因此,您可以在声明后立即开始使用它们。

例如:

C#:

代码语言:javascript
复制
int i;
i++;        //you can't do this

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

VB.NET:

代码语言:javascript
复制
Dim i As Integer
i += 1      ' works ok

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

编辑:

请阅读有关String类型变量行为的评论。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25076994

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档