简体   繁体   中英

java Mockito verify abstract method

i have an issue on verifying a call to method of class under test, using the verify() method it tells that the call is not done to that method, this method is defined as abstract in super class (loadFile(String))

find bellow the code:

public abstract class FileParser {
public Iterator<String> loadFile(FileSettingsToSend fileSetting) {

        System.out.println("file before staged");
        try {
        if(!movFile("staged",fileSetting)) 
             return null;
        System.out.println("file after move "+fileSetting.getFile().getAbsolutePath());
        boolean isValidFormatFile = fileValidator.checkFileFormat(fileSetting);
        if (!isValidFormatFile) {
            System.out.println("file format is not valid");
            return null;
        }

            return readBlock(fileSetting);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        } finally {

        }

        //return null;
    }

    public abstract Iterator<String> readBlock(FileSettingsToSend fileSettingsToSend)
            throws JsonProcessingException, IOException;
}

public  class JsonFileParser extends FileParser {

    public final ObjectMapper mapper = new ObjectMapper();

    @Autowired
    public JsonFileParser(FileValidator jsonFileValidatorService, FileAttributeService fileAttributeService) {
        super(jsonFileValidatorService, fileAttributeService);
    }

    @Override
    public Iterator<String> readBlock(FileSettingsToSend fileSetting) throws JsonProcessingException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        System.out.println("inside readBlock json implementation");
        List<String> listAttribute = fileAttributeService.getAttributes(fileSetting.getDiretoryPath());
        String[] blocDelimitor = fileAttributeService.getDelimitorRepositpry(fileSetting.getDiretoryPath());
        System.out.println("after validator");
        final JsonNode root = mapper.readTree(fileSetting.getFile());
        if (root == null)
            return null;
        Iterator<JsonNode> nodeIterator = root.elements();
        System.out.println("Data is " + root);
        return new Iterator<String>() {
            JsonNode node;

            @Override
            public boolean hasNext() {

                return nodeIterator.hasNext();
            }

            @Override
            public String next() {
                int i = 0;
                node = nodeIterator.next();
                System.out.println("after nex " + node.toString());
                Arrays.stream(blocDelimitor).forEach(e -> {
                    node = node.path(e);
                    System.out.println("inside next " + node.toString());
                });
                String result = null;
                if (node.isArray()) {
                    System.out.println("It is Array");
                    for (JsonNode node1 : node) {

                        if (i != 0)
                            result = result + "," + listAttribute.stream().map(e -> e + "=" + node1.get(e))
                                    .collect(Collectors.joining(","));
                        else
                            result = listAttribute.stream().map(e -> e + "=" + node1.get(e))
                                    .collect(Collectors.joining(","));
                        i++;
                    }
                } else
                    result = listAttribute.stream().map(e -> e + "=" + node.get(e)).collect(Collectors.joining(","));
                return result;
            }

        };

    }

Test method is:

    @Mock
    FileValidator jsonFileValidatorService;
    @Mock
    FileAttributeService fileAttributeService;
    JsonFileParser jsonFileParserMock = new JsonFileParser(jsonFileValidatorService, fileAttributeService);

    @Test
    public void validatorNotTrue() throws JsonProcessingException, IOException{

        when(jsonFileValidatorService.checkFileFormat( anyObject() )).thenReturn(true);
        JsonFileParser jsonFileParser  = Mockito.spy(jsonFileParserMock);
        doReturn(true).when(jsonFileParser).movFile(anyString(),anyObject() );
        assertNull(jsonFileParser.loadFile(null));

        verify(jsonFileParser, times(1)).movFile(anyString(),anyObject());
        assertTrue(jsonFileParser.movFile(anyString(), anyObject()));
        assertTrue(jsonFileValidatorService.checkFileFormat( anyObject() ));

        //exception.expect(Exception.class);
        verify(jsonFileParser,times(1)).readBlock(anyObject();

    }

    @BeforeClass
    public static  void settingUp(){

    }

    @Before
    public void initMock(){
        MockitoAnnotations.initMocks(this);
    }

the line verify(jsonFileParser,times(1)).readBlock(anyObject(); return false; meaning that the method loadFile of jsonfileParser not called can you get your held to tell why it is not called. Thank you.

This happens because you initialize the mocks after you create a JsonFileParser . Note that @Before method is executed after all the fields of your test class are initialized.

As a result, you pass null dependencies to the class. The invocation to the null FileValidator throws NullPointerException , but you swallow it in your catch block.

Generally it is advisable to verify the arguments you pass to your constructors and methods, to fail fast in case of an error. For example, Java comes with a handy Objects::requireNonNull method to verify that the passed parameters are non-null.

Similarly it's generally a bad practice to swallow every single exception. For instance, in your example, you expect IOException and JsonProcessingException to be thrown. It's better to catch these explicitly and let the program crash (or at least log a warning) for any other one.

Finally, mocks and spies are prone to overuse. Usually, it's enough to use fakes - dummy implementations of your interfaces. Depending on how much control you have over the code, you may also want to refactor it to avoid using a spy at all. Using one in a code you may freely change may signal an architectural problem.

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