mardi 15 septembre 2020

JUnit Test with Mockito won't throw JSONException

I'm currently struggling with getting my test to work.

I have a method a:

public void a(String test){
   b(test);
}

method b:

private void b(String test){
 try{
   JSONObject jsonObject=c(test);
   System.out.println(jsonObject.toString());
 } catch (JSONException e) {
   System.out.println(e.getMessage());
 }

and method c, which generates the JSONObject:

private JSONObject c(String test) throws JSONException{
  return new JSONObject().put("test",test);
}

I want to trigger the JSONException, but for some reason it won't. This is my code so far:

  @Test
  void aTest(){
    ByteArrayOutputStream outContent = new ByteArrayOutputStream();
    System.setOut(new PrintStream(outContent));

    TestClass testClass=new TestClass(this.getClass().getName());

    JSONObject jsonObject = Mockito.mock(JSONObject.class);
    Mockito.when(jsonObject.put(anyString(),anyString())).thenThrow(new JSONException("MalformedJSON"));



    testClass.a("Test");

    assertTrue(outContent.toString().contains("MalformedJSON"));

  }

I want the exception to be printed to the console, it works with other methods, but not for the JSONException. Always telling me that the Assertion is false. What am I missing?

Thanks in advance

Aucun commentaire:

Enregistrer un commentaire