gpt4 book ai didi

java - 如何测试一个永不返回的方法?

转载 作者:行者123 更新时间:2023-11-30 08:13:10 24 4
gpt4 key购买 nike

如何测试我的类的方法行为?

public class InfiniteWhileLoop {
public void fun() {
while (true) {
// some code to test
}
}
}

我需要测试方法 fun 并确保它将字段设置为“xyz”。问题是我遇到了无限循环。所以我需要运行 while 循环并让它设置字段,然后停止循环。

可能吗?

最佳答案

如果涉及另一个依赖项,您可以抛出异常来转义。

使用 Mockito 的示例(也可以通过手动伪造依赖项来实现)

public class Foo
{
public interface Bar
{
void doSomething();
}

private Bar bar;
private int counter = 0;

public Foo( Bar bar )
{
this.bar = bar;
}

public void loop()
{
while ( true )
{
counter++;
bar.doSomething();
}
}

public int getCounter()
{
return counter;
}
}

测试:

public class FooTest
{
@SuppressWarnings( "serial" )
private class TestException extends RuntimeException
{}

@Test
public void loop3ShouldIncrementCounterBy3() throws Exception
{
Bar bar = mock( Bar.class );
Foo cut = new Foo( bar );

doNothing().doNothing().doThrow( new TestException() ).when( bar ).doSomething();

try
{
cut.loop();
}
catch ( TestException e )
{}

assertThat( cut.getCounter(), is( 3 ) );
}
}

关于java - 如何测试一个永不返回的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30058717/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com