Mockito:如何测试构造函数是否被调用? [英] Mockito: how to test that a constructor was called?

查看:66
本文介绍了Mockito:如何测试构造函数是否被调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Mockito来测试Java应用程序中的方法.

I am using Mockito to test methods within my Java application.

如何测试构造函数被调用一次?

How can I test that a constructor was called once?

我正在尝试进行与此类似的验证:

I am trying to do a verification similar to this:

verify(myClass, times(1)).doSomething(anotherObject);

但是我无法验证构造函数是否被调用,因为它没有类似于例如的方法. doSomething().

But I can't verify that the constructor was called as it doesn't have a method similar to e.g. doSomething().

推荐答案

使用Mockito无法做到这一点,因为正在创建的对象不是模拟对象.这也意味着您也将无法验证该新对象上的任何东西.

This can't be done with Mockito, since the object being created is not a mocked object. This also means that you won't be able to verify anything on that new object either.

我过去通过使用 Factory 创建对象而不是对其进行更新来解决这种情况.然后,您可以模拟 Factory 以返回测试所需的对象.

I've worked around this scenario in the past by using a Factory to create the object rather than newing it up. You're then able to mock the Factory to return the object required for your test.

您是否乐意更改设计以适合您的测试取决于您!

Whether you're happy changing your design to suit your tests is up to you!

这篇关于Mockito:如何测试构造函数是否被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆