Search code examples
javajunitmockitopowermockito

How to mock com.google.inject.Binder and org.yaml.snakeyaml.Yaml?


According to my requirement I have to increase my code coverage to 80% I some how reached up to 71% but 30% of code is written in main class and the YAML config loader class. Can anyone tell me how to write test cases for following methods:-

private String configFilePath;

    private Optional<ItemMasterFileProcessorConfiguration> config;

    public ItemMasterFileProcessorTaskModule(String configFilePath)
    {
        this.configFilePath = configFilePath;
        config = Optional.empty();
    }

    @Override
    public void configure(Binder binder)
    {
        binder.bind(<Interface>.class).to(<ImplClass>.class);
        binder.bind(<Interface>.class).to(<ImplClass>.class);
    }

    @Provides
    public ItemMasterFileProcessorConfiguration getConfig() throws ItemMasterFileProcessorException
    {
        Yaml yaml = new Yaml();

        try
        {
            if (!config.isPresent())
            {
                ItemMasterFileProcessorConfiguration writerConfig = yaml.loadAs(ItemMasterFileProcessorConfiguration.class.getClassLoader().getResourceAsStream(configFilePath), ItemMasterFileProcessorConfiguration.class);
                config = Optional.of(writerConfig);
            }
            /*
             * Sonar is wanting is to add isPresent() before this But if I do
             * Sonar complains that it will always evaluate to TRUE
             */
            return config.get();
        }
        catch (Exception e)
        {
            throw new ItemMasterFileProcessorException("Config is NULL while initializing configuration for config path : {}", e);
        }
    }

Solution

  • If you create a temp file with valid config I don't see any issues in testing your class. You can use TemporaryFolder from JUnit to create temp files and some IOUtils to write config in yaml format into the file.

    The following example is from official org.junit.rules.TemporaryFolder javadoc

     public static class HasTempFolder {
      @Rule
      public TemporaryFolder folder= new TemporaryFolder();
    
      @Test
      public void testUsingTempFolder() throws IOException {
          File createdFile= folder.newFile("myfile.txt");
          File createdFolder= folder.newFolder("subfolder");
          // ...
         }
     }