public abstract class AbstractValidator implements Validator
{
@Override
public abstract void validate(
FacesContext context, UIComponent component, Object value)
throws ValidatorException;
protected String buildValidationMessage(String param)
{
return param;
}
}
public abstract class AbstractMatchValidator extends AbstractValidator {
protected String field1ComponentId;
protected String field1InputLabel;
protected String inputLabel;
protected abstract String cleanBeforeComparing(String value);
@Override
public void validate(FacesContext context,
UIComponent component,
Object value) throws ValidatorException {
UIInput input1 = Components.findComponentInParents(component,
field1ComponentId);
if (null == input1) {
return;
}
String field1 = null;
if (input1.isValid()) {
field1 = this.cleanBeforeComparing((String)input1.getValue());
}
String confirmField = this.cleanBeforeComparing((String) value);
if (!StringUtils.isBlank(field1) && !field1.equals(confirmField)) {
input1.setValid(false);
FacesMessage msg = buildValidationMessage(context,
this.inputLabel,
this.fieldToMatchInputLabel);
throw new ValidatorException(msg);
}
}
public class EmployeeIDMatchValidator extends AbstractFieldMatchValidator {
protected String cleanBeforeComparing(String value) {
return value.replace("_",":");
}
public class SSNMatchValidator extends AbstractFieldMatchValidator {
protected String cleanBeforeComparing(String value) {
return value.replace("_","-");
}
我有这个Jmockit测试:
@RunWith(JMockit.class)
public class EmployeeIDMatchValidatorTest {
@Tested
EmployeeIDMatchValidator validator;
@Test
@SuppressWarnings(value = "unchecked")
public final void testNoExceptionIsThrownForNoEmployeeIDValue(
@Mocked FacesContext facesContext,
@Mocked UIInput textInput,
@Mocked UIInput uiInput){
new MockUp<Components>() {
@Mock
public <C extends UIComponent> C findComponentInParents(UIComponent component, String clientId) {
return (C) textInput;
}
};
new Expectations() {{
textInput.getSubmittedValue();
result="9-9192121-1";
MessageFormat.format(anyString, any);
result = "Employee ID is invalid.";
}};
validator.validate(facesContext, uiInput, "9-91921211");
}
}
当我运行此测试时,textInput和uiInput值显示为null。有人可以告诉我为什么这些值没有传递给findComponentInParents方法。
我在日志中收到此错误:
mockit.internal.MissingInvocation: Missing 1 invocation to:
javax.faces.component.UIInput#getSubmittedValue()
on mock instance: javax.faces.component.UIInput@1a04f701
我在这次测试中缺少的是什么?请帮忙。
答案 0 :(得分:0)
JMockit告诉您,您没有调用该方法,并且根据您共享的代码,您通过使用块“预期”进行一次调用:
new Expectations() {{
textInput.getSubmittedValue();
result="9-9192121-1"; ...
}};
如果你想要返回一个特定的值,那么你正在测试的方法不会调用 getSubmittedValue() ,但它会调用 getValue() 方法。
new Expectations() {{
uiInput.getValue();
result="9-9192121-1";
//... more code
}};
对于 getValue() isValid() 方法的预期>被称为。
new Expectations() {{
uiInput.isValid(); result = true;
uiInput.getValue(); result="9-9192121-1";
// ... more code
}};
不要忘记在Expectations的静态块中提到的所有内容都应该被调用至少一次。欲获得更多信息: http://jmockit.org/api1x/mockit/Expectations.html