JUnit test for setter method Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of JUnit test for setter method without wasting too much if your time.

The question is published on by Tutorial Guruji team.

    public class Room extends java.lang.Object implements java.io.Serializable {

            public String description;
            public Map<String, Room> map;
            public List<Thing> things;

            //Room
            //Parameters:
            //desc - Description for the room Note: any newlines in desc will be 
            replaced with *

            public Room(java.lang.String desc){
                this.description = desc;
            }
            //getDescription
            //A description of the room
            //Returns:
            //Description

            public java.lang.String getDescription(){
                return description;
            }
            //replaceLine
            //any new line in s will be replaced with *

            public String replaceLine(String s){
                return s.replace("n", "*");
            }

            //setDescription
            //Change Room description Note: any newlines in s will be 
            //replaced with *
            //Parameters:
            //s - new Description

            public void setDescription(java.lang.String s){
                    this.description = replaceLine(s);
            }
}

I am trying to write a Junit test for the last method:

@Test
    public void setDescription(java.lang.String s) {
        String input = "abcn";
        String expected = "abc";
        setDescription(input);
        assertEquals(expected, input);
    }

I know that it is not correct but I have no idea how to fix it. I am pretty new to Java and coding as a whole. Could someone please help me with this?

Answer

Here is your test:

@Test
  public void testSetDescription() {
    Room instance = new Room("test");
    instance.setDescription("abcn");
    assertEquals("abc*", instance.getDescription());
  }

The assertEquals method is oveloaded and can be used in many ways. In this case we set in first place the expectation an on the second place what we really have (actual data) from the object. But in real life, most useful test is a test which check only single method, but in your case you call for one method but actually test other method. In real project you shouldn’t test getters and setters. Only business logic, because if you’ll test each method you will newer have time for main code.

We are here to answer your question about JUnit test for setter method - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji