运行Mockito测试时,Spring @Autowired字段为空

时间:2018-10-14 09:51:49

标签: java spring spring-boot testing mockito

这是我的主要代码:

@Service
public class MainService {
    public String mainMethod() {
        SomeService someService = new SomeService("required");
        // do Sth.
    }
}

@Service
@RequiredArgsConstructor
public class SomeService {
    @Autowired
    private SomeOtherService someOtherService;
    @Notnull
    private final String requiredField;
    // ...
}

@Service
public class SomeOtherService {
    // just a bunch of public methods that might as well be static
}

这是测试设置:

@RunWith(SpringRunner.class)
public class MainServiceTest {
    @InjectMocks
    private MainService mainService;

    @Test
    public void givenSth_whenSth_doSth() {
        // test mainService.mainMethod();
    }
}

能否请您告诉我SomeService中的someOtherService为什么为空?

我发现当您使用Spring的注入时,您不应同时使用手动实例化(新...);所以也许是new SomeService("required")的问题?但是,如果不通过构造函数调用,该如何将字段变量注入SomeService?我不想使用Builder,因为requiredField应该是NotNull。

2 个答案:

答案 0 :(得分:0)

对于Spring Bean,可以使用MockBean来遵循Adam Weidner的tutorial,而对于Spring的TestNG,可以使用AbstractTestNGSpringContextTest扩展

@TestExecutionListeners(MockitoTestExecutionListener.class)
@SpringBootTest
public class WidgetServiceIntegrationTest extends AbstractTestNGSpringContextTest {
@MockBean private SprockService sprockService;
@MockBean private SpringService springService;
@Autowired WidgetService widgetService;
@Test
public void testSomethingOnWidgetService() {
     when(sprockService.makeASprock()).thenReturn(...);

答案 1 :(得分:0)

对于集成测试,请考虑使用如下所示的上下文配置实例化

@RunWith(SpringRunner.class)
@ContextConfiguration("mockito-config.xml")

有关详细说明,请参阅

对于单元测试,请考虑使用Mockito提供的@Mock批注。

在此特定示例中,我们可以如下所示模拟SomeOtherService

 @RunWith(SpringRunner.class)
 public class MainServiceTest {

 @InjectMocks
 private MainService mainService;

 @Mock
 private SomeOtherService someOtherService

 @Test
 public void givenSth_whenSth_doSth() {
     // test mainService.mainMethod();
 }
}

有关详细说明,请参阅以下帖子