简体   繁体   English

Junit:对于每个循环 [暂停]

[英]Junit : For each loop [on hold]

Question: I want to write a test case for For-Each loop?问题:我想为 For-Each 循环编写一个测试用例?

for(Car car : Cars){
    Engine.set(car)
}

How write a Junit test case for this.如何为此编写 Junit 测试用例。 Kindly explain for this.请为此解释。

This question is very open ended and the code itself isn't written to be easily tested as Engine.set is a static function.这个问题是非常开放的,并且代码本身并不是为了易于测试而编写的,因为Engine.set是 static function。 If you are only concerned about the end result then you could do something like this:如果您只关心最终结果,那么您可以执行以下操作:

@Test
public void sampleEngineTestForStackOverflow() {
    setCarForEngine(); // This function would run the foreach loop in your example

    assertEquals(Engine.getCar(), lastCar)
}

I'm assuming that since you can set a Car to the Engine you would also have a getCar() method.我假设由于您可以将Car设置为Engine ,因此您还将拥有一个getCar()方法。 The value of lastCar would be the last Car which was set to the Engine instance. lastCar的值将是设置为Engine实例的最后一个Car Unfortunately as the question doesn't include other information it's difficult to provide more information other than this.不幸的是,由于该问题不包含其他信息,因此很难提供除此之外的更多信息。

If you need to verify that the Engine.set method is called multiple times then you would need to use PowerMock to first mock the Engine instance and then you could use Mockito to verify the different Car instances that were set.如果您需要验证Engine.set方法是否被多次调用,那么您需要使用PowerMock首先模拟Engine实例,然后您可以使用Mockito来验证设置的不同Car实例。 Alternatively the code could be refactored to not use static instances and you'd have a much easier time with testing.或者,可以将代码重构为不使用static实例,这样您可以更轻松地进行测试。

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

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