单元测试中的模拟不起作用。 Select 正在进入数据库

Mock in unit test is not working. Select into database is working now

我有一项服务 class,它执行用户的请求:

public class UnitServiceImpl extends HttpRequestServiceImpl implements UnitService {
    private final UnitRepository unitRepository;

    public UnitServiceImpl(UnitRepository unitRepository) {
        this.unitRepository = unitRepository;
    }

    @Override
    public Unit addUnit(String unitName) {
        final Unit unit = new Unit();
        unit.setUnitName(unitName);
        return unitRepository.save(unit);
    }

    @Override
    public Unit getUnit(int id) {
        final Unit unit = unitRepository.findById(id);
        if (unit == null) {
            throw new EntityNotFoundException("Unit is not found");
        }
        return unit;
    }

    @Override
    public Unit updateUnit(int id, String unitName) {
        final Unit unit = getUnit(id);
        unit.setUnitName(unitName);
        return unitRepository.save(unit);
    }

    @Override
    public Iterable<Unit> getAllUnits() {
        return unitRepository.findAll();
    }
}

控制器,即使用服务:


@RestController
public class UnitController {
    private final UnitService managementService;

    public UnitController(UnitService managementService) {
        this.managementService = managementService;
    }

    @GetMapping(value = "/unit", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Iterable<Unit>> getAllUnits() {
        final Iterable<Unit> allUnits = managementService.getAllUnits();
        return new ResponseEntity<>(allUnits, HttpStatus.OK);
    }

    @PostMapping(value = "/unit", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Unit> addUnit(HttpServletRequest request) throws FieldsIsAbsentException {
        final String unitName = managementService.getParameter(request, "unit_name");

        final Unit unit = managementService.addUnit(unitName);
        return new ResponseEntity<>(unit, HttpStatus.CREATED);
    }

    @GetMapping(value = "/unit/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Unit> getUnitById(@PathVariable("id") int id) {
        final Unit unit = managementService.getUnit(id);
        return new ResponseEntity<>(unit, HttpStatus.OK);
    }

    @PutMapping(value = "/unit/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Unit> updateUnit(HttpServletRequest request, @PathVariable("id") int id) {
        final String unitName = managementService.getParameter(request, "unit_name");
        return new ResponseEntity<>(managementService.updateUnit(id, unitName), HttpStatus.ACCEPTED);
    }
}

我创建了单元测试。他们是 mockito 方法不起作用。所有向数据库发出请求的测试方法。测试 class:

@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ApplicationTestConfig.class)
@WebAppConfiguration
@AutoConfigureMockMvc
class UnitControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @Mock
    UnitService unitService;

    @Autowired
    private UnitController unitController;

    private final List<Unit> units = new ArrayList<>();

    @BeforeEach
    public void initUnits() {
        this.mockMvc = MockMvcBuilders.standaloneSetup(unitController)
                .setControllerAdvice(new ExceptionHandlingController()).build();

        Unit unit = new Unit();
        unit.setUnitName("someUnit 1");
        unit.setId(1);
        units.add(unit);

        unit = new Unit();
        unit.setId(2);
        unit.setUnitName("Some unit 2");
        units.add(unit);
    }

    @Test
    void testGetAllUnits() throws Exception {
        when(this.unitService.getAllUnits()).thenReturn(units);
        mockMvc.perform(get("/unit"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON));
    }

    @Test
    void testUnitNotFound() throws Exception {
        int id = -1;
        given(this.unitService.getUnit(id)).willThrow(EntityNotFoundException.class);
        mockMvc.perform(get("/unit/" + id))
                .andDo(print())
                .andExpect(status().isNotFound())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON));
    }

    @Test
    void testUnitFound() throws Exception {
        int id = 5;
        Unit unitWithName = new Unit();
        unitWithName.setId(id);
        unitWithName.setUnitName("NameUnit");
        given(unitService.getUnit(id)).willReturn(unitWithName);
        mockMvc.perform(get("/unit/" + id).contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.id").value(id))
                .andExpect(jsonPath("$.unitName").value(unitWithName.getUnitName()));
    }

    @Test
    void testAddUnit() throws Exception {
        Unit unit = new Unit();
        unit.setId(1);
        unit.setUnitName("TestUnit");

        given(unitService.addUnit("TestUnit")).willReturn(unit);
        mockMvc.perform(post("/unit").param("unit_name", "TestUnit"))
                .andExpect(status().isCreated())
                .andExpect(jsonPath("$.unitName").value(unit.getUnitName()))
                .andExpect(jsonPath("$.id").value(1));
    }
}

此代码正在尝试读取或写入数据库。我尝试了很多变体。 这几天我一直在尝试编写测试。=( 错误是什么?

我已将我的测试 class 更改为下一个代码,现在可以运行了:

@WebMvcTest(UnitController.class)
class UnitControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @MockBean
    UnitService unitService;

    private final List<Unit> units = new ArrayList<>();

    @BeforeEach
    public void initUnits() {
        Unit unit = new Unit();
        unit.setUnitName("someUnit 1");
        unit.setId(1);
        units.add(unit);

        unit = new Unit();
        unit.setId(2);
        unit.setUnitName("Some unit 2");
        units.add(unit);
    }

///test methods