如何用void返回类型模拟方法?
我实现了一个观察者模式,但我无法用Mockito模拟它,因为我不知道如何.
我试图在互联网上找到一个例子,但没有成功.
我的班级看起来像
public class World {
List<Listener> listeners;
void addListener(Listener item) {
listeners.add(item);
}
void doAction(Action goal,Object obj) {
setState("i received");
goal.doAction(obj);
setState("i finished");
}
private string state;
//setter getter state
}
public class WorldTest implements Listener {
@Test public void word{
World w= mock(World.class);
w.addListener(this);
...
...
}
}
interface Listener {
void doAction();
}
Run Code Online (Sandbox Code Playgroud)
系统不会通过模拟触发.=(我想显示上面提到的系统状态.并根据它们做出断言.
如何为调用同一类的其他方法但不返回值的方法编写单元测试?(让我们说PHPUnit.)
例如,假设我有以下类:
class MyClass {
public function doEverything() {
$this->doA;
$this->doB;
$this->doC;
}
public function doA() {
// do something, return nothing
}
public function doB() {
// do something, return nothing
}
public function doC() {
// do something, return nothing
}
}
Run Code Online (Sandbox Code Playgroud)
你会怎么测试doEverything()?
编辑:
我问这个是因为从我看过的内容看来,几乎所有的方法都应该有自己的专用单元测试.当然,你也有功能和集成测试,但那些目标特定的例程,可以这么说(不是必须在每个方法级别).
但是,如果几乎所有方法都需要自己的单元测试,我认为对所有上述方法进行单元测试将是"最佳实践".是/否?
我正在尝试使用测试驱动设计方法编写一个应用程序 - 我对单元测试相当陌生,所以我只是想知道测试正确输入和异常的正确方法是什么。
我有一个用于加载配置文件的类:
class Config
{
private XmlDocument configfile;
public Config()
{
configfile = new XmlDocument();
}
public void LoadConfigFile(string filename)
{
if(string.IsNullOrEmpty(filename))
throw new System.ArgumentException("You must specify a filename");
try
{
configfile.Load(filename);
}
catch (Exception ex)
{
throw new System.IO.FileNotFoundException("File could not be loaded");
}
}
}
Run Code Online (Sandbox Code Playgroud)
因此,这里可以执行 3 个测试:
测试这些的正确方法是编写 3 个测试方法,如下所示:
/// <summary>
///A test for LoadConfigFile
///</summary>
[TestMethod()]
public void LoadConfigFileTest()
{
Config target = new Config(); // TODO: Initialize to an …Run Code Online (Sandbox Code Playgroud) unit-testing ×3
c# ×1
codeception ×1
java ×1
mocking ×1
mockito ×1
php ×1
phpunit ×1
testing ×1
void ×1