如何在Junit 5中检查模拟的对象是否有空状态?

发布于 2025-02-13 13:15:43 字数 257 浏览 1 评论 0原文

如果我有一个在服务层中的对象,

@Autowired
private Config appConfig;
.
.
.
if(appConfig == null)
    //check configuration

则通过模拟对象编写的junit。

@Mock
private Config appConfig;

如何使该对象在JUNIT中为Nult以涵盖测试案例中的条件?

If I have an object as below in service layer

@Autowired
private Config appConfig;
.
.
.
if(appConfig == null)
    //check configuration

JUnit written by mocking the object.

@Mock
private Config appConfig;

How to make that object to null in JUnit to cover that condition in test case?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

遇到 2025-02-20 13:15:43

您可以做类似的事情:

@Mock
private Config appConfig;


@Test
public void nullTest(){
 appConfig = Mockito.nullable(Config.class);
 System.out.println(appConfig == null ? "null" : "notNull");
  ..
}

这将显示null作为输出。

You can do something like :

@Mock
private Config appConfig;


@Test
public void nullTest(){
 appConfig = Mockito.nullable(Config.class);
 System.out.println(appConfig == null ? "null" : "notNull");
  ..
}

This displays null as output.

寂寞清仓 2025-02-20 13:15:43

对于null,您根本不需要模拟。为什么不只是将null值传递到测试方法中,而不是appconfig字段?

For null you don't need a mock at all. Why don't you just pass in the null value into the method to test, instead of your appConfig field?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文