[英]How to write unit test which creates new thread
I have following method for test: 我有以下测试方法:
public class classToTest{
@Autowired
private Alternator alternator;
public void methodToTest(){
Thread t = new Thread(new Runnable() {
public void run() {
while(true) {
if(alternator.get()) {
System.out.print("Hello");
alternator.set(false);
}
}
}
};
t.start()
}
}
I need to check that was invoked method 我需要检查那是被调用的方法
alternator.set(false);
How can I do it? 我该怎么做?
Instead of starting a thread directly, can you pass in an "Executor" instance? 您可以传入“Executor”实例,而不是直接启动线程吗?
For example... 例如...
public class ClassToTest{
@Autowired
private Alternator alternator;
@Autowired @Qualifier("myExecutor")
private java.util.concurrent.Executor executor;
public void methodToTest() {
Runnable runnable = new Runnable() {
public void run() {
while(true) {
if(alternator.get()) {
System.out.print("Hello");
alternator.set(false);
}
}
};
executor.execute(runnable);
}
}
Now you can test this easier... 现在你可以更轻松地测试这个......
public class ClassToTestTest {
...
@Before
public void setup() {
alternator = mock(Alternator.class);
executor = mock(Executor.class);
obj = new ClassToTest();
ReflectionTestUtils.setField(obj, "alternator", alternator);
ReflectionTestUtils.setField(obj, "executor", executor);
}
@Test
public void shouldStartRunnable() {
obj.methodToTest();
ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
verify(executor).execute(runnableCaptor.capture());
Runnable runnable = runnableCaptor.getValue();
// Now test your actual "runnable"...
when(alternator.get()).thenReturn(true);
runnable.run();
verify(alternator).set(false);
}
}
(Have not tried to compile this, so I apologise if there are any mistakes!!) (没有尝试编译这个,所以如果有任何错误,我道歉!!)
Though Bret's post of passing in an executor is very much recommended, you can use the timeout()
mock verification setting to test for asynchronous conditions. 虽然非常推荐Bret的传入执行程序的帖子 ,但您可以使用
timeout()
模拟验证设置来测试异步条件。
verify(alternator, timeout(500)).set(false);
Note that this will necessarily increase the flakiness of your test (ie the likelihood that the test fails when the code passes). 请注意,这必然会增加测试的瑕疵(即代码通过时测试失败的可能性)。 With a sensible timeout value, that flakiness should be negligible, but if you're making this a part of your core test infrastructure you may consider refactoring to allow for synchronous execution in the test.
使用合理的超时值,这种松散度应该可以忽略不计,但如果您将其作为核心测试基础架构的一部分,则可以考虑重构以允许在测试中同步执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.