Home > Net >  Junit string comparison failure
Junit string comparison failure

Time:11-24

This is the source code for the class that has to be tested. When i run the junit class it gives me two failures although the expected and actual output are identical why?

It is also true that both are strings, so that should not be an issue? I see in the junit console org.opentest4j.AssertionFailedError: expected: java.lang.String@4d5b6aac but was: ss.week2.Setting@3e84448c

    
    private ThreeWayLamp testLamp;
    
    @BeforeEach
    public void setUp() {
        testLamp = new ThreeWayLamp();
    }
    
    @Test
    public void testState() {
        assertEquals("OFF",testLamp.getStatus());
    }
    
    @Test
    public void testSequence() {
        testLamp.setNextStatus();
        assertEquals("LOW", testLamp.getStatus());
    }

} 
.............................................

    /**
     * @requires String userInput OFF,LOW,MEDIUM or HIGH
     * @ensures currentSetting=userInput
     * **/
    public void setStatus(String userInput) {
        if(userInput.equals("OFF")) {
            currentSetting=Setting.OFF;
        }       
        if(userInput.equals("LOW")) {
            System.out.println("Setting lamp to low");
            currentSetting=Setting.LOW;
        }
        if(userInput.equals("MEDIUM")) {
            currentSetting=Setting.MEDIUM;
        }
        if(userInput.equals("HIGH")) {
            currentSetting=Setting.HIGH;
        }
        

    
    public void setNextStatus() {
        switch(currentSetting) {
        case OFF:
            currentSetting=Setting.LOW;
            break;
        case LOW:
            currentSetting=Setting.MEDIUM;
            break;
        case MEDIUM:
            currentSetting=Setting.HIGH;
            break;
        case HIGH:
            currentSetting=Setting.OFF;
            break;
        }
        
        }
    }
    
    
    ```

CodePudding user response:

You don't show the code for getStatus() but the error message implies that it returns a Setting, not a String. Hence you need to do

assertEquals(Setting.OFF, testLamp.getStatus());
  •  Tags:  
  • java
  • Related