对一个不返回任何东西的方法进行单元测试的最佳方法是什么?特别是在c#中。
我真正想测试的是一个方法,它接受一个日志文件并解析它的特定字符串。然后将字符串插入到数据库中。没有什么是以前没有做过的,但对于TDD来说是非常新的,我想知道是否有可能测试这个,或者它是没有真正测试过的东西。
对一个不返回任何东西的方法进行单元测试的最佳方法是什么?特别是在c#中。
我真正想测试的是一个方法,它接受一个日志文件并解析它的特定字符串。然后将字符串插入到数据库中。没有什么是以前没有做过的,但对于TDD来说是非常新的,我想知道是否有可能测试这个,或者它是没有真正测试过的东西。
当前回答
无论你使用什么实例来调用void方法,你可以使用,验证
例如:
在我的例子中,它的_Log是实例,LogMessage是要测试的方法:
try
{
this._log.Verify(x => x.LogMessage(Logger.WillisLogLevel.Info, Logger.WillisLogger.Usage, "Created the Student with name as"), "Failure");
}
Catch
{
Assert.IsFalse(ex is Moq.MockException);
}
验证是否由于测试将失败的方法失败而抛出异常?
其他回答
假设方法做了一些事情,而不是简单地返回?
假设是这样,那么:
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).
如果你告诉我们这个方法是做什么的,我可以更具体地说。
无论你使用什么实例来调用void方法,你可以使用,验证
例如:
在我的例子中,它的_Log是实例,LogMessage是要测试的方法:
try
{
this._log.Verify(x => x.LogMessage(Logger.WillisLogLevel.Info, Logger.WillisLogger.Usage, "Created the Student with name as"), "Failure");
}
Catch
{
Assert.IsFalse(ex is Moq.MockException);
}
验证是否由于测试将失败的方法失败而抛出异常?
一如既往:测试该方法应该做什么!
它是否应该在某个地方改变全局状态(哎呀,代码味道!)?
它是否应该调用接口?
当使用错误的参数调用时,它是否会抛出异常?
当使用正确的参数调用时,它是否不抛出异常?
应该……吗?
试试这个:
[TestMethod]
public void TestSomething()
{
try
{
YourMethodCall();
Assert.IsTrue(true);
}
catch {
Assert.IsTrue(false);
}
}
这取决于它在做什么。如果它有参数,则传入模拟,以便稍后询问是否使用正确的参数集调用了它们。