英文:
Mock in unit test is not working. Select into database is working now
问题
I have a service class, that executes user's request:
@Service
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();
}
}
Controller, that's use Service:
@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);
}
}
I created unit tests. They are mockito methods isn't working. All test methods doing request to the database. Test 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));
}
}
This code is trying to read or write to the database. I've tried so many variants. I've been trying to write tests for a few days. =( What is the error?
英文:
I have a service class, that executes user's request:
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();
}
}
Controller, that's use Service:
@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);
}
}
I created unit tests. They are mockito methods isn't working. All test methods doing request to database. Test 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));
}
}
This code is trying to read or write to database. I've tried so many variants.
I've been trying to write tests for a few days.=( What is the error?
答案1
得分: 1
我已经将我的测试类更改到下面的代码中,现在它可以正常工作:
@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);
}
// 测试方法
}
英文:
I've changed my test class onto next code and it works now:
@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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论