简体   繁体   English

如何在 Mockito 的方法内模拟“新”创建的对象

[英]How to mock "new" created objects inside a method in Mockito

I have a legacy code where the code looks like below:我有一个遗留代码,代码如下所示:

public String getToken() {

HttpURLConnection urlConnection = (HttpURLConnection)(new URL(endpoint).getConnection();
..
}

How to mock a new URL(endpoint).getConnection() .如何模拟一个new URL(endpoint).getConnection() Until I get a mocked urlConnection , I can't proceed into further statements of the method.在我得到一个模拟的urlConnection ,我无法继续对该方法的进一步陈述。

You can't mock this piece of code.你不能模拟这段代码。 Why?为什么?

Let's say you mocked the URL object but when the code reaches this part of the code, new URL(endpoint) the new URL object is always created. Let's say you mocked the URL object but when the code reaches this part of the code, new URL(endpoint) the new URL object is always created.

This is a bad design and the best thing you can possibly do is to inject the object into the constructor which makes the code easily testable as you can mock it.这是一个糟糕的设计,您可以做的最好的事情是将 object 注入构造函数中,这使得代码易于测试,因为您可以模拟它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM