我正在尝试对我的服务类进行单元测试,但模拟返回空
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
为 null。我无法弄清楚我是否错过了什么。我已经尝试过 RunWith SpringRunner
和MockitoJUnitRunner
但结果相同。任何帮助,不胜感激。
提前谢谢你。
使用 @InjectMocks
注释时,您需要初始化DataMigrationService
字段。这将创建待测试类的实例,并将模拟对象注入其中。
@InjectMocks
DataMigrationService dataMigrationService = new DataMigrationService();
http://www.baeldung.com/mockito-annotations
如果你使用 JUnit 来运行你的测试,那么你应该有这样的东西:
@Before
public void setup()
{
MockitoAnnotations.initMocks(this);
}
这可确保初始化所有模拟。使用MockitoJUnitRunner
时,这应该是不必要的。