2

There is great debate about whether or not setters/getters should be unit tested.

Example Should unit tests be written for getter and setters?

I believe that builder objects fall within the same conversation. I want to know best practices for unit testing a builder object. Here are my thoughts.

i. confirm that builder object can be created

ii. confirm that output reflects input

iii. confirm that omitted constructs will throw exception (if they are required)

Additionally, if the builder object is required for instantiating another object, does it make sense to also create a test to confirm that the second object instantiates with given builder? Any critiques on what I am missing or should omit is appreciated.

@RunWith(AndroidJUnit4.class)
public class MyBuilderTest {

    private Context mContext;
    private ApiClient mApiClient;
    private Profile mProfileBuilder;
    private ProfilePojo mProfileSampleResponse;

    @Before
    public void setUp() {
        mContext = InstrumentationRegistry.getTargetContext();
        mProfileSampleResponse= new Gson().fromJson(Utils.getLocalJsonFile(mContext,
                R.raw.profile_info), ProfilePojo.class);
    }

    @Test
    public void checkLocalProfileResponse() {
        assertNotNull(mProfileSampleResponse);
    }

    @Test
    public void checkProfileBuilder() {
        mProfileBuilder  = new Profile.ProfileBuilder()
                .setFirstName(mProfileSampleResponse.firstName)
                .setLastName(mProfileSampleResponse.lastName)
                .isVerified(mProfileSampleResponse.isVerified)
                .create();

        assertNotNull(mProfileBuilder);
        assertNotNull(mProfileBuilder.getFirstName());
        assertNotNull(mProfileBuilder.getLastName());

        assertEquals(mProfileSampleResponse.isVerified, mProfileBuilder.getIsVerified);
        assertEquals(mProfileSampleResponse.firstName, mProfileBuilder.getFirstName);
        assertEquals(mProfileSampleResponse.lastName, mProfileBuilder.getLastName);
    }

    @Test
    public void checkApiClientBuilder() {
        mApiClient= new ApiClient(mContext, mProfileBuilder);

        assertNotNull(mApiClient);
    }

}

In my case, I also need to test request and responses. The profile information I build with the ProfileBuilder can be passed into the ApiClient and the ApiClient will make request for me. Should all of this be inside of one test class?

portfoliobuilder
  • 7,556
  • 14
  • 76
  • 136

0 Answers0