使用 mockito 或 Jmockit 模拟私有静态最终字段
Mock private static final field using mockito or Jmockit
我在 class 中使用 private static final LOGGER 字段,我想要 LOGGER.isInfoEnabled() return false 的方法。
如何使用 mockito 或 jMockit
模拟静态最终字段
我的class是:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Class1 {
private static final Logger LOGGER = LoggerFactory.getLogger(Class1.class);
public boolean demoMethod() {
System.out.println("Demo started");
if (LOGGER.isInfoEnabled()) {
System.out.println("@@@@@@@@@@@@@@ ------- info is enabled");
} else {
System.out.println("info is disabled");
}
return LOGGER.isInfoEnabled();
}
}
它的单位是:
import mockit.Mocked;
import mockit.NonStrictExpectations;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.slf4j.Logger;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
import com.source.Class1;
public class MyTest {
@InjectMocks
Class1 cls1;
@BeforeMethod
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
@Test
public void test(@Mocked final Logger LOGGER) {
new NonStrictExpectations() {
{
LOGGER.isInfoEnabled();
result = false;
}
};
assertFalse(cls1.demoMethod());
}
}
当我 运行 结果是:
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.test.MyTest
Configuring TestNG with: TestNG652Configurator
Demo started
@@@@@@@@@@@@@@ ------- info is enabled
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 1.9 sec <<< FAILURE! - in com.test.MyTest
test(com.test.MyTest) Time elapsed: 0.168 sec <<< FAILURE!
java.lang.AssertionError: expected [false] but found [true]
at com.test.MyTest.test(MyTest.java:35)
Results :
Failed tests:
MyTest.test:35 expected [false] but found [true]
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 9.899s
[INFO] Finished at: Mon Jun 08 12:35:36 IST 2015
[INFO] Final Memory: 16M/166M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.18.1:test (default-test) on project JMockDemo: The
re are test failures.
[ERROR]
[ERROR] Please refer to D:\perfoce_code\workspace_kepler\JMockDemo\target\surefire-reports for the individual test results.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
我是 jmockit 的新手,我希望我的上述 junit 案例能够 运行 成功。
而且我必须使用 JMockit 或 mockito,不能使用 Powermockito。
请帮忙。
我认为 mockito 或 jMockit 不能模拟 static final 类,因为它们试图在单元测试时覆盖方法。但是,powerMockito 可以,因为它使用反射并模拟静态最终 class/methods.
一种方法是使用反射从字段中删除 final
修饰符,然后将 LOGGER
字段替换为 Mocked one
public class Class1Test {
@Test
public void test() throws Exception {
Logger logger = Mockito.mock(Logger.class);
Mockito.when(logger.isInfoEnabled()).thenReturn(false);
setFinalStatic(Class1.class.getDeclaredField("LOGGER"), logger);
Class1 cls1 = new Class1();
assertFalse(cls1.demoMethod());
}
static void setFinalStatic(Field field, Object newValue) throws Exception {
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newValue);
}
}
将参数中的“@Mocked Logger”更改为“@Capturing Logger”使其工作。喜欢
@Test
public void test(@Capturing final Logger LOGGER) {
new NonStrictExpectations() {
{
LOGGER.isInfoEnabled();
result = false;
}
};
assertFalse(cls1.demoMethod());
}
接受的解决方案不适用于JDK 12。原因可见。
使用 PowerMockito 很容易做到这一点(使用 2.0.9 版测试)。您可以使用Whitebox.setInternalState方法为您完成。
示例:
Whitebox.setInternalState(MyTestClass.class, "myCar", carMock);
MyTestClass 是包含字段的 class。
myCar是字段的变量名
carMock 是你想要传递的一些模拟。
我在 class 中使用 private static final LOGGER 字段,我想要 LOGGER.isInfoEnabled() return false 的方法。 如何使用 mockito 或 jMockit
模拟静态最终字段我的class是:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Class1 {
private static final Logger LOGGER = LoggerFactory.getLogger(Class1.class);
public boolean demoMethod() {
System.out.println("Demo started");
if (LOGGER.isInfoEnabled()) {
System.out.println("@@@@@@@@@@@@@@ ------- info is enabled");
} else {
System.out.println("info is disabled");
}
return LOGGER.isInfoEnabled();
}
}
它的单位是:
import mockit.Mocked;
import mockit.NonStrictExpectations;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.slf4j.Logger;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
import com.source.Class1;
public class MyTest {
@InjectMocks
Class1 cls1;
@BeforeMethod
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
@Test
public void test(@Mocked final Logger LOGGER) {
new NonStrictExpectations() {
{
LOGGER.isInfoEnabled();
result = false;
}
};
assertFalse(cls1.demoMethod());
}
}
当我 运行 结果是:
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.test.MyTest
Configuring TestNG with: TestNG652Configurator
Demo started
@@@@@@@@@@@@@@ ------- info is enabled
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 1.9 sec <<< FAILURE! - in com.test.MyTest
test(com.test.MyTest) Time elapsed: 0.168 sec <<< FAILURE!
java.lang.AssertionError: expected [false] but found [true]
at com.test.MyTest.test(MyTest.java:35)
Results :
Failed tests:
MyTest.test:35 expected [false] but found [true]
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 9.899s
[INFO] Finished at: Mon Jun 08 12:35:36 IST 2015
[INFO] Final Memory: 16M/166M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.18.1:test (default-test) on project JMockDemo: The
re are test failures.
[ERROR]
[ERROR] Please refer to D:\perfoce_code\workspace_kepler\JMockDemo\target\surefire-reports for the individual test results.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
我是 jmockit 的新手,我希望我的上述 junit 案例能够 运行 成功。 而且我必须使用 JMockit 或 mockito,不能使用 Powermockito。 请帮忙。
我认为 mockito 或 jMockit 不能模拟 static final 类,因为它们试图在单元测试时覆盖方法。但是,powerMockito 可以,因为它使用反射并模拟静态最终 class/methods.
一种方法是使用反射从字段中删除 final
修饰符,然后将 LOGGER
字段替换为 Mocked one
public class Class1Test {
@Test
public void test() throws Exception {
Logger logger = Mockito.mock(Logger.class);
Mockito.when(logger.isInfoEnabled()).thenReturn(false);
setFinalStatic(Class1.class.getDeclaredField("LOGGER"), logger);
Class1 cls1 = new Class1();
assertFalse(cls1.demoMethod());
}
static void setFinalStatic(Field field, Object newValue) throws Exception {
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newValue);
}
}
将参数中的“@Mocked Logger”更改为“@Capturing Logger”使其工作。喜欢
@Test
public void test(@Capturing final Logger LOGGER) {
new NonStrictExpectations() {
{
LOGGER.isInfoEnabled();
result = false;
}
};
assertFalse(cls1.demoMethod());
}
接受的解决方案不适用于JDK 12。原因可见
使用 PowerMockito 很容易做到这一点(使用 2.0.9 版测试)。您可以使用Whitebox.setInternalState方法为您完成。
示例:
Whitebox.setInternalState(MyTestClass.class, "myCar", carMock);
MyTestClass 是包含字段的 class。
myCar是字段的变量名
carMock 是你想要传递的一些模拟。