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

问题描述

对不返回任何内容的方法进行单元测试的最佳方法是什么?特别是在 c# 中.

What is the best way to unit test a method that doesn't return anything? Specifically in c#.

我真正想要测试的是一种获取日志文件并将其解析为特定字符串的方法.然后将字符串插入到数据库中.之前没有做过任何事情,但对 TDD 非常陌生

What I am really trying to test is a method that takes a log file and parses it for specific strings. The strings are then inserted into a database. Nothing that hasn't been done before but being VERY new to TDD I am wondering if it is possible to test this or is it something that doesn't really get tested.

推荐答案

如果一个方法没有返回任何东西,则是以下任一情况

If a method doesn't return anything, it's either one of the following

  • 命令式 - 你要么要求对象对自己做某事..例如改变状态(不期待任何确认......它假设它会完成)
  • 信息性 - 分别通知某人某事发生(不期望采取行动或回应).
  • imperative - You're either asking the object to do something to itself.. e.g change state (without expecting any confirmation.. its assumed that it will be done)
  • informational - just notifying someone that something happened (without expecting action or response) respectively.

命令式方法 - 您可以验证任务是否实际执行.验证状态更改是否实际发生.例如

Imperative methods - you can verify if the task was actually performed. Verify if state change actually took place. e.g.

void DeductFromBalance( dAmount )

可以通过验证发布此消息的余额是否确实小于dAmount的初始值来测试

can be tested by verifying if the balance post this message is indeed less than the initial value by dAmount

信息方法 - 作为对象的公共接口的成员很少见......因此通常没有经过单元测试.但是,如果必须,您可以验证是否对通知进行了处理.例如

Informational methods - are rare as a member of the public interface of the object... hence not normally unit-tested. However if you must, You can verify if the handling to be done on a notification takes place. e.g.

void OnAccountDebit( dAmount )  // emails account holder with info

可以通过验证是否正在发送电子邮件来测试

can be tested by verifying if the email is being sent

发布有关您的实际方法的更多详细信息,人们将能够更好地回答.
更新:你的方法做了两件事.我实际上将它分成两种现在可以独立测试的方法.

Post more details about your actual method and people will be able to answer better.
Update: Your method is doing 2 things. I'd actually split it into two methods that can now be independently tested.

string[] ExamineLogFileForX( string sFileName );
void InsertStringsIntoDatabase( string[] );

String[] 可以通过为第一种方法提供一个虚拟文件和预期字符串来轻松验证.第二个有点棘手..您可以使用 Mock(在模拟框架上使用 Google 或搜索 stackoverflow)来模拟 DB 或点击实际 DB 并验证字符串是否插入到正确的位置.查看此主题以获取一些好书...如果您愿意,我会推荐实用单元测试处于紧缩状态.
在代码中,它会像

String[] can be easily verified by providing the first method with a dummy file and expected strings. The second one is slightly tricky.. you can either use a Mock (google or search stackoverflow on mocking frameworks) to mimic the DB or hit the actual DB and verify if the strings were inserted in the right location. Check this thread for some good books... I'd recomment Pragmatic Unit Testing if you're in a crunch.
In the code it would be used like

InsertStringsIntoDatabase( ExamineLogFileForX( "c:OMG.log" ) );

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

08-03 20:14
查看更多