繁体   English   中英

使用Mockito模拟时无法调用以@PostConstruct注释的方法

[英]Unable to invoke method annotated with @PostConstruct when mocked using Mockito

我正在尝试使用Junit和Mockito为存储库层类编写单元测试。 我嘲笑了提供NamedParameterJdbcOperations的基类,并试图注入到repo类中。 在repo类中,我们从classpath上的文件加载sql查询。 这是通过@PostConstruct注释的方法完成的。 尝试测试存储库的方法时,它无法找到或加载查询,从而引发NullPointerException。

需要有关如何处理这种情况的帮助/建议。

PS:我不允许更改repo类的实现。

附加回购代码和测试类以供参考。

RepositoryImpl.java

@Repository
public class RepositoryImpl extends AppJdbcImpl implements
    Repository {

private static final StudentMapper STUDENT_ROW_MAPPER = new StudentMapper();
private static final CourseMapper COURSE_ROW_MAPPER = new CourseMapper();

@Value("classpath:sql/sql1.sql")
private Resource sql1;
private String query1;

@Value("classpath:sql/sql2.sql")
private Resource sql2;
private String query2;

public RepositoryImpl() { }

public RepositoryImpl(NamedParameterJdbcOperations jdbc) {
    super(jdbc);
}

@PostConstruct
public void setUp() {
    query1 = loadSql(sql1);
    query2 = loadSql(sql2);
}

public Iterable<Course> findCoursesByStudentId(int studentId) throws
    DataAccessException {

    try {
        return jdbc().queryForObject(query1,
            ImmutableMap.of("studentId", studentId),
            COURSE_ROW_MAPPER);

    } catch (EmptyResultDataAccessException emptyResult) {
        return null;
    } catch (DataAccessException e) {
        // Need to create exception classes and throw specific exceptions
        throw e;
    }

}

public Iterable<Student> findStudentsByCourseId(int courseId) throws DataAccessException {

    try {

        return jdbc().query(query2,
            ImmutableMap.of("courseId", courseId),
            STUDENT_ROW_MAPPER);

    } catch (DataAccessException e) {
        // Need to create exception classes and throw specific exceptions
        throw e;
    }

}

private String loadSql(Resource resource) {
    try {
        return CharStreams.toString(new InputStreamReader(resource.getInputStream()));
    } catch (IOException e) {
        return null;
    }
}

}

RespositoryImplTest.java

@RunWith(MockitoJUnitRunner.class)
public class RepositoryImplTest {
@Mock
private NamedParameterJdbcOperations jdbc;

@Mock
private ResultSet resultSet;

@Mock
private StudentMapper studentMapper;

@Mock
private CourseMapper CourseMapper;

@InjectMocks
private RepositoryImpl repository;

private Student student1;
private Student student2;

private Course course1;
private Course course2;

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    course1 = new Course(1, "Karate");
    course2 = new Course(2, "Riding");
    course8 = new Course(8, "Swimming");
    List<Course> courseList = Arrays.asList(course1, course2, course8);

    student1 = new Student(1, "Chuck", "Norris", 27, new Arrays.asList(course1, course2));
    student2 = new Student(2, "Bruce", "Lee", 54, new Arrays.asList(course1, course8));
    List<Student> studentList = Arrays.asList(student1, student2);

    when(jdbc.queryForObject(Matchers.anyString(), anyMap(),
        isA(StudentMapper.class)))
        .thenAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
                Object[] args = invocationOnMock.getArguments();
                int queryParam = Integer.parseInt(args[0].toString());

                Iterable<Credentials> result = studentList.stream()
                .filter(d -> d.getId() == queryParam)
                .collect(Collectors.toList());

                return result;
            }
        });
}

@Test
public void findCoursesByStudentId() {
    Iterable<Course> result = repository.findCoursesByStudentId(1);
    assertNotNull(result);
}

}

在repo类中,由于query1为null引发了异常。

需要帮助以正确解决问题。

谢谢,巴鲁

@RunWith(MockitoJUnitRunner.class)

您可以使用模仿启动器而不是弹簧启动器开始测试。 这意味着春天没有为您提供豆类。 Mockito入门者对PostConstruct批注一无所知。

您可以在sturUp junit方法或测试方法中自行调用PostConstruct方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM