哪个大师知道测试这个类的行为的最佳实践,所以每当调用AsyncCallback时,它应该进入onSuccess方法。打印出“onSuccess”。
@RunWith(MockitoJUnitRunner.class)
public class InterfaceTest {
@Mock
private Service service;
private Employee employee;
@Before
public void setUp() throws Exception {
employee = mock(Employee.class);
}
@Test
public void testMockBehavier() throws Exception {
}
}
interface AsyncCallback {
void onError();
void onSuccess();
}
class Employee {
@Autowired
Service service;
public void save(){
service.save(new AsyncCallback() {
@Override
public void onError() {
System.out.println("Error");
}
@Override
public void onSuccess() {
System.out.println("Success");
}
});
}
}
interface Service {
void save(AsyncCallback asyncCallback);
}
我还没有找到如何访问匿名内部类。 非常感谢良好的练习tipps。
由于
答案 0 :(得分:1)
如果我理解正确,被测试的课程是员工。所以如果有一个你不应该嘲笑的课程,那就是员工。
其次,您需要将模拟服务注入受测试的员工。
第三,你需要告诉模拟服务在调用save()
时调用成功回调。
@RunWith(MockitoJUnitRunner.class)
public class InterfaceTest {
@Mock
private Service service;
@InjectMocks
private Employee employee;
@Test
public void testSuccess() throws Exception {
Answer<Void> answer = new Answer<Void>() {
Void answer(InvocationOnMock invocation) {
AsyncCallback callback = invocation.getArguments()[0];
callback.onSuccess();
return null;
}
};
doAnswer(answer).when(service).save(any(AsyncCallback.class));
employee.save()
// TODO: now check that the success callback does what it's supposed to do
}
}