Mockito 模拟对象返回 null

2022-09-01 10:33:51

我尝试为我的JSF应用程序和我使用的模拟实现一些测试。(也用弹簧)

@RunWith(MockitoJUnitRunner.class)
public class GeneralConfigServiceImplTest  {

    private GeneralConfigService generalConfigService;

    @Mock
    private GeneralConfigDAO generalConfigDAO;

    @Mock
    private GeneralConfig gen;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        generalConfigService = new GeneralConfigService();
        ReflectionTestUtils.setField(generalConfigService, "generalConfigDAO", generalConfigDAO);                  
    }

    @Test
    public void testAddGeneralConfigCallDAOSuccess() throws DAOException, EntityNullException, IllegalEntityArgumentException, ParseException, EntityPersistException {
        gen = createGeneralConfigs("label", "value");

        generalConfigService.setInstance(gen);
        generalConfigService.persist();
        log.info(generalConfigService.getInstance().toString());
    }
}

测试成功,但当我想使用该方法检索实例时。我之前设置的所有参数(通过之前的构造函数)都是空的。我是模拟对象的新手,所以这种行为是正常的,还是我的代码中有错误?getInstance


答案 1

它实际上取决于GeneralConfigService#getInstance()实现。此外,如果使用注释,则可以大大简化测试代码。@InjectMocks

使用时,您不需要初始化模拟并手动注入依赖项:MockitoJUnitRunner

@RunWith(MockitoJUnitRunner.class)
public class GeneralConfigServiceImplTest  {

    @InjectMocks
    private GeneralConfigService generalConfigService;

    @Mock
    private GeneralConfigDAO generalConfigDAO;

    @Test
    public void testAddGeneralConfigCallDAOSuccess() {
       // generalConfigService is already instantiated and populated with dependencies here
       ...
    }
}

答案 2

我的问题是注释导入不正确:Test

import org.junit.jupiter.api.Test;

正确

import org.junit.Test;