-2

How to test an exception in the run function?

 `    public void run() {
     ArrayBlockingQueue<String> bookQueue = 
     library.getBookQueue(book);
     try {
        bookQueue.take();
        try {
            updateState(State.IN_PROGRESS);
            Thread.sleep(READ_TIME_MS);
            bookQueue.put(book);
            updateState(State.ENDED);
        } catch(InterruptedException e){
            bookQueue.put(book);
        }
    } catch(InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    finally {
        updateState(State.ENDED);
    }
   }`
kompil
  • 21
  • 1
  • 4
  • 1
    It is extremely unclear what you are asking for. What kind of exceptions? What kind of previous research did you do, regarding mocking frameworks? What tests did you yourself come up with? – GhostCat May 04 '19 at 17:18
  • Possible duplicate: https://stackoverflow.com/questions/156503/how-do-you-assert-that-a-certain-exception-is-thrown-in-junit-4-tests – Progman May 04 '19 at 20:22

1 Answers1

1

In the @Test annotation you can specify the expected exception

For Example

@Test(expected=IndexOutOfBoundsException.class) 
 public void outOfBounds() {
   new ArrayList<Object>().get(1);
}

In the same way you can write test method and call run method inside of it

@Test(expected=Exception.class) 
 public void testRun() {
   run();
}

We can also make this better by considering the @GhostCatsuggestions in the comments, you can addtry-catch` in test method

@Test
 public void testRun() {
    tyr {
       run();
      Asserts.fail(); // 
      }
     catch(Exception ex) {
      assertTrue(//some condition);
      assertEquals(//some condition);
     }
 }

If run() method doesn't throw any exception test will fail because of Asserts.fail(), or in any exception case catch block assert statements will get executed

Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
  • updated thank you sir for suggestion and guiding me, i need to learn a lot @GhostCat – Ryuzaki L May 04 '19 at 18:33
  • To make perfectly perfect, you could assert something on that ex the catch block caught. That is the major point here : that you can check more about that exception from the production code than it's class. – GhostCat May 04 '19 at 19:22