Not able to set value of instance variable of a class in Java while testing with JUnit

StackOverflow https://stackoverflow.com/questions/23561859

  •  18-07-2023
  •  | 
  •  

Question

I am trying to test my classes using JUnits and i am facing an issue below is code. There is a base class BaseMapper and TokenFraming which is dependent class. The getMappedValue() from the baseclass is calling the mapStates() in the derived class. I want to set the lineTokenizer instance variable in the TokenFraming class but it is not being set from the code. When i debug TokenFraming the lineTokenizer is always Null and i get a Null Pointer exception when i try to access the tokenize() method.

I tried setting the value of lineTokenizer by using the setLineTokenizer() but still its not getting set. Also tried to set the value using Reflection but that also does not work. Any ideas as to what i am doing wrong here and how i can correct it. any help would be great.

Class BaseMapper {

    private String fieldName;
    private String fieldvalue;

    // getters and setters

    public static String getMappedValue(){
        TokenFraming frame = new TokenFraming();
        frame.mapStates(fieldName,fieldName,"validate")
    }

}

 Class TokenFraming {

     private Tokenizer lineTokenizer = null;

     public void setLineTokenizer(LineTokenizer arg) {
         this.lineTokenizer = arg;
     }

     public String mapStates(String fieldName, String fieldName, String line) {
         FieldMappedRow values = this.lineTokenizer.tokenize(line);// NullPointerException here
     .......
     .......
     }
}

JUNit method

@Test
public void testMethods() {
    TokenFraming framing = null;
    try {
        //using reflection to set is not working
        framing = new TokenFraming();
        Class<?> c1 = framing.getClass();
        Field config = c1.getDeclaredField("lineTokenizer ");
        config.setAccessible(true);
        config.set(framing, new DefaulltToknizer());

        //setting with a setter is also not working
        framing.setLineTokenizer(new DefaulltToknizer());

        BaseMapper mapped = new BaseMapper();
        String value = mapped.getMappedValue();
    } catch (Exception e) {
       message = e.getMessage();
    }       
    Assert.assertNotSame(null, message);
}
Was it helpful?

Solution

The BaseMapper class creates a new instance of TokenFraming - this is not the same instance of TokenFraming that you create in your test.

You should pass the TokenFraming object as an argument:

 public static String getMappedValue(TokenFraming frame) {
     frame.mapStates(fieldName,fieldName,"validate");
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top