Yud*_*rya 7 java spring asynchronous mockito spring-boot
@Async使用mockito 模拟asynchronous()方法的最佳方法是什么?提供以下服务:
@Service
@Transactional(readOnly=true)
public class TaskService {
@Async
@Transactional(readOnly = false)
public void createTask(TaskResource taskResource, UUID linkId) {
// do some heavy task
}
}
Run Code Online (Sandbox Code Playgroud)
Mockito的验证如下:
@RunWith(SpringRunner.class)
@WebMvcTest(SomeController.class)
public class SomeControllerTest {
@Autowired
MockMvc mockMvc;
@MockBean
private TaskService taskService;
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
// other details omitted...
@Test
public void shouldVerify() {
// use mockmvc to fire to some controller which in turn call taskService.createTask
// .... details omitted
verify(taskService, times(1)) // taskService is mocked object
.createTask(any(TaskResource.class), any(UUID.class));
}
}
Run Code Online (Sandbox Code Playgroud)
shouldVerify上面的测试方法总是抛出:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced argument matcher detected here:
-> at SomeTest.java:77) // details omitted
-> at SomeTest.java:77) // details omitted
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))
Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.
Run Code Online (Sandbox Code Playgroud)
如果我@Async从TaskService.createTask方法中删除,则不会发生上述异常.
Spring Boot版本:1.4.0.RELEASE
Mockito版本:1.10.19
发现通过将 Async 模式更改为 AspectJ 解决了该问题:
@EnableCaching
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(lazyInit = true)
@EnableAsync(mode = AdviceMode.ASPECTJ) // Changes here!!!
public class Main {
public static void main(String[] args) {
new SpringApplicationBuilder().sources(Main.class)
.run(args);
}
}
Run Code Online (Sandbox Code Playgroud)
在我了解此问题的真正根本原因之前,我会接受这是一个临时的黑客解决方案。
| 归档时间: |
|
| 查看次数: |
2494 次 |
| 最近记录: |