我做错了什么?测试不起作用。
这是我的界面类:
@Validated
public interface ICustomerService
{
public List<Customer> findbyStr(
@NotEmpty(message = "{column.notvalid}")
@NotNull(message = "{column.notvalid}")
String column,
@NotEmpty(message = "{column.notvalid}")
@NotNull(message = "{value.notvalid}")
String value);
}
这是我的实现类:
@Service("customerService")
@Scope(value = "singleton", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class CustomerService implements ICustomerService {
@Autowired
private IStorageDao<Customer> dao;
@Override
public List<Customer> findbyStr(String column, String value) {
return dao.findByString(Customer.class, column, value);
}
}
这是我的单元测试类: JUNIT测试不起作用。
@RunWith(SpringJUnit4ClassRunner.class)
public class CustomerTest extends BaseIntegrationTest {
@Autowired
private ICustomerService service;
@Autowired
public static Validator validator;
@Test
public void test_A6_CustomerFindByStrNull() {
List<Customer> result = service.findbyStr(null, null);
Set<ConstraintViolation<ICustomerService>> constraintViolations = validator
.validate(service);
assertEquals(0, constraintViolations.size());
assertEquals("Die angegebene E-Mail-Adresse ist fehlerhaft.",
constraintViolations.iterator().next().getMessage());
assertNotNull(result);
assertNotNull(result.get(1));
}
}
答案 0 :(得分:1)
我很确定当注释在对象的方法上时,你无法测试ConstraintViolations
因为它应该抛出MethodConstraintViolationException
。你应该尝试这样的事情:
@RunWith(SpringJUnit4ClassRunner.class)
public class CustomerTest extends BaseIntegrationTest {
@Autowired
private ICustomerService service;
@Test
public void test_A6_CustomerFindByStrNull() {
try {
List<Customer> result = service.findbyStr(null, null);
} catch (MethodConstraintViolationException ex) {
assertEquals("Die angegebene E-Mail-Adresse ist fehlerhaft.", ex.getConstraintViolations().iterator().next().getMessage());
}
fail("Exception expected");
}
}
您需要在application-context.xml
文件中包含以下Bean:
<bean class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor"/>