我有这样的课:
Class A
{
public boolean do(String s)
{
C c = DB.GetResult(s);
....
return yes/no
}
}
我想如何用 Mockito 编写单元测试,但是如何模拟内部对象 C 来抑制数据库连接操作。
我有这样的课:
Class A
{
public boolean do(String s)
{
C c = DB.GetResult(s);
....
return yes/no
}
}
我想如何用 Mockito 编写单元测试,但是如何模拟内部对象 C 来抑制数据库连接操作。
您的意思是模拟内部对象数据库而不是 C 对吗?
在像你这样的代码中你不能。您必须将 DB 注入 A 类。然后在单元测试中注入模拟/存根而不是与数据库对话的对象。
编辑:你可以这样做(我正在使用 C#):
Class A
{
private readonly IDb database;
// you can inject by hand or using IoC container
// if you don't like that you have to pass IDb implementation everywhere
// where you create objects of type A you can add another constructor - look under
public A(IDb database)
{
this.database = database;
}
// here you call the above constructor and pass you original DB object
public A() : this(new DB())
{
}
public boolean do(String s)
{
C c = database.GetResult(s);
....
return yes/no
}
}
当然,您的 DB 类必须实现 IDb 接口。
interface IDb
{
C GetResults(String s);
}
现在在你的测试中你这样做:
var a = new A(new TestDBDoingReturningExactlyWhatYouTellItToReturn());
并在应用程序代码中:
var a = new A(new DB());
或无参数构造函数,它完全执行上面的行
var a = new A();