猿问

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

这是我的主要代码:


@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 ...);所以也许new SomeService("required")是问题所在?但是,如果不是通过构造函数调用,我如何将字段变量注入 SomeService?我不想使用 Builder,因为 requiredField 应该是 NotNull。


梵蒂冈之花
浏览 415回答 2
2回答

慕无忌1623718

对于集成测试,请考虑使用如下所示的上下文配置实例化 bean@RunWith(SpringRunner.class)@ContextConfiguration("mockito-config.xml")详细解释请参考https://blog.jayway.com/2011/11/30/spring-integration-tests-part-i-creating-mock-objects/对于单元测试,请考虑使用 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(); }}详细解释请参考以下帖子http://www.vogella.com/tutorials/Mockito/article.htmlhttp://static.javadoc.io/org.mockito/mockito-core/2.23.0/org/mockito/MockitoAnnotations.html

MM们

您可以按照 Adam Weidner 的教程使用MockBeanSpring Bean 并使用Spring 扩展AbstractTestNGSpringContextTestTestNG@TestExecutionListeners(MockitoTestExecutionListener.class)@SpringBootTestpublic class WidgetServiceIntegrationTest extends AbstractTestNGSpringContextTest {@MockBean private SprockService sprockService;@MockBean private SpringService springService;@Autowired WidgetService widgetService;@Testpublic void testSomethingOnWidgetService() {     when(sprockService.makeASprock()).thenReturn(...);
随时随地看视频慕课网APP

相关分类

Java
我要回答