Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

unit testing - Mockito uses method stubbing from other test method in the same class

I am trying to test a method for the happy path and an Exception scenario. My class looks like this

class MyClass
{
  @Autowired
  AnotherClass anotherClass;

  public Object myMethod() throws MyException
  {
     try{
       //DO SOME STUFF
       anotherClass.anotherMethod();
     }
     catch(Exception e)
     {
        throw MyException(e);
     }
  }
}

I am testing the above myMethod like this.

@RunWith(MockitoJUnitRunner.class)
class MyClassTest
{
   @Mock
   AnotherClass anotherClass; 
   @InjectMocks
   MyClass myClass;

   @Test
   public void myMethodTest()
   {
      when(anotherClass.anotherMethod()).thenReturn("Mocked data");

      myClass.myMethod();
   }
   
   @Test(expected=MyException.class)
   public void myMethodExpTest()
   {
      when(anotherClass.anotherMethod()).thenThrow(MyException.class);

      myClass.myMethod();
   }
}

When I checked the code coverage using Jacoco, it does not coverage the exception catch block. I tried debugging the test in my Eclipse IDE. I am getting the "Mocked Data" for the exception test method. It appears to be the mocking to that method is not getting reset for the second method. Is there a way to flush the method mocking/stubbing from previous test methods?

question from:https://stackoverflow.com/questions/66068453/mockito-uses-method-stubbing-from-other-test-method-in-the-same-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First I would consider this a bug. But you can manually reset mocks

@Before
public void resetMock() {
  Mockito.reset(anotherClass);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...