gpt4 book ai didi

java - 为什么反射 api 在测试用例中不起作用

转载 作者:行者123 更新时间:2023-12-01 18:30:55 25 4
gpt4 key购买 nike

我正在尝试使用 java 反射 api 从我的测试类访问主类变量,但我遇到了如下异常,有人可以指导我吗

主类

package com.example.microservice.controller;

public class PrivateStatic {

public void process() {
String message = "data";
if (message != null && message.equalsIgnoreCase("data")) {
System.out.println("print message"+message);
} else {
System.out.println("empty message"+message);
}
}

}

测试类

package com.example.microservice.controller;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class PrivateStaticTest {

@InjectMocks
PrivateStatic private_Static;

@Test
public void processTest() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {

final java.lang.reflect.Field field = private_Static.getClass().getDeclaredField("message");
final boolean origionalValue = field.isAccessible();
field.setAccessible(true);
field.set(private_Static, "data");
field.setAccessible(origionalValue);
private_Static.process();
}

}

异常

java.lang.NoSuchFieldException: message
at java.lang.Class.getDeclaredField(Class.java:2070)
at com.example.microservice.controller.PrivateStaticTest.processTest(PrivateStaticTest.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:675)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)

最佳答案

public class PrivateStatic {
private String message = "data";

public void process() {
if (message != null && message.equalsIgnoreCase("data")) {
System.out.println("print message"+message);
} else {
System.out.println("empty message"+message);
}
}
}

将“消息”设为类字段也可以使用 ReflectionTestUtils.setField(private_Static, "message", "data");

关于java - 为什么反射 api 在测试用例中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60167234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com