相关疑难解决方法(0)

如果我们不验证使用单元测试调用私有方法,我们如何验证它们是否被调用?

我讨厌再次提起这件事,但我真的想了解如何用我的测试保护一些东西.

我有一个公共方法(下面),在调用另一个实际采取某些操作的方法之前调用私有方法.我想确保不会删除对私有方法的调用,因为这可能是灾难性的.我已经做了一些研究,在这里,这里,在这里,他们都说不要测试私有方法.我想,我可以理解,但是我如何防止删除这行代码

如您所见,public方法返回void,因此我无法测试公共方法调用的结果.我有ApplicationShouldBeInstalled()直接测试的单元测试.

public void InstallApplications()
{
    foreach (App app in this._apps)
    {
        // This is the line of code that can't be removed. How can I make
        // sure it doesn't get removed?
        if (!ApplicationShouldBeInstalled(app)) { continue; }

        // This simply can't run unless it passes the above call.
        CommonUtility.Container.Resolve<IAppInstaller>().InstallApplication(this, app);
    }                       
}
Run Code Online (Sandbox Code Playgroud)

编辑 - 根据JerKimball的回答,我选择了这个.

基本上,我只使用Mock对象(来自Moq),然后验证其方法被调用了预期的次数.

[TestMethod()]
public void ApplicationShouldBeInstalledTest_UseCase13()
{
    var mockAppInstaller = new Mock<IAppInstaller>();
    mockAppInstaller.Setup(m => …
Run Code Online (Sandbox Code Playgroud)

c# testing mstest moq

8
推荐指数
2
解决办法
3285
查看次数

使用moq测试对私有方法的调用

我有以下方法需要用Moq测试.问题是switch语句中调用的每个方法都是私有的,包括最后的PublishMessage.但是这种方法(ProcessMessage)是公开的.我如何测试这个,以便我可以确保根据参数进行调用?请注意,我没有测试私有方法,我只想测试"调用".我想模拟这些私有方法,并检查它们是否使用安装程序调用,但Moq不支持模拟私有方法.

public void ProcessMessage(DispenserMessageDataContract dispenserMessage)
    {
        var transOptions = new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted };
        using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew, transOptions))
        {
            switch (dispenserMessage.Type)
            {
                case DispenserMessageType.AckNack:
                    UpdateAckNackMessageQueue(dispenserMessage);
                    break;

                case DispenserMessageType.FillRequest:
                    CreateFillRequestMessageQueue(dispenserMessage);
                    break;

                case DispenserMessageType.FillEvent:
                    UpdateFillEventMessageQueue(dispenserMessage);
                    break;

                case DispenserMessageType.RequestInventory:
                    CreateRequestInventoryMessageQueue(dispenserMessage);
                    break;

                case DispenserMessageType.ReceiveInventory:
                    CreateReceiveInventoryMessageQueue(dispenserMessage);
                    break;
            }

            scope.Complete();
        }

        PublishMessage(dispenserMessage);
    }
Run Code Online (Sandbox Code Playgroud)

moq

8
推荐指数
2
解决办法
1万
查看次数

C#单元测试 - 检查是否达到了私有方法

我正在使用C#MOQ库.

让我们说我想UnitTest为这段代码创建一个:

if(condition){
    privateMethod();
}
else{
    logger.info("didn't hit")
}
Run Code Online (Sandbox Code Playgroud)

我想检查是否privateMethod被击中,我不能使用该Verify功能,因为它是私人的.我怎样才能做到这一点?

我想添加一个Status专门用于单元测试的成员,它将在退出测试方法之前保留最后一个位置.

c# moq

0
推荐指数
1
解决办法
1680
查看次数

标签 统计

moq ×3

c# ×2

mstest ×1

testing ×1