[JAVA] How to mock each case with PowerMock + Mockito1x

Overview

How to mock each case with Mockito 1x https://qiita.com/taka_22/items/0c13aacf6ffbc2c77970 Continued.

Premise

Mockito 1.10.19 PowerMock 1.7.3 JUnit 4.11 Java 1.8.0_151

Case

Handles cases where dependent objects are created with new, static methods, and private methods. Based on the previous pattern, we classified it into the following 12 patterns.

No pattern Return type of mock target method Mock range Mock operation
7 The class you want to mock is generated with new Other than void The entire Returns the specified return value
8 The class you want to mock is generated with new Other than void The entire Throw an exception
9 The class you want to mock is generated with new void The entire Throw an exception
10 Mock target is static method Other than void The entire Returns the specified return value
11 Mock target is static method Other than void The entire Throw an exception
12 Mock target is static method void The entire Throw an exception
13 Mock target is private method Other than void The entire Returns the specified return value
14 Mock target is private method Other than void The entire Throw an exception
15 Mock target is private method void The entire Throw an exception
16 Mock target is private method Other than void Only some methods Returns the specified return value
17 Mock target is private method Other than void Only some methods Throw an exception
18 Mock target is private method void Only some methods Throw an exception

Class created for testing

DateUtil.java import java.text.SimpleDateFormat; import java.util.Date; public class DateUtil { private Boolean flag; public static String getCurrentDate() { Date d = new Date(); return new SimpleDateFormat("yyyy/MM/dd").format(d); } public static void setCurrentDate(long currentTime) { Date d = new Date(); d.setTime(currentTime); } public String getYYYYMMDDStringWrapper(Date date) throws Exception { return getYYYYMMDDString(date); } private String getYYYYMMDDString(Date date) throws Exception { return new SimpleDateFormat("yyyyMMdd").format(date); } private void setFlag(Boolean flag) throws Exception { this.flag = flag; } }

How to write a test

How to write a test in PowerMock

  1. The methods used in Mockito, such as mock / spy / doThrow, must be dedicated to PowerMock.
  2. Specify PowerMockRunner with @RunWith
  3. Specify the mock target test with @PrepareForTest

import static org.powermock.api.mockito.PowerMockito.doThrow; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.spy; import static org.powermock.api.mockito.PowerMockito.whenNew;

@RunWith(PowerMockRunner.class) @PrepareForTest({ DateUtil.class }) public class PowerMockTest { ...

No.7 Makes whenNew return a mock of the object created by new.

/**

// Recording phase Date dateMocked = mock(Date.class); whenNew(Date.class).withNoArguments().thenReturn(dateMocked); when(dateMocked.getTime()).thenReturn(expected.getTime());

// Replay phase String strDate = DateUtil.getCurrentDate();

// Verification phase assertThat(strDate, is("2015/05/05")); }

No.8 /**

// Replay & Verification Phase try { DateUtil.getCurrentDate(); fail(); } catch (RuntimeException e) { assertThat(e.getMessage(), is("aaa")); } }

No.9 /**

// Replay & Verification Phase try { DateUtil.setCurrentDate(123456789L); fail(); } catch (RuntimeException e) { assertThat(e.getMessage(), is("bbb")); } }

No.10 Mock static methods with mockStatic.

/**

// Replay & Verification Phase assertThat(String.valueOf(true), is("false")); assertThat(String.valueOf(false), is("false")); }

No.11 /**

// Replay & Verification Phase try { String.valueOf(true); fail(); } catch (RuntimeException e) { assertThat(e.getMessage(), is("aaa")); } assertNull(String.valueOf(false)); }

No.12 /**

// Replay & Verification Phase try { DateUtil.setCurrentDate(12345L); fail(); } catch (RuntimeException e) { assertThat(e.getMessage(), is("bbb")); } }

No.13 Since it mock the whole, the mocked method is called directly by reflection.

/**

// Replay phase Method getYYYYMMDDStringMethod = DateUtil.class.getDeclaredMethod("getYYYYMMDDString", Date.class); getYYYYMMDDStringMethod.setAccessible(true); String actual = (String)getYYYYMMDDStringMethod.invoke(dateMocked, new Date());

// Verification phase assertThat(actual, is("12345678")); }

No.14 /**

// Replay & Verification Phase try { Method getYYYYMMDDStringMethod = DateUtil.class.getDeclaredMethod("getYYYYMMDDString", Date.class); getYYYYMMDDStringMethod.setAccessible(true); getYYYYMMDDStringMethod.invoke(dateMocked, new Date()); fail(); } catch (Exception e) { if (e instanceof InvocationTargetException) { InvocationTargetException ite = (InvocationTargetException) e; assertThat(ite.getTargetException().getMessage(), is("aaa")); } else { fail(); } } }

No.15 /**

// Replay & Verification Phase Method setFlagMethod = DateUtil.class.getDeclaredMethod("setFlag", Boolean.class); setFlagMethod.setAccessible(true); try { setFlagMethod.invoke(dateMocked, true); fail(); } catch (Exception e) { if (e instanceof InvocationTargetException) { InvocationTargetException ite = (InvocationTargetException) e; assertThat(ite.getTargetException().getMessage(), is("bbb")); } else { fail(); } } }

No.16 The only difference in how to mock is to use spy. The rest is the same as No.13-15. It doesn't mock everything, so you can test it via public methods. Of course, reflection is also possible. /**

// Replay phase String strDate = dateMocked.getYYYYMMDDStringWrapper(new Date());

// Verification phase assertThat(strDate, is("12345678")); }

No.17 /**

// Replay & Verification Phase try { dateMocked.getYYYYMMDDStringWrapper(new Date()); fail(); } catch (RuntimeException e) { assertThat(e.getMessage(), is("aaa")); } }

No.18 /**

// Replay & Verification Phase Method setFlagMethod = DateUtil.class.getDeclaredMethod("setFlag", Boolean.class); setFlagMethod.setAccessible(true); try { setFlagMethod.invoke(dateMocked, true); fail(); } catch (Exception e) { if (e instanceof InvocationTargetException) { InvocationTargetException ite = (InvocationTargetException) e; assertThat(ite.getTargetException().getMessage(), is("bbb")); } else { fail(); } } }

reference

Mockito http://site.mockito.org/ PowerMock https://github.com/powermock/powermock

Project confirmed to work

https://github.com/taka2/mockito-sample

How to mock each case with Mockito 1x

https://qiita.com/taka_22/items/0c13aacf6ffbc2c77970

Recommended Posts

How to mock each case with PowerMock + Mockito1x
How to mock each case with Mockito 1x
Mock Enums with PowerMock
How to mock a super method call in PowerMock
Mock static methods with PowerMock
How to number (number) with html.erb
Mock the constructor with PowerMock
How to update with activerecord-import
How to scroll horizontally with ScrollView
How to get started with slim
How to enclose any character with "~"
How to use mssql-tools with alpine
How to get along with Rails
How to start Camunda with Docker
How to adjustTextPosition with iOS Keyboard Extension
How to share files with Docker Toolbox
How to compile Java with VsCode & Ant
[Java] How to compare with equals method
[Android] How to deal with dark themes
How to use BootStrap with Play Framework
[Rails] How to use rails console with docker
How to switch thumbnail images with JavaScript
[Note] How to get started with Rspec
How to do API-based control with cancancan
How to achieve file download with Feign
How to update related models with accepts_nested_attributes_for
How to set JAVA_HOME with Maven appassembler-maven-plugin
How to implement TextInputLayout with validation function
How to handle sign-in errors with devise
How to delete data with foreign key
How to test private scope with JUnit
How to monitor nginx with docker-compose with datadog
How to deal with Precompiling assets failed.
How to achieve file upload with Feign
How to run Blazor (C #) with Docker
How to build Rails 6 environment with Docker
How to download Oracle JDK 8 rpm with curl
[Java] How to test for null with JUnit
How to execute and mock methods using JUnit
How to use MyBatis2 (iBatis) with Spring Boot 1.4 (Spring 4)
How to save to multiple tables with one input
How to test interrupts during Thread.sleep with JUnit
How to use built-in h2db with spring boot
How to search multiple columns with gem ransack
How to use Java framework with AWS Lambda! ??
[Swift] How to link the app with Firebase
How to create multiple pull-down menus with ActiveHash
Notes on how to use each JUnit Rule
How to use Java API with lambda expression
How to get started with Eclipse Micro Profile
How to give your image to someone with docker
How to insert all at once with MyBatis
How to monitor SPA site transitions with WKWebView
How to write test code with Basic authentication
[Rails] How to easily implement numbers with pull-down
How to build API with GraphQL and Rails
How to use nfs protocol version 2 with ubuntu 18.04
How to use docker compose with NVIDIA Jetson
How to get resource files out with spring-boot
How to create member variables with JPA Model
How to verify variable items with WireMock's RequestBodyMatching