我正在尝试使用SpringJUnit4ClassRunner创建junit测试用例。
@Configuration
@ComponentScan(basePackages = { "com.controller",
"com.service",
"com.repository" })
class CustomConfiguration {
}
@RunWith(SpringJUnit4ClassRunner.class)
@org.springframework.test.context.ContextConfiguration(classes = CustomConfiguration.class)
public class Test {
@InjectMocks
@Spy
private EmployeeController employeeController;
@Mock
EmployeeService employeeService;
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
@org.junit.Test
public void test() throws Exception {
Employee employee = new Employee();
employee.setEmailId("admin@gmail.com");
employee.setFirstName("admin");
employee.setLastName("admin");
Employee employee = employeeController.createEmployee(employee);
assertNotNull(employee);
}
}它给出的错误是没有类型为EmployeeRepository的限定bean。
发布于 2020-07-24 15:21:29
似乎即使您有一个自定义配置类用于测试,存储库bean也不会通过类路径扫描在后台创建。如果您的目标是集成测试用例而不是junit测试用例,因为您提供的代码中似乎没有模拟任何东西,那么为什么不尝试使用更新的注释版本,比如使用SpringRunner.class而不是SpringJunit4Runner.class,如果您的spring版本支持它的话。如果你只是想创建一个单元测试用例。为您想模拟的任何东西创建一个模拟bean:
@Mock
SomeRepository repo;这个mock应该在junit启动时自动注入到您的服务bean中。如果你使用的是springboot,那么:
@RunWith(SpringRunner.class)
@SpringBootTest
public class Test {
@Mock
EmployeeService employeeService;
@InjectMocks
private EmployeeController employeeController;
@org.junit.Test
public void test() throws Exception {
Employee employee = new Employee();
employee.setEmailId("admin@gmail.com");
employee.setFirstName("admin");
employee.setLastName("admin");
when(employeeService.save(any)).thenReturn(employee);
Employee employee = employeeController.createEmployee(employee);
assertNotNull(employee);
}
}上面是一个在springboot中进行单元测试的典型例子,但是对于你的控制器类,springboot提供了注释@WebMvcTest或者你想要做的web层only.If单元测试,请阅读doc。
https://stackoverflow.com/questions/63068222
复制相似问题