对一个不返回任何东西的方法进行单元测试的最佳方法是什么?特别是在c#中。
我真正想测试的是一个方法,它接受一个日志文件并解析它的特定字符串。然后将字符串插入到数据库中。没有什么是以前没有做过的,但对于TDD来说是非常新的,我想知道是否有可能测试这个,或者它是没有真正测试过的东西。
对一个不返回任何东西的方法进行单元测试的最佳方法是什么?特别是在c#中。
我真正想测试的是一个方法,它接受一个日志文件并解析它的特定字符串。然后将字符串插入到数据库中。没有什么是以前没有做过的,但对于TDD来说是非常新的,我想知道是否有可能测试这个,或者它是没有真正测试过的东西。
当前回答
假设方法做了一些事情,而不是简单地返回?
假设是这样,那么:
If it modifies the state of it's owner object, then you should test that the state changed correctly. If it takes in some object as a parameter and modifies that object, then your should test the object is correctly modified. If it throws exceptions is certain cases, test that those exceptions are correctly thrown. If its behaviour varies based on the state of its own object, or some other object, preset the state and test the method has the correct Ithrough one of the three test methods above).
如果你告诉我们这个方法是做什么的,我可以更具体地说。
其他回答
使用Rhino mock来设置可能预期的调用、操作和异常。假设您可以模拟或去掉方法的某些部分。如果不了解关于方法甚至上下文的一些细节,就很难知道。
假设方法做了一些事情,而不是简单地返回?
假设是这样,那么:
If it modifies the state of it's owner object, then you should test that the state changed correctly. If it takes in some object as a parameter and modifies that object, then your should test the object is correctly modified. If it throws exceptions is certain cases, test that those exceptions are correctly thrown. If its behaviour varies based on the state of its own object, or some other object, preset the state and test the method has the correct Ithrough one of the three test methods above).
如果你告诉我们这个方法是做什么的,我可以更具体地说。
你甚至可以这样尝试:
[TestMethod]
public void ReadFiles()
{
try
{
Read();
return; // indicates success
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
一如既往:测试该方法应该做什么!
它是否应该在某个地方改变全局状态(哎呀,代码味道!)?
它是否应该调用接口?
当使用错误的参数调用时,它是否会抛出异常?
当使用正确的参数调用时,它是否不抛出异常?
应该……吗?
它会对一个对象产生一些影响....查询效果的结果。如果没有明显的效果,就不值得进行单元测试!