Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Junit和Mockito测试Spring验证器_Spring_Testing_Junit_Mockito - Fatal编程技术网

如何使用Junit和Mockito测试Spring验证器

如何使用Junit和Mockito测试Spring验证器,spring,testing,junit,mockito,Spring,Testing,Junit,Mockito,我有一个Spring验证器: @Component public class AddClientAccountValidator implements Validator { @Autowired private ValidatorUtils validatorUtils; @Override public boolean supports(Class<?> clazz) { return UserDto.class.equals(

我有一个Spring验证器:

@Component
public class AddClientAccountValidator implements Validator {

    @Autowired
    private ValidatorUtils validatorUtils;

    @Override
    public boolean supports(Class<?> clazz) {
        return UserDto.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        UserDto user = (UserDto) target;
        validatorUtils.setParam(errors, user);

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "username.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "password.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "confirmPassword",
                "confirmPassword.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "firstName.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "lastName.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "personalId", "personalId.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "city", "city.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address", "address.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "email.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "phone", "phone.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "contribution", "contribution.required");

        validatorUtils.validateAddClientAccount();
    }
}
但当我运行测试时,我得到以下Failet跟踪:

java.lang.AssertionError
at org.junit.Assert.fail(Assert.java:86)
at org.junit.Assert.assertTrue(Assert.java:41)
at org.junit.Assert.assertFalse(Assert.java:64)
at org.junit.Assert.assertFalse(Assert.java:74)
at pl.piotr.ibank.validator.AddClientAccValidatorTest.testValidate(AddClientAccValidatorTest.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
为什么我会犯这个错误?我在这行中得到错误:

errors = new BeanPropertyBindingResult(userDto, "userDto");
我的第二个问题是,我不能用注释声明多个RunWith。当我加上:

@RunWith(MockitoJUnitRunner.class)
我无法使用
@RunWith(Parameterized.class)

如何解决


有人能帮我吗?也许我的方法不好?使用Junit测试Spring验证器的最佳方法是什么?

您可以在没有Mockito的情况下成功运行测试。以下代码适用于Spring@Configuration类(需要作为依赖项进行Spring测试):


您可以在没有Mockito的情况下成功运行测试。以下代码适用于Spring@Configuration类(需要作为依赖项进行Spring测试):


你不需要嘲笑任何事情。在验证时,我们需要要验证的对象和错误。创建一个对象,其中包含要验证的必填字段和错误对象。比如说,

@Test
public void shouldReturnErrorsWhenCustomObjectIsNull() {
    CustomValidator customValidator = new CustomValidator();

    Employee employee = new Employee();
    employee.setEmployeeFirstname("empName")


    Errors errors = new BeanPropertyBindingResult(employee, "employee");
    customValidator.validate(employee, errors);
    List<ObjectError> allErrors = errors.getAllErrors();
    assertTrue("Errors list size should not be null : ", allErrors.size() > 0);
    assertTrue(errors.hasErrors());
    assertNotNull( errors.getFieldError("empName") );
}
@测试
public void应在CustomObjectisAll()时返回错误{
CustomValidator CustomValidator=新CustomValidator();
员工=新员工();
employee.setEmployeeFirstname(“empName”)
Errors Errors=newbeanPropertyBindingResult(雇员,“雇员”);
customValidator.validate(员工、错误);
List allErrors=errors.getAllErrors();
assertTrue(“错误列表大小不应为空:”,allErrors.size()>0);
assertTrue(errors.hasErrors());
assertNotNull(errors.getFieldError(“empName”);
}

你不需要模仿任何东西。在验证时,我们需要要验证的对象和错误。创建一个对象,其中包含要验证的必填字段和错误对象。比如说,

@Test
public void shouldReturnErrorsWhenCustomObjectIsNull() {
    CustomValidator customValidator = new CustomValidator();

    Employee employee = new Employee();
    employee.setEmployeeFirstname("empName")


    Errors errors = new BeanPropertyBindingResult(employee, "employee");
    customValidator.validate(employee, errors);
    List<ObjectError> allErrors = errors.getAllErrors();
    assertTrue("Errors list size should not be null : ", allErrors.size() > 0);
    assertTrue(errors.hasErrors());
    assertNotNull( errors.getFieldError("empName") );
}
@测试
public void应在CustomObjectisAll()时返回错误{
CustomValidator CustomValidator=新CustomValidator();
员工=新员工();
employee.setEmployeeFirstname(“empName”)
Errors Errors=newbeanPropertyBindingResult(雇员,“雇员”);
customValidator.validate(员工、错误);
List allErrors=errors.getAllErrors();
assertTrue(“错误列表大小不应为空:”,allErrors.size()>0);
assertTrue(errors.hasErrors());
assertNotNull(errors.getFieldError(“empName”);
}

在您的测试中,您没有将任何行为添加到
验证器utils validateOutils
,因此注入
AddClientAccountValidator验证器
的模拟将基本上不起作用。此外,
UserDto-UserDto
将被初始化为
null
,因此,它肯定不会通过您定义的任何验证规则。阅读Mockito文档显然是一个起点。请注意,堆栈跟踪包含有用的信息:
addclientacvalidatortest.java:67
。记得提到问题中的哪一行,因为它目前不明显(甚至不包括在内)。对不起,我粘贴了错误的代码。UserDto已初始化,错误行67为:
errors=newbeanPropertyBindingResult(UserDto,“UserDto”)
在您的测试中,您没有向
ValidatorUtils ValidatorOutils
添加任何行为,因此注入
AddClientAccountValidatorValidator
的模拟基本上是不可操作的。此外,
UserDto UserDto
将被初始化为
null
,因此,它肯定不会通过您定义的任何验证规则。阅读Mockito文档显然是一个起点。请注意,堆栈跟踪包含有用的信息:
addclientacvalidatortest.java:67
。记得提到问题中的哪一行,因为它目前不明显(甚至不包括在内)。对不起,我粘贴了错误的代码。UserDto已初始化,错误行67为:
errors=newbeanPropertyBindingResult(UserDto,“UserDto”)您还可以查看JSR-303和属性上带有注释的验证。您还可以查看JSR-303和属性上带有注释的验证。
package foo.bar;

import static org.junit.Assert.assertFalse;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.Errors;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class AddClientAccValidatorTest {

    @Configuration
    static class ContextConfiguration {

        @Bean
        public AddClientAccountValidator validator() {
            return new AddClientAccountValidator();
        }

        @Bean
        public ValidatorUtils validatorUtils() {
            return new ValidatorUtils();
        }
    }

    @Autowired
    private AddClientAccountValidator validator;
    private UserDto userDto;
    public Errors errors;

    @Before
    public void setUp() {
        userDto = new UserDto();
        userDto.setLastName("Doe");
        userDto.setFirstName("John");
        userDto.setUsername("username");
        userDto.setPhone("phone");
        userDto.setPassword("password");
        userDto.setConfirmedPassword("password");
        userDto.setEmail("email");
        userDto.setContribution("contribution");
        userDto.setAddress("address");
        userDto.setCity("city");
        userDto.setPersonalId("personalId");
        errors = new BeanPropertyBindingResult(userDto, "userDto");
    }

    @Test
    public void testValidate() {
        validator.validate(userDto, errors);
        assertFalse(errors.hasErrors());
    }
}
@Test
public void shouldReturnErrorsWhenCustomObjectIsNull() {
    CustomValidator customValidator = new CustomValidator();

    Employee employee = new Employee();
    employee.setEmployeeFirstname("empName")


    Errors errors = new BeanPropertyBindingResult(employee, "employee");
    customValidator.validate(employee, errors);
    List<ObjectError> allErrors = errors.getAllErrors();
    assertTrue("Errors list size should not be null : ", allErrors.size() > 0);
    assertTrue(errors.hasErrors());
    assertNotNull( errors.getFieldError("empName") );
}