Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Một phương pháp không đồng bộ thực hiện trong thread riêng của mình, thông báo một số người nghe khi nó được hoàn thành. Mã gọi một phương pháp không đồng bộ không ngăn chặn, có nghĩa là bạn không thể viết một thử nghiệm như thế này: | new TestGame testSameFighters 200 run some other test suite in a fourth thread suite.addTest TestPerson.suite return suite 4.14.4 See Also Recipe 4.10 explains the RepeatedTest class. 4.15 Testing Asynchronous Methods 4.15.1 Problem You want to test asynchronous methods. 4.15.2 Solution Use a mock listener to wait for the asynchronous method to complete. 4.15.3 Discussion An asynchronous method executes in its own thread notifying some listener when it is complete. Code that calls an asynchronous method does not block meaning that you cannot write a test like this public void testSomething someAsynchronousMethod assertXXX . The problem with this code lies in the fact that the assertXXX is almost certainly executed before the thread started by someAsynchronousMethod has a chance to do its work. We really need to do something like this 1. Call an asynchronous method. 2. Wait until the method is complete. 3. Get the results. If the method times out fail. Otherwise check the results. To illustrate let s look at a simple interface for searching. We assume that searching occurs in its own thread notifying a SearchModelListener whenever the search is complete. Example 4-8 shows the API. Example 4-8. SearchModel interface public interface SearchModel void search Object searchcriteria SearchModelListener listener The search method is asynchronous notifying the SearchModelListener when it is complete. Example 4-9 shows the code for the SearchModelListener interface. Example 4-9. SearchModelListener interface public interface SearchModelListener extends EventListener void searchFinished SearchModelEvent evt In order to test the search model we must write a mock listener that waits for the search to complete. Once the mock listener receives its result we can verify that the data is correct. Example 4-10 shows the code for a mock listener. Example 4-10. MockSearchModelListener class class MockSearchModelListener implements SearchModelListener private SearchModelEvent evt public