我试图在下面的类中为“ Isunique”功能编写单元测试,看起来像这样:

class Foo
{
    public bool IsUnique(params...)
    {
       ValidateStuffExists(params);
       return CheckUniqueness(params);
    }

    private void ValidateStuffExists(params)
    {
      //does some validation
    }

    private bool CheckUniqueness(params)
    {
       //does logic to determine if its unique per params
       return result;
    }

}

我在这里唯一要测试的是,valialateStuffexists和chectuniquess被调用并通过了参数。这就是所有这些功能,所以我将要测试(我将弯曲“仅测试公共行为” psoudo-rule并在此处测试私人方法,因为它要么具有一个大的复杂方法/测试,要么测试2私有方法)。

我向任何模拟图书馆开放。我使用nmock,并且不认为这是为了完成这项任务 - 所以我下载了打字机,因为我已经阅读了,听说这是最好的,甚至可以模拟甚至具体的类 /非接口方法调用...

我正在测试中做类似的事情,并且在“分离式”线上引发了例外:

        CrmEntityUniqueValidator_Accessor target = new CrmEntityUniqueValidator_Accessor(); // TODO: Initialize to an appropriate value
        DynamicEntity entity = null; // TODO: Initialize to an appropriate value
        string[] propertyNames = null; // TODO: Initialize to an appropriate value

        bool tru = true;
        Isolate.WhenCalled(() => target.CheckUniqueness(entity, propertyNames, null, null)).WillReturn(tru);

        target.ValidatePropertiesExist(entity, propertyNames);

        Isolate.Verify.WasCalledWithArguments(() => target.ValidatePropertiesExist(entity, propertyNames));
        Isolate.Verify.WasCalledWithArguments(() => target.CheckUniqueness(entity, propertyNames, null, null));

这引发了一个例外 “ ***当值时,不支持使用方法调用作为参数。”

即使我能够使用CLR类做同样的事情 - 我也可以嘲笑DateTime。现在执行此操作(代码工作):

        DateTime endOfWorld = new DateTime(2012, 12, 23);
        Isolate.WhenCalled(() => DateTime.Now).WillReturn(endOfWorld);
        DateTime dt = DateTime.Now;

        Assert.AreEqual(dt, endOfWorld);

有人在这里有任何建议吗?我是否必须将这两种方法拆分为单独的类,并唯一的方法?还是使我的方法/测试复杂化???我在这里一定有一些我缺少的东西...非常感谢您提前提供的任何帮助。

编辑:我想我试图为一个单元测试嘲笑类中的两种私人方法。我该怎么做,而不必将这两种方法拆分为单独的类 /接口?

有帮助吗?

解决方案

尝试孤立.nonpublic.whencalled(对象,“非公开方法”)。

或分离。

其他提示

犀牛有 AssertWasCalled 可以保证方法调用另一种方法的方法...但是我不确定您是否可以在单位测试的同一类的私人功能上执行此操作。我认为,只有在您想存根的两种方法中,您才能做到这一点。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top