[英]Unit test with wrapped public static method Java
I am not very familiar with Unit Tests, I know that they are very important for code quality, and I want to write some in my project.我对单元测试不是很熟悉,我知道它们对代码质量非常重要,我想在我的项目中写一些。 I recently run into some issues.
我最近遇到了一些问题。 The context is that, I am writing the testClassA for my Aclass, but some functions in Aclass depend on BClass.
上下文是,我正在为我的 Aclass 编写 testClassA,但 Aclass 中的某些函数依赖于 BClass。
BClass is a utility function, so it has many public static
function. BClass 是一个实用函数,所以它有很多
public static
函数。 AClass uses Bclass's functions : AClass 使用 Bclass 的功能:
public class Aclass{
public boolean Afunction()
{
String result = Bclass.Bfunction();
//do stuff with result
return true
}
}
public class Bclass{
public static String Bfunction()
{
//function code
}
}
I want that everytime the BClass.Bfunction is called, then I can return what I want without really execute the real Bfunction in Bclass, so my Aclass doesn't depend on other class in my test.我希望每次调用 BClass.Bfunction 时都可以返回我想要的内容,而无需在 Bclass 中真正执行真正的 Bfunction,因此我的 Aclass 不依赖于我的测试中的其他类。 Is it possible ?
有可能吗?
One approach that limits your changes to just the Aclass, and eliminates the dependency on Bclass (as you asked for) is extract-and-override:将您的更改限制在 Aclass 并消除对 Bclass 的依赖(如您所要求的)的一种方法是提取和覆盖:
So your modified Aclass would look like this:因此,您修改后的 Aclass 将如下所示:
public class Aclass {
public boolean Afunction() {
String result = doBfunction();
// do stuff with result
return true;
}
// This is your "extracted" method.
protected doBfunction() {
return Bclass.Bfunction();
}
}
and your test class would look like this:你的测试类看起来像这样:
class AClassTest {
@Test
public void testAFunction() {
Aclass testObject = new TestableAclass();
boolean value = testObject.AFunction();
// now you can assert on the return value
}
class TestableAclass extends Aclass {
@Override
protected String doBfunction() {
// Here you can do whatever you want to simulate this method
return "some string";
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.