Raj Pannala
Raj Pannala

Reputation: 67

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:

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());

Upvotes: 3

Views: 347

Answers (2)

durron597
durron597

Reputation: 32323

  • 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());

Upvotes: 1

Waters
Waters

Reputation: 363

This boolean value seems to be an internal state. This is not something you can directly test with unit tests unless you make it public or it is detectable by influencing the behavior of another method.

Upvotes: 0

Related Questions