简体   繁体   中英

How do I write unit test for a setter method which does not have a getter method?

I have a class which looks like this

public class Assignment {

   protected String AssName;

   public void SetAssSpec(String theSpec){

     this.AssSpec = theSpec;

   }

}

Here is my Testing class

class AssignmentTest {

   @Test
   void testSetAssSpec(){

       String assignmentName = "CSE101";
       Assignment cseAssigment = new Assignment();
       cseAssigment.SetAssSpec(String assignmentName);

       //Now what?

   }


} 

Since there is no getter method.
Another way to access the set String would be cseAssigment.AssName but the problem is the AssName is protected so I can not access it.
How would I test it? I am new to testing and Junit. So, please tell me if this even makes sense?

You can declare a local subclass which has a getter:

@Test
void testSetAssSpec(){
   class SubAssigment extends Assignment {
     String getter() { return AssName; }
   }

   String assignmentName = "CSE101";
   SubAssigment cseAssigment = new SubAssigment();
   cseAssigment.SetAssSpec(String assignmentName);

   assertEquals(assignmentName, cseAssignment.getter());
}

But, as Kayaman points out, you probably don't really need to test that Java assignment works.

The problem in this example is that it doesn't show how the value is used after it is being set. And that is the clue on how to test it.

If it isn't used, the setter is useless and should be removed as well.

It is protected, so I guess a subclass is using it. In that case, I would use the approach with the test subclass.

If it is used via reflection, I would also test it via reflection.

Testing getter methods would be overkill, but if you ever want to check/test the value of private variables in an object with out getters you can use reflection

Field f = obj.getClass().getDeclaredField("AssName"); //NoSuchFieldException
f.setAccessible(true);
String assignmentName = (String) f.get(obj); 

String assignmentName = "CSE101";
Assignment cseAssigment = new Assignment();
cseAssigment.SetAssSpec(String assignmentName);
assertEquals(AssSpec ,ReflectionTestUtils.getField(cseAssigment, "AssSpec"));

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