简体   繁体   中英

Test a method using the org.springframework.test.util.ReflectionTestUtils

I have a class method that I would like test

public class EllaDtoConverter {


    private static void convertToIp( final IrisBo irisBo, EllaRequestDto request ) {

        if( nonNull( irisBo.getDevice() ) ) {
            request.setIp( irisBo.getDevice().getIpAddress() );
        }
    }
}

My test is provided

@Test
public void testConvertToIp() {

    assertNotNull( validIrisBo.getDevice() );
    assertNotNull( validIrisBo.getDevice().getIpAddress() );

    EllaRequestDto ellaRequestDto = new EllaRequestDto();

    ReflectionTestUtils.invokeMethod( ellaRequestDto, "setIp", validIrisBo.getDevice().getIpAddress() );
}

Does it okay to leave it like this or I have a better option to test?

If writing a separate test for private method increases the confidence in the code than it should not be a private method. private methods are implementation details and should be tested through the interface of the class.

In case you don't want to extract this private method to make it visible eg as a separate class, you can use the default visibility modifier to at least avoid Java reflection:

public class EllaDtoConverter {
    static void convertToIp( final IrisBo irisBo, EllaRequestDto request ) {
        ...
    }
}

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