在JUnit和Mockito测试中,如果你发现注入的bean返回了零(null),这通常意味着bean没有被正确地注入或者mock。以下是一些基础概念和解决这个问题的步骤:
如果你的bean没有被Spring容器管理,那么它就不会被注入。
解决方案:
确保你的bean被标记为Spring组件(使用@Component
, @Service
, @Repository
, 或 @Controller
注解)。
@Service
public class MyService {
// ...
}
如果你的测试类没有被Spring管理,那么它就不会注入bean。
解决方案:
使用@RunWith(SpringRunner.class)
(对于JUnit 4)或@ExtendWith(SpringExtension.class)
(对于JUnit 5)注解来让Spring管理你的测试类。
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyServiceTest {
@Autowired
private MyService myService;
// ...
}
如果你在测试中使用了Mockito mock,但未正确设置返回值,那么mock将返回默认值(对于对象类型是null)。
解决方案:
使用Mockito.when(...).thenReturn(...)
来设置mock的返回值。
@RunWith(MockitoJUnitRunner.class)
public class MyServiceTest {
@Mock
private AnotherDependency anotherDependency;
@InjectMocks
private MyService myService;
@Test
public void testMethod() {
Mockito.when(anotherDependency.someMethod()).thenReturn("expectedValue");
// ...
}
}
如果你使用构造函数注入,确保所有必需的依赖项都在测试中提供。
解决方案: 在测试中创建bean实例时,确保传递所有必需的依赖项。
public class MyService {
private final AnotherDependency anotherDependency;
public MyService(AnotherDependency anotherDependency) {
this.anotherDependency = anotherDependency;
}
// ...
}
@Test
public void testConstructorInjection() {
AnotherDependency mockDependency = Mockito.mock(AnotherDependency.class);
MyService myService = new MyService(mockDependency);
// ...
}
这些概念和解决方案适用于任何使用Spring框架进行依赖注入,并且使用JUnit和Mockito进行单元测试的场景。
确保你的bean被Spring正确管理,你的测试类也被Spring管理,并且如果你使用mock,确保它们被正确设置。通过这些步骤,你应该能够解决bean注入返回null的问题。
领取专属 10元无门槛券
手把手带您无忧上云