IanUnderhill
IanUnderhill
Reputation Top 5%
Ian Underhill
2 Snippets  (263rd place)
Published
1 Channel
Created
1 Channel
Following
May 23, 2017
Last Visit
Sep 20, 2016
Registered
56 points  (373rd place)
Reputation
Junior Code Generator
Junior Popular Coder
Junior Autobiographer
Senior Autobiographer
Junior Wise Coder

Recent Snippets See all snippets by IanUnderhill

public by IanUnderhill created May 16, 2017  219  15  3  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  8060  0  4  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;
        });
    }
}
                        
;