Disable static initializer in PowerMock

table of contents

  1. Procedure for building an environment for using PowerMock
  2. Mock and Spy in PowerMock
  3. Mock static methods with PowerMock
  4. Mock the constructor with PowerMock
  5. Mock private methods with PowerMock
  6. Try using WhiteBox of PowerMock
  7. Disable static initializer in PowerMock ← Now here

Overview

PowerMock is provided with the annotation @SuppressStaticInitializationFor to disable the static initializer.

Example of use

Mocking class

When the class is loaded, the static initializer sets the field to the string "value".

Here, we have prepared a judge method that returns true if the field is set to "value" and false otherwise.

SampleEm.java


public class SampleEm {
	
	private static String field = null;
	
	static {
		field = "value";
	}
	
	public boolean judge() {
		return "value".equals(field);
	}
}

Test class

To use PowerMock with JUnit, specify PowerMockRunner for @RunWith.

For @PrepareForTest, specify the class to mock.

I also specify a class to mock in @SuppressStaticInitializationFor, but be aware that it is not@SuppressStaticInitializationFor (SampleEm.class).

@RunWith(PowerMockRunner.class)
@PrepareForTest(SampleEm.class)
@SuppressStaticInitializationFor("jp.co.sample_powermock.staticinitializer.SampleEm")
public class SampleEmTest {

	@Test
	public void test() throws Exception {
		//Run
		SampleEm em = new SampleEm();
		boolean result = em.judge();

		//Check the result
		assertFalse(result);
	}
}

When I run the test, this JUnit succeeds because the static initializer is disabled and the field is not set to "value".

Recommended Posts

Disable static initializer in PowerMock
Disable turbolinks in Rails
Disable IPv6 in CentOS8
Mock static methods with PowerMock
Mock static methods in Mockito 3.4
Disable display when not logged in