简体   繁体   中英

Why do we throw exceptions and assert it throws exceptions using junit 4 + mockito

I am learning mockito and unit testing.This is my constructor. To test the constructor that it throws jparse exceptions, I have a test method. Why do we generate our own exception and assert it. How is it testing? What are we testing here? Please help!

public ClassA(File file) throws JsonParseException,
        JsonMappingException, IOException {
    ObjectMapper json= new ObjectMapper();
    Map<String, String>> readValue= mapper.readValue(file,
            Map.class);
    ..........
}

@Test(expected = JsonParseException.class)
public void testCorruotionInContent() throws Exception {
    ObjectMapper json= Mockito.mock(ObjectMapper.class);
    PowerMockito.whenNew(ObjectMapper.class).withNoArguments()
            .thenReturn(json);
    Mockito.when(
            mapper.readValue(Mockito.any(File.class), Mockito.eq(Map.class)))
            .thenThrow(new JsonParseException(null, null));
    new ClassA(Mockito.mock(File.class));
}

Your test is fragile - as pointed out in comments, you're not testing anything about a concrete implementation, but rather the mock. I'm not even convinced you're testing anything at all.

Remember: you assert against concrete data; you mock what you absolutely need to .

Given that I don't know the full implementation of Constructor , I don't know what it'd take to cause it to fail. I do know, however, there are at least three conditions in which it would fail:

  • Some kind of IOException - likely the file doesn't exist or can't be read
  • Some kind of JsonMappingException - the object can't be mapped to JSON
  • Some kind of JsonParseException - the JSON entity can't be parsed

It is good practice to test all of these conditions, to ensure that your code behaves appropriately when any of these exceptions come up. If you don't expect your code to handle it, then it is acceptable for it to throw these exceptions, and when such a situation occurs in your code, you are verifying that the exception was actually thrown.

But how do we get to that? Let's start off simple.

Suppose we mocked out the instance of the File , and whenever/wherever we decided to read it, we'd get back a string of invalid JSON. That would be a sufficient case to test against - we can't create a file on the host file system (not worth the headache to spin up different files, so simply mocking them out would be acceptable), but we can dictate the data coming from the file.

(In the time I've written this answer, you've changed the class name from Constructor to Class . That's not going to fly - there's already a Class object.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM