How to call the same method multiple times in junit5 to return different values

  Kiến thức lập trình

My situation is different! Chained calls don’t seem to work.
There is a lot of code, I wrote a similar test class

JavaFile.java
public void methodA(){
  try{
    new OtherClass().MethodB();
  }catch(Exception e){
    System.out.println("e1");
  }
   System.out.println("-----------");
  try{
    new OtherClass().MethodB();
  }catch(Exception e){
    System.out.println("e2");
  }
}
Junit5File.java
//The annotation is written like this because it is needed in other places.
@InjectMocks
JavaTest test = new JavaTest();
@Spy
@InjectMocks
JavaTest testSpy;

@Test
void testMethodA(){
//other test point

 try(MockedConstruction<JavaTest> mock = mockConstruction(JavaTest.class,(dao, context)->{
  //method method has no return value
   doThrow(new Exception()).doNothing.when(dao).MethodB();
 }
 testspy.MethodA();
}

Desired result. Call methodB twice, the first time an exception is thrown, and the second time the execution ends without any operation.
actual results. Throws two exceptions and prints the results “e1” and “e2”.
This seems to be the reason for keyword new twice, I’m not sure.
I checked the documentation and other answers, and it seems there is no such problem as mine.

If methodB and methodA are in the same class, directly call methodB(); without using the keyword new.
Using spy to simulate the call in junit5, the result is normal. Unfortunately, it is not, and the code of the class under test cannot be changed.

New contributor

plz is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT