gpt4 book ai didi

java - 如何使用junit模拟同一类的方法

转载 作者:行者123 更新时间:2023-11-30 02:45:20 24 4
gpt4 key购买 nike

我正在使用JUnit,我的情况如下:

class A{
public int[] method1(){
...
int res = method2();
...
return intArray;
}

public int method2(){
....
return intA;
}
}

我正在尝试模仿method2()

new MockUp<MockClass>() {
int[] methodToMock() {
int[] mockedResult = {1, 2, 4, 6};
return mockedResult;
}
};

当我将上面的代码用于另一个类时,它工作得很好。但如果我想模拟同一个类的方法,它就不起作用。

请指导我在JUnit中找到mock方法,以mock来自同一个类的方法。

谢谢。

最佳答案

public method 调用同一类的另一个 public method 不一定是软件开发中的问题,但它会在您的类中创建内部耦合,并且可能是类(class)里的责任太多。不一定总是正确的,但可以提出问题。
证据:在这里,单元测试在没有欺骗的情况下变得更加困难。

i cant move this method to any other class . And this method is also used some where else so i cant club it in once.

考虑到这些限制,我建议您保留这两个公共(public)方法并引入一个新类,该类会考虑这两个方法的共同行为。
这两个公共(public)方法现在可以依赖公共(public)类来进行处理。

class A{

private CommonProcess commonProcess;

public int[] method1(){
...
int res = commonProcess.method(...);
...
return intArray;
}

public int method2(){
....
commonProcess.method(...);
...
return intA;
}
}

现在,要模拟 method2method1 中的外部依赖项,只需模拟对 commonProcess.method() 的调用即可。

关于java - 如何使用junit模拟同一类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40360165/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com