@Component
public class MyBean {
public void fun() {
System.out.println("my bean fun");
}
}
@Component
public class StaticBean {
private static MyBean myBean;
public static void fun() {
myBean.fun();
}
@Autowired
public void setMyBean(MyBean myBean) {
StaticBean.myBean = myBean;
}
}
方法一:new一个实例去修改类中的静态变量
静态变量是类级别的共享数据
@SpringBootTest
public class MyStaticTest extends AbstractTestNGSpringContextTests {
@Mock
private MyBean myBean; // Mock 对象
@Autowired
private StaticBean staticBean;
@BeforeClass
public void init() throws NoSuchFieldException, IllegalAccessException {
MockitoAnnotations.openMocks(this); // 初始化 @Mock
// 方法一:通过new一个实例去修改类的静态变量
StaticBean staticBean = new StaticBean();
staticBean.setMyBean(myBean);
}
@Test
public void testStaticFun() {
// 设置 mock 行为
Mockito.doAnswer(invocation -> {
System.out.println("Mocked myInterface fun called!");
return null; // void 方法返回 null
}).when(myBean).fun();
// 调用 StaticBean 的静态方法
StaticBean.fun();
// 验证调用
Mockito.verify(myBean, Mockito.times(1)).fun();
}
}
方法二:通过spring中的实例去修改类的静态变量
@SpringBootTest
public class MyStaticTest extends AbstractTestNGSpringContextTests {
@Mock
private MyBean myBean; // Mock 对象
@Autowired
private StaticBean staticBean;
@BeforeClass
public void init() throws NoSuchFieldException, IllegalAccessException {
MockitoAnnotations.openMocks(this); // 初始化 @Mock
// 方法二:通过spring中的实例去修改类的静态变量
staticBean.setMyBean(myBean);
}
@Test
public void testStaticFun() {
// 设置 mock 行为
Mockito.doAnswer(invocation -> {
System.out.println("Mocked myInterface fun called!");
return null; // void 方法返回 null
}).when(myBean).fun();
// 调用 StaticBean 的静态方法
StaticBean.fun();
// 验证调用
Mockito.verify(myBean, Mockito.times(1)).fun();
}
}
方法三:反射
@SpringBootTest
public class MyStaticTest extends AbstractTestNGSpringContextTests {
@Mock
private MyBean myBean; // Mock 对象
@Autowired
private StaticBean staticBean;
@BeforeClass
public void init() throws NoSuchFieldException, IllegalAccessException {
MockitoAnnotations.openMocks(this); // 初始化 @Mock
// 方法三:反射
Field field = StaticBean.class.getDeclaredField("myBean");
field.setAccessible(true);
field.set(null, myBean);
}
@Test
public void testStaticFun() {
// 设置 mock 行为
Mockito.doAnswer(invocation -> {
System.out.println("Mocked myInterface fun called!");
return null; // void 方法返回 null
}).when(myBean).fun();
// 调用 StaticBean 的静态方法
StaticBean.fun();
// 验证调用
Mockito.verify(myBean, Mockito.times(1)).fun();
}
}