IanUnderhill
IanUnderhill
Reputation Top 5%
Ian Underhill
2 Snippets  (264th place)
Published
1 Channel
Created
1 Channel
Following
8 hours ago
Last Visit
Sep 20, 2016
Registered
56 points  (365th place)
Reputation
Junior Code Generator
Junior Autobiographer
Senior Autobiographer

Recent Snippets See all snippets by IanUnderhill

public by IanUnderhill created May 16, 2017  36  2  1  0

lazy singleton

public final class Singleton {
    private static volatile Singleton INSTANCE = null;

    private Singleton() {// singleton instance}

    /**
     * @return the single instance of the class
     */
    public static Singleton getInstance() {
        if (INSTANCE == null) {
            synchronized(Singleton.class) {
                if (INSTANCE == null) {
                    INSTANCE = new Singleton();
                }
            }
        }
        return INSTANCE;
    }
}                                    
;

public by IanUnderhill created Sep 20, 2016  722  0  3  0

Powermock - mocking static methods

shows how to mock a static method, using powermock
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

import java.io.IOException;
import java.nio.channels.SocketChannel;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;


/**
 * I test that mocking static methods works correctly
 *
 * @author Ian Underhill
 * @created 20 Sep 2016
 */
@RunWith(PowerMockRunner.class)
@PrepareForTest({ SocketChannel.class })
public class StaticMethodsUnitTest {

    private boolean worked = false;

    @Test
    public void shouldBeAbleToMockStaticMethods() throws IOException {
        givenASocket();
        whenOpened();
        thenItWorked();
    }

    @SuppressWarnings("boxing")
    private void thenItWorked() {
        assertThat(this.worked, is(true));
    }

    private void whenOpened() throws IOException {
        SocketChannel.open();
    }

    private void givenASocket() {
        PowerMockito.mockStatic(SocketChannel.class, invocation -> {
            this.worked = true;
            return null;
        });
    }
}
                        
;