Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test a void method using JUnit and Mockito?

My void method changes boolean variable value in the class. How do DI check that?

I have:

  • mocked class object
  • called the method with proper parameters
  • checked the instance variable

But that doesn't change the value of instance variable. How do I do this?

ReferenceLettersBean rf = Mockito.mock(ReferenceLettersBean.class);
     rf.setBoolcheck(false);

Mockito.doNothing().when(rf).checkForDuplicates(anyString(),     anyString(), anyString());
         rf.checkForDuplicates("[email protected]","[email protected]","[email protected]");
assertEquals(true,rf.getBoolcheck());
like image 542
Raj Pannala Avatar asked Mar 19 '26 12:03

Raj Pannala


1 Answers

  • DON'T mock the class you are trying to test.
  • DO mock the classes that interact with the class you are trying to test.

If you want to test that a field in a a class changes from false to true, what you really want to do is something like (I don't have your actual constructor, I'm just guessing):

SomeDependency dependency = mock(SomeDependency.class);

// Make a REAL ReferenceLettersBean
ReferenceLettersBean bean = new ReferenceLettersBean(dependency);

// now make your test
rf.checkForDuplicates("[email protected]","[email protected]","[email protected]");
assertEquals(true,rf.getBoolcheck());
like image 150
durron597 Avatar answered Mar 22 '26 00:03

durron597