我正在尝试对我的服务类进行单元测试,但模拟返回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 SpringRunner
和MockitoJUnitRunner
但结果相同。任何帮助表示赞赏。
提前谢谢。
答案 0 :(得分:2)
使用DataMigrationService
注释时,您需要初始化@InjectMocks
字段。这将创建一个被测试类的实例,并将模拟对象注入其中。
@InjectMocks
DataMigrationService dataMigrationService = new DataMigrationService();
答案 1 :(得分:-1)
如果您正在使用JUnit来运行测试,那么您应该具有以下内容:
@Before
public void setup()
{
MockitoAnnotations.initMocks(this);
}
这可确保您的所有模拟都已初始化。使用MockitoJUnitRunner
时,这应该是不必要的。