返回VOID的方法的单元测试 [英] Unit test for method returning VOID

查看:604
本文介绍了返回VOID的方法的单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问候。



我有一个返回VOID的方法,我在下面用Microsoft.VisualStudio.TestTools.UnitTesting编写单元测试。还有更好的选择吗?



我尝试过:



Greetings.

I have a method returning VOID and I have written below Unit test with "Microsoft.VisualStudio.TestTools.UnitTesting" for it. Is there any better alternative to do so?

What I have tried:

using (var uow = new UOW.SalesEntityUOW())
{
    try
    {
        uow.MyMethodCall(); // This method will update data and return nothing.
    }
    catch (Exception ex)
    {
        Assert.IsFalse(true);
    }
    finally
    {
        Assert.IsTrue(true);
    }
}

推荐答案

我同意,如上所述,测试不会测试void方法。它甚至不会验证在出现某种情况时是否会抛出预期的异常。所有它确实运行并且不会抛出异常。可以测试Void方法,但是您需要查看模拟框架的使用和某种形式的依赖注入。在TDD中,你应该在生成代码之前开发测试,因此测试是定义代码应该做什么。



以下是正在测试的void方法的示例:

I would agree that as presented the test does not test the void method. It does not even verify that an expected exception is thrown when a certain condition arises. All it does it verify that something runs and does not throw an exception. Void method can be tested but you will need to look at the use of a mocking framework and some form of dependency injection. In TDD you should be developing the test before producing the code and therefore the test is defining what the code should do.

Here is sample of void method being tested:
/// <summary>
/// Creates the model.
/// </summary>
/// <param name="activityId">The activity identifier.</param>
/// <param name="documentModel">The document model.</param>
/// <exception cref="NotImplementedException"></exception>
public void CreateModel(string activityId, string documentModel)
{
    this.UpdateModel(activityId, documentModel);
}



它使用以下私有方法:


it uses the following private method:

/// <summary>
/// Updates the model.
/// </summary>
/// <param name="activityId">The activity identifier.</param>
/// <param name="documentModel">The document model.</param>
public void UpdateModel(string activityId, string documentModel)
{
    FlattenedActivityModel activityModel = null;
    IAzureContainer azureContainer = ClassContainer.Resolve<IAzureContainer>();
    IPublishActivityEvents publisher = ClassContainer.Resolve<IPublishActivityEvents>();
    var searchQuery = string.Format(CultureInfo.CurrentCulture, "activityId:{0}", activityId);
    var activityModels = azureContainer.ActivitySearch(string.Empty, searchQuery);
    if (activityModels != null)
    {
        if (activityModels.Count > 0)
        {
            activityModel = activityModels[0];
        }
    }

    FlattenedDocumentModel model = new FlattenedDocumentModel(activityModel, documentModel);
    var metadata = JsonConvert.SerializeObject(model);
    publisher.PublishDocumentMetadata(metadata, activityModel.RootName, model.MetadataFileName);
}





验证代码的其中一项测试如下:





One of the tests to validate the code would look like:

[TestMethod]
        public void When_CreateModel_Is_Called_Then_Model_Is_Created_As_Expected()
        {
            var activityContent = File.ReadAllText(@"TestData\FlattenedActivity.json");
            var activity = JsonConvert.DeserializeObject<FlattenedActivityModel>(activityContent);
            var documentRequest = File.ReadAllText(@"TestData\DocumentRequest.json");

            var activityId = Guid.NewGuid().ToString();
            var document1 = new FlattenedDocumentModel
            {
                DocumentId = Guid.NewGuid().ToString(),
                ActivityId = activityId
            };
            var documents = new Collection<FlattenedDocumentModel>
            {
                document1
            };
            var azureConatiner = new Mock<IAzureContainer>();

            var activities = new Collection<FlattenedActivityModel>();
            activity.ActivityId = activityId;
            activities.Add(activity);

            //get the activity
            var queryString = string.Format("activityId:{0}", activityId);
            azureConatiner.Setup(a => a.ActivitySearch(string.Empty, queryString)).Returns(activities);

            var publishActivityEvents = new Mock<IPublishActivityEvents>();

            // Register the components to the IOC container
            ClassContainer.InitialiseRegistrations();
            ClassContainer.RegisterInstance(azureConatiner.Object);
            ClassContainer.RegisterInstance(publishActivityEvents.Object);

            var target = new DocumentApi();
            target.UpdateModel(activityId, documentRequest);

            FlattenedDocumentModel expectedModel = new FlattenedDocumentModel(activity, documentRequest);
            var expectedMetadata = JsonConvert.SerializeObject(expectedModel);

            azureConatiner.Verify(a => a.ActivitySearch(string.Empty, queryString), Times.Once());
            publishActivityEvents.Verify(p => p.PublishDocumentMetadata(expectedMetadata, activity.RootName, expectedModel.MetadataFileName));
        }





此测试验证void方法的内部是否正在进行预期调用,具有预期值和预计的次数。(我想指出这个样本是WIP并且有一些问题需要进一步测试,例如activityModel为null)。



This test verifies that the internals of the void method is making the expected calls, with the expected values and the expected number of times.(I would point out that this sample is WIP and has some issues that need further tests e.g. activityModel being null).


这篇关于返回VOID的方法的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆