简体   繁体   English

get getResourceAsStream的单元测试

[英]Unit Test for get getResourceAsStream

I have a controller with 我有一个控制器

InputStream inStream = ControllerClass.getClass().getResourceAsStream(doc); 

doc is a stream that I send in via httpservletrequest (it will be /doc/xxx.json). doc是我通过httpservletrequest发送的流(它将是/doc/xxx.json)。 If I want to unit test this controller, I have to create a mock resource first for the code above to fetch my mock resource. 如果要对该控制器进行单元测试,则必须首先为上面的代码创建一个模拟资源,以获取我的模拟资源。 As I know, the above code will fetch the file from the path project/target/classes/doc/xxx.json . 据我所知,以上代码将从路径project/target/classes/doc/xxx.json提取文件。

How can you create a mock file at the path in order to unit test the controller? 您如何在路径上创建模拟文件以对控制器进行单元测试?

You don't need to create a mock file in order to unit test the controller until and unless its a very huge JSON String. 您无需创建模拟文件即可对控制器进行单元测试,直到且除非它是一个非常大的JSON字符串。

Just try with this simple code: 只需尝试以下简单代码:

InputStream inStream = new StringInputStream(mockJsonString);

As per your last comment - won't find the file at /doc/xxx.json 根据您的最后评论-在/doc/xxx.json找不到文件

Try this one 试试这个

InputStream inStream = new FileInputStream(new File("doc/xxx.json"));

I just went through the hell of how resourceasstream can behave differently under different circumstances. 我只是经历了在不同情况下resourceasstream如何表现不同的地狱。 I ended up changing over to basically mocking the source and the mock really just returned the JSON or HTML we wanted to use in the tests in question. 我最终转为基本上模拟源代码,并且该模拟实际上只是返回了我们要在相关测试中使用的JSON或HTML。

Can't recommend this enough. 不能推荐这个。 The code is cleaner and you are not trying to figure out whether a file ended up in the classpath or where off the classpath it is. 代码更简洁,您不打算弄清楚文件是在类路径中结束还是不在类路径中。 If your file is large, it might be less appealing, but you could even create modular versions of those assembled files, eg: 如果您的文件很大,则吸引力可能会降低,但是您甚至可以为这些组合文件创建模块化版本,例如:

new MockResponse.Builder().addHeader(headerJSON).body(forecastTable).build();

Of course, those elements will be strings somewhere, but you could do a lot of organizing that frankly your sample test files don't have. 当然,这些元素将在某些地方是字符串,但是坦率地说,示例测试文件没有这些内容,因此您可以进行很多整理。

I rethought this because I spent a bunch of time looking at tests that ran under gradle at the command line but not inside IntelliJ. 我之所以重新考虑,是因为我花了很多时间来查看在命令行下但不在IntelliJ内部进行的测试。 But then I was thinking about how Karma works in Angular: when you are writing tests against expected responses, you are literally saying things like: 但是后来我想到了Karma在Angular中的工作方式:当您针对预期的响应编写测试时,您实际上是在说诸如此类的事情:

.when("/forecasts").respond("{ forecasts: [ { "mon", 75º }, { "tue", "78º" } ... ]")

So the idea that responses would be mocked as literal snippets is deemed acceptable there. 因此,将响应模拟为文字摘要的想法在那里被认为是可以接受的。

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

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