MyCode:
class LocalClass{
public getNumber(){
retunr 5;
}
}
class AnotherLocalClass{
public static getNumber(){
retunr 10;
}
}
public class A{
public int methodAa(Boolean flag, int paramValue){
return methodA(flag, paramValue);
}
private int methodA(Boolean flag, int paramValue){
int returnValue = 0;
try{
if(flag){
LocalClass localVariable = new LocalClass();
returnValue = localVariable.getNumber() + paramValue;
} else{
returnValue = AnotherLocalClass.getNumber() + paramValue;
}
return returnValue;
}catch(Exception e){
e.printStackTrace();
return 0;
}
}
}
public class ATest{
@InjectMocks
A a;
public void methodATest(){
//need help to write here
}
}
CCD_ 1和CCD_ 2是包含返回值的方法的类。
AnotherLocalClass
中的getNumber
是一种静态方法。
类A
是我为其编写ATest
类的主要类。
我只能用methodATest
编写代码。并且不能更改LocalClass
、AnotherLocalClass
或类LocalClass
0中的任何内容。
我想写methodATest
,这样methodA
就会抛出一个异常。
我的mockito版本是1.19.10,不能更改。
而且我不能使用PowerMockito或任何其他新的依赖项。
您希望代码中出现哪些异常?哪些参数值会导致异常?在这些情况下,您期望的返回值是多少?
当你得到这些问题的答案时,你必须为例外情况的发生设定条件。然后你的代码看起来像这样:
public class ATest{
A a = new A();
@Test
public void methodATest(){
Boolean flag = ?;
int paramValue = ?;
int expectedReturnValue = ?;
int returnValue = a.methodAa(flag, paramValue);
assertEquals(expectedReturnValue, returnValue);
}
}
注意mock方法。我们通常在需要设置一个类时使用它,而我们并不希望它运行它的方法,所以我们进行模拟,然后返回测试所需的东西。
您可以通过本教程了解有关测试的更多信息:https://www.vogella.com/tutorials/JUnit/article.html#junittesting
----【编辑】----
如果你想嘲笑LocalClass,你需要做这样的事情:
@PrepareForTest({LocalClass.class, A.class})
@RunWith(PowerMockRunner.class)
public class ATest{
A a = new A();
@Test
public void methodATest(){
PowerMockito.mockStatic(LocalClass.class);
PowerMockito.when(LocalClass.getNumber()).thenThrow(new Exception());
...
}
}
但是,getNumber((方法应该是静态的才能工作。而且,由于您不能使用PowerMockito,因此不可能模拟该类。
----【编辑】----
@PrepareForTest({AnotherLocalClass.class, A.class})
@RunWith(PowerMockRunner.class)
public class ATest{
A a = new A();
@Test
public void methodATest(){
PowerMockito.mockStatic(AnotherLocalClass.class);
PowerMockito.when(AnotherLocalClass.getNumber()).thenThrow(new Exception());
a.methodAa(...);
...
}
}
但是,由于静态方法属于类,所以在Mockito中无法模拟静态方法。