简体   繁体   中英

Calling a private static void method

I have a private static void method namely convertToIp in the class EllaDtoConverter that has a private constructor. If I try to create an instance of the class, it throws an exception. The code is provided,

public final class EllaDtoConverter {

    private EllaDtoConverter() {
        throw new PrivateConstructorException();
    }

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

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

    // ..... some code 
}

I can create the instances of the IrisBo and the EllaRequestDto and pass inside the method. Do I have an option to call the convertToIp method outside from another class (even with using the reflection)?

From the junit tag I assume you want to know if it is possible to test the method.

I suggest you this article which basically says that you shouldn't be testing private methods (static or not doesn't really matter) on their own.

The main idea is that unit testing should test the contract that your module is exposing, assuring that whoever calls you get what it expects from you, and private methods are not part of the contract.

As @bracco23 written before, you should read an article about testing private methods. However, if you have already decided to do it (despiting all this negative aspects which comes with testing them), there is a special framework called PowerMockito . PowerMockito allows us to test private or static methods.

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