使用InjectMocks时,JUnit Mock测试返回null

时间:2017-11-03 03:28:57

标签: java unit-testing junit mockito spring-test

我正在尝试对我的服务类进行单元测试,但模拟返回null

package com.tgt.store.pricetask.pricetask_service;

import com.tgt.store.pricetask.model.PriceTaskMaster;
import com.tgt.store.pricetask.model.TaskModel;
import com.tgt.store.pricetask.repository.PriceTaskMasterRepository;
import com.tgt.store.pricetask.service.DataMigrationService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.time.LocalDateTime;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;

@RunWith(SpringJUnit4ClassRunner.class)
public class DataMigrationServiceTest {

  @Mock
  PriceTaskMasterRepository priceTaskMasterRepository;

  @InjectMocks
  DataMigrationService dataMigrationService;

  @Test
  public void
testPriceTaskMasterService_whenTaskModelPassed_thenSavePriceTaskMaster() {

    TaskModel taskModel = new TaskModel.TaskModelBuilder().setTaskID(1)
            .setDueDate("2017-11-01T11:41:00+0000").setIsAlertable("A").setIsPriority("P").setLocationid("1234")
            .createTaskModel();

    PriceTaskMaster priceTaskMaster = new PriceTaskMaster.PriceTaskMasterBuilder().setId(1L).setTaskStatus("A")
            .setAlertable("A").setPriority("P").setLocationId(1234)
            .setDueDate(LocalDateTime.now()).createPriceTaskMaster();

    when(priceTaskMasterRepository.insertPriceTaskMaster(any(PriceTaskMaster.class))).thenReturn(priceTaskMaster);

    PriceTaskMaster savedPriceTaskMaster = dataMigrationService.savePriceTaskMaster(taskModel);

    assertNotNull(savedPriceTaskMaster);
    assertEquals("A", savedPriceTaskMaster.getTaskStatus());
    assertEquals("P", savedPriceTaskMaster.getPriority());
    assertEquals(1234, savedPriceTaskMaster.getLocationId().intValue());
    assertEquals(123456789, savedPriceTaskMaster.getTcin().longValue());

    verify((priceTaskMasterRepository), times(1)).insertPriceTaskMaster(priceTaskMaster);
  }
}

在上面的代码中,当调用到达服务类priceTaskMasterRepository时为空。我无法弄清楚我是否遗漏了什么。我尝试过RunWith SpringRunnerMockitoJUnitRunner但结果相同。任何帮助表示赞赏。

提前谢谢。

2 个答案:

答案 0 :(得分:2)

使用DataMigrationService注释时,您需要初始化@InjectMocks字段。这将创建一个被测试类的实例,并将模拟对象注入其中。

@InjectMocks
DataMigrationService dataMigrationService = new DataMigrationService();

http://www.baeldung.com/mockito-annotations

答案 1 :(得分:-1)

如果您正在使用JUnit来运行测试,那么您应该具有以下内容:

@Before
public void setup()
{
    MockitoAnnotations.initMocks(this);
}

这可确保您的所有模拟都已初始化。使用MockitoJUnitRunner时,这应该是不必要的。