1

I'm trying to test void method that has boolean conditions inside with Junit

/** Method to create request */
public void createRequest(String name) {

  if (verifyName(name)) {
    testRepo.getRequest(name); // Void method from test repo
    demoRepo.testMethod(name); // Another void method from demo repo
  }
}

/** Validate name */
private boolean verifyName(String name) {

 return "Test".equals(name);
}

In this case, what is the best approach to test the void method when verifyName() returns true/false with JUnit ??

Expected Test Scenarios:

  1. verifyName() returns true --> assert or make sure the methods get executed.
  2. verifyName() return false --> assert or make sure the methods won't get executed.
Ramana
  • 1,692
  • 3
  • 18
  • 34
  • 1
    `return "Test".equals(name) ? true : false;`, you can just skip the `? true : false` – akuzminykh May 08 '20 at 02:42
  • Updated my post – Ramana May 08 '20 at 02:44
  • The goto tools for that are listed [here](https://www.baeldung.com/mockito-annotations). The most relevant tool here is probably [Mockito – Using Spies](https://www.baeldung.com/mockito-spy). You can spy on `testRepo` and `demoRepo` and check if they get called. Here is a question very similar to yours: [How to verify if method was called from other with same class by mockito](https://stackoverflow.com/questions/8755449/how-to-verify-if-method-was-called-from-other-with-same-class-by-mockito) – akuzminykh May 08 '20 at 02:46

2 Answers2

0

you can verify if some function is called or not based on the condition

try something like that

@Test
public void testValidName() {
    service.createRequest("Test");
    verify(testRepo, times(1)).getRequest();
    verify(demoRepo, times(1)). testMethod();
}
Khaled Ahmed
  • 1,074
  • 8
  • 21
  • 1
    They did not mention mocks/spies in their question and you did not mention it in your answer. If you are going to suggest a certain pattern or framework, you should call it out and explain how/why it should be used. – iraleigh May 09 '20 at 16:48
0

You can simply write two scenarios :

@Captor
private String ArgumentCaptor<String> nameCaptor;

@Test
public void testForValidName() {
    service.createRequest("Test");
    Mockito.verify(testRepo, Mockito.times(1)).getRequest(nameCaptor.capture());
    Mockito.verify(demoRepo, Mockito.times(1)).testMethod(nameCaptor.capture());
    List<String> capturedValues = nameCaptor.getValues();
    Assert.assertEquals("Test", capturedValues.get(0));
    Assert.assertEquals("Test", capturedValues.get(1));
}

@Test
public void testForInValidName() {
   service.createRequest("Test1");
   Mockito.verifyNoMoreInteractions(testRepo);
   Mockito.verifyNoMoreInteractions(demoRepo);
}