Search code examples
javaunit-testinginner-classes

How to Unit Test a class with a nested static class in java?


I have to write a unit test for this class that contains a nested static class. I don't know how to initialize the class variable "mUri" of "_Deferred" to make an assertion that it is not null.

public class _Deferred {

    @SerializedName("uri")
    private String mUri;

    public String getUri() {
        return mUri;
    }

    public static class Builder {

        private String mUri;

        public _Deferred.Builder withUri(String uri) {
            mUri = uri;
            return this;
        }

        public _Deferred build() {
            _Deferred _Deferred = new _Deferred();
            _Deferred.mUri = mUri;
            return _Deferred;
        }
    }
}

Any help on how to initialize "mUri" is appreciated.

What I tried is:

@Test
public void testGetUriNotNull() {

    //preparations
    _deferred = new _Deferred();
    _Deferred.Builder builder = new _Deferred.Builder();

}

But then i don't know how to set "mUri".


Solution

  • Just invoke the Builder method 0n _Deferred class with desired value for mUri field

    public class StackOverflow {
    
        @Test
        public void deferredTest(){
            _Deferred deferred = new _Deferred.Builder().withUri("some_uri").build();
            Assertions.assertNotNull(deferred.getUri());
        }
    }
    

    And test will pass successfully .

    enter image description here