問題描述
在我們想要模擬的一個(gè) Java 類中有一個(gè) URL 對(duì)象,但它是最終類,所以我們不能.我們不想更上一層樓并模擬 InputStream,因?yàn)檫@仍然會(huì)給我們留下未經(jīng)測(cè)試的代碼(我們有嚴(yán)格的測(cè)試覆蓋標(biāo)準(zhǔn)).
We have a URL object in one of our Java classes that we want to mock, but it's a final class so we cannot. We do not want to go a level above, and mock the InputStream because that will still leave us with untested code (we have draconian test coverage standards).
我嘗試了 jMockIt 的反射功能,但我們?cè)?Mac 上工作,Java 代理處理程序存在我無法解決的問題.
I've tried jMockIt's reflective powers but we work on Macs and there are problems with the Java agent handler that I haven't been able to resolve.
那么有沒有在junit測(cè)試中不涉及使用真實(shí)URL的解決方案?
So are there any solutions that do not involve using real URLs in the junit test?
推薦答案
當(dāng)我有一個(gè)類因?yàn)樗?final (或在 C# 中密封)而不能輕易模擬時(shí),我通常的路線是圍繞類并在我使用實(shí)際類的任何地方使用包裝器.然后我會(huì)根據(jù)需要模擬包裝類.
When I have a class that can't be easily mocked because it is final (or sealed in C#), my usual route is to write a wrapper around the class and use the wrapper wherever I would use the actual class. Then I would mock out the wrapper class as necessary.
這篇關(guān)于在 Java 中模擬 URL的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!