在单元测试中模拟不起作用。现在选择进数据库正在工作。

huangapple go评论104阅读模式
英文:

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

问题

I have a service class, that executes user's request:

  1. @Service
  2. public class UnitServiceImpl extends HttpRequestServiceImpl implements UnitService {
  3. private final UnitRepository unitRepository;
  4. public UnitServiceImpl(UnitRepository unitRepository) {
  5. this.unitRepository = unitRepository;
  6. }
  7. @Override
  8. public Unit addUnit(String unitName) {
  9. final Unit unit = new Unit();
  10. unit.setUnitName(unitName);
  11. return unitRepository.save(unit);
  12. }
  13. @Override
  14. public Unit getUnit(int id) {
  15. final Unit unit = unitRepository.findById(id);
  16. if (unit == null) {
  17. throw new EntityNotFoundException("Unit is not found");
  18. }
  19. return unit;
  20. }
  21. @Override
  22. public Unit updateUnit(int id, String unitName) {
  23. final Unit unit = getUnit(id);
  24. unit.setUnitName(unitName);
  25. return unitRepository.save(unit);
  26. }
  27. @Override
  28. public Iterable<Unit> getAllUnits() {
  29. return unitRepository.findAll();
  30. }
  31. }

Controller, that's use Service:

  1. @RestController
  2. public class UnitController {
  3. private final UnitService managementService;
  4. public UnitController(UnitService managementService) {
  5. this.managementService = managementService;
  6. }
  7. @GetMapping(value = "/unit", produces = MediaType.APPLICATION_JSON_VALUE)
  8. public ResponseEntity<Iterable<Unit>> getAllUnits() {
  9. final Iterable<Unit> allUnits = managementService.getAllUnits();
  10. return new ResponseEntity<>(allUnits, HttpStatus.OK);
  11. }
  12. @PostMapping(value = "/unit", produces = MediaType.APPLICATION_JSON_VALUE)
  13. public ResponseEntity<Unit> addUnit(HttpServletRequest request) throws FieldsIsAbsentException {
  14. final String unitName = managementService.getParameter(request, "unit_name");
  15. final Unit unit = managementService.addUnit(unitName);
  16. return new ResponseEntity<>(unit, HttpStatus.CREATED);
  17. }
  18. @GetMapping(value = "/unit/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
  19. public ResponseEntity<Unit> getUnitById(@PathVariable("id") int id) {
  20. final Unit unit = managementService.getUnit(id);
  21. return new ResponseEntity<>(unit, HttpStatus.OK);
  22. }
  23. @PutMapping(value = "/unit/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
  24. public ResponseEntity<Unit> updateUnit(HttpServletRequest request, @PathVariable("id") int id) {
  25. final String unitName = managementService.getParameter(request, "unit_name");
  26. return new ResponseEntity<>(managementService.updateUnit(id, unitName), HttpStatus.ACCEPTED);
  27. }
  28. }

I created unit tests. They are mockito methods isn't working. All test methods doing request to the database. Test class:

  1. @SpringBootTest
  2. @RunWith(SpringJUnit4ClassRunner.class)
  3. @ContextConfiguration(classes = ApplicationTestConfig.class)
  4. @WebAppConfiguration
  5. @AutoConfigureMockMvc
  6. class UnitControllerTest {
  7. @Autowired
  8. private MockMvc mockMvc;
  9. @Mock
  10. UnitService unitService;
  11. @Autowired
  12. private UnitController unitController;
  13. private final List<Unit> units = new ArrayList<>();
  14. @BeforeEach
  15. public void initUnits() {
  16. this.mockMvc = MockMvcBuilders.standaloneSetup(unitController)
  17. .setControllerAdvice(new ExceptionHandlingController()).build();
  18. Unit unit = new Unit();
  19. unit.setUnitName("someUnit 1");
  20. unit.setId(1);
  21. units.add(unit);
  22. unit = new Unit();
  23. unit.setId(2);
  24. unit.setUnitName("Some unit 2");
  25. units.add(unit);
  26. }
  27. @Test
  28. void testGetAllUnits() throws Exception {
  29. when(this.unitService.getAllUnits()).thenReturn(units);
  30. mockMvc.perform(get("/unit"))
  31. .andDo(print())
  32. .andExpect(status().isOk())
  33. .andExpect(content().contentType(MediaType.APPLICATION_JSON));
  34. }
  35. @Test
  36. void testUnitNotFound() throws Exception {
  37. int id = -1;
  38. given(this.unitService.getUnit(id)).willThrow(EntityNotFoundException.class);
  39. mockMvc.perform(get("/unit/" + id))
  40. .andDo(print())
  41. .andExpect(status().isNotFound())
  42. .andExpect(content().contentType(MediaType.APPLICATION_JSON));
  43. }
  44. @Test
  45. void testUnitFound() throws Exception {
  46. int id = 5;
  47. Unit unitWithName = new Unit();
  48. unitWithName.setId(id);
  49. unitWithName.setUnitName("NameUnit");
  50. given(unitService.getUnit(id)).willReturn(unitWithName);
  51. mockMvc.perform(get("/unit/" + id).contentType(MediaType.APPLICATION_JSON))
  52. .andExpect(status().isOk())
  53. .andExpect(jsonPath("$.id").value(id))
  54. .andExpect(jsonPath("$.unitName").value(unitWithName.getUnitName()));
  55. }
  56. @Test
  57. void testAddUnit() throws Exception {
  58. Unit unit = new Unit();
  59. unit.setId(1);
  60. unit.setUnitName("TestUnit");
  61. given(unitService.addUnit("TestUnit")).willReturn(unit);
  62. mockMvc.perform(post("/unit").param("unit_name", "TestUnit"))
  63. .andExpect(status().isCreated())
  64. .andExpect(jsonPath("$.unitName").value(unit.getUnitName()))
  65. .andExpect(jsonPath("$.id").value(1));
  66. }
  67. }

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:

  1. public class UnitServiceImpl extends HttpRequestServiceImpl implements UnitService {
  2. private final UnitRepository unitRepository;
  3. public UnitServiceImpl(UnitRepository unitRepository) {
  4. this.unitRepository = unitRepository;
  5. }
  6. @Override
  7. public Unit addUnit(String unitName) {
  8. final Unit unit = new Unit();
  9. unit.setUnitName(unitName);
  10. return unitRepository.save(unit);
  11. }
  12. @Override
  13. public Unit getUnit(int id) {
  14. final Unit unit = unitRepository.findById(id);
  15. if (unit == null) {
  16. throw new EntityNotFoundException(&quot;Unit is not found&quot;);
  17. }
  18. return unit;
  19. }
  20. @Override
  21. public Unit updateUnit(int id, String unitName) {
  22. final Unit unit = getUnit(id);
  23. unit.setUnitName(unitName);
  24. return unitRepository.save(unit);
  25. }
  26. @Override
  27. public Iterable&lt;Unit&gt; getAllUnits() {
  28. return unitRepository.findAll();
  29. }
  30. }

Controller, that's use Service:

  1. @RestController
  2. public class UnitController {
  3. private final UnitService managementService;
  4. public UnitController(UnitService managementService) {
  5. this.managementService = managementService;
  6. }
  7. @GetMapping(value = &quot;/unit&quot;, produces = MediaType.APPLICATION_JSON_VALUE)
  8. public ResponseEntity&lt;Iterable&lt;Unit&gt;&gt; getAllUnits() {
  9. final Iterable&lt;Unit&gt; allUnits = managementService.getAllUnits();
  10. return new ResponseEntity&lt;&gt;(allUnits, HttpStatus.OK);
  11. }
  12. @PostMapping(value = &quot;/unit&quot;, produces = MediaType.APPLICATION_JSON_VALUE)
  13. public ResponseEntity&lt;Unit&gt; addUnit(HttpServletRequest request) throws FieldsIsAbsentException {
  14. final String unitName = managementService.getParameter(request, &quot;unit_name&quot;);
  15. final Unit unit = managementService.addUnit(unitName);
  16. return new ResponseEntity&lt;&gt;(unit, HttpStatus.CREATED);
  17. }
  18. @GetMapping(value = &quot;/unit/{id}&quot;, produces = MediaType.APPLICATION_JSON_VALUE)
  19. public ResponseEntity&lt;Unit&gt; getUnitById(@PathVariable(&quot;id&quot;) int id) {
  20. final Unit unit = managementService.getUnit(id);
  21. return new ResponseEntity&lt;&gt;(unit, HttpStatus.OK);
  22. }
  23. @PutMapping(value = &quot;/unit/{id}&quot;, produces = MediaType.APPLICATION_JSON_VALUE)
  24. public ResponseEntity&lt;Unit&gt; updateUnit(HttpServletRequest request, @PathVariable(&quot;id&quot;) int id) {
  25. final String unitName = managementService.getParameter(request, &quot;unit_name&quot;);
  26. return new ResponseEntity&lt;&gt;(managementService.updateUnit(id, unitName), HttpStatus.ACCEPTED);
  27. }
  28. }

I created unit tests. They are mockito methods isn't working. All test methods doing request to database. Test class:

  1. @SpringBootTest
  2. @RunWith(SpringJUnit4ClassRunner.class)
  3. @ContextConfiguration(classes = ApplicationTestConfig.class)
  4. @WebAppConfiguration
  5. @AutoConfigureMockMvc
  6. class UnitControllerTest {
  7. @Autowired
  8. private MockMvc mockMvc;
  9. @Mock
  10. UnitService unitService;
  11. @Autowired
  12. private UnitController unitController;
  13. private final List&lt;Unit&gt; units = new ArrayList&lt;&gt;();
  14. @BeforeEach
  15. public void initUnits() {
  16. this.mockMvc = MockMvcBuilders.standaloneSetup(unitController)
  17. .setControllerAdvice(new ExceptionHandlingController()).build();
  18. Unit unit = new Unit();
  19. unit.setUnitName(&quot;someUnit 1&quot;);
  20. unit.setId(1);
  21. units.add(unit);
  22. unit = new Unit();
  23. unit.setId(2);
  24. unit.setUnitName(&quot;Some unit 2&quot;);
  25. units.add(unit);
  26. }
  27. @Test
  28. void testGetAllUnits() throws Exception {
  29. when(this.unitService.getAllUnits()).thenReturn(units);
  30. mockMvc.perform(get(&quot;/unit&quot;))
  31. .andDo(print())
  32. .andExpect(status().isOk())
  33. .andExpect(content().contentType(MediaType.APPLICATION_JSON));
  34. }
  35. @Test
  36. void testUnitNotFound() throws Exception {
  37. int id = -1;
  38. given(this.unitService.getUnit(id)).willThrow(EntityNotFoundException.class);
  39. mockMvc.perform(get(&quot;/unit/&quot; + id))
  40. .andDo(print())
  41. .andExpect(status().isNotFound())
  42. .andExpect(content().contentType(MediaType.APPLICATION_JSON));
  43. }
  44. @Test
  45. void testUnitFound() throws Exception {
  46. int id = 5;
  47. Unit unitWithName = new Unit();
  48. unitWithName.setId(id);
  49. unitWithName.setUnitName(&quot;NameUnit&quot;);
  50. given(unitService.getUnit(id)).willReturn(unitWithName);
  51. mockMvc.perform(get(&quot;/unit/&quot; + id).contentType(MediaType.APPLICATION_JSON))
  52. .andExpect(status().isOk())
  53. .andExpect(jsonPath(&quot;$.id&quot;).value(id))
  54. .andExpect(jsonPath(&quot;$.unitName&quot;).value(unitWithName.getUnitName()));
  55. }
  56. @Test
  57. void testAddUnit() throws Exception {
  58. Unit unit = new Unit();
  59. unit.setId(1);
  60. unit.setUnitName(&quot;TestUnit&quot;);
  61. given(unitService.addUnit(&quot;TestUnit&quot;)).willReturn(unit);
  62. mockMvc.perform(post(&quot;/unit&quot;).param(&quot;unit_name&quot;, &quot;TestUnit&quot;))
  63. .andExpect(status().isCreated())
  64. .andExpect(jsonPath(&quot;$.unitName&quot;).value(unit.getUnitName()))
  65. .andExpect(jsonPath(&quot;$.id&quot;).value(1));
  66. }
  67. }

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

我已经将我的测试类更改到下面的代码中,现在它可以正常工作:

  1. @WebMvcTest(UnitController.class)
  2. class UnitControllerTest {
  3. @Autowired
  4. private MockMvc mockMvc;
  5. @MockBean
  6. UnitService unitService;
  7. private final List<Unit> units = new ArrayList<>();
  8. @BeforeEach
  9. public void initUnits() {
  10. Unit unit = new Unit();
  11. unit.setUnitName("someUnit 1");
  12. unit.setId(1);
  13. units.add(unit);
  14. unit = new Unit();
  15. unit.setId(2);
  16. unit.setUnitName("Some unit 2");
  17. units.add(unit);
  18. }
  19. // 测试方法
  20. }
英文:

I've changed my test class onto next code and it works now:

  1. @WebMvcTest(UnitController.class)
  2. class UnitControllerTest {
  3. @Autowired
  4. private MockMvc mockMvc;
  5. @MockBean
  6. UnitService unitService;
  7. private final List&lt;Unit&gt; units = new ArrayList&lt;&gt;();
  8. @BeforeEach
  9. public void initUnits() {
  10. Unit unit = new Unit();
  11. unit.setUnitName(&quot;someUnit 1&quot;);
  12. unit.setId(1);
  13. units.add(unit);
  14. unit = new Unit();
  15. unit.setId(2);
  16. unit.setUnitName(&quot;Some unit 2&quot;);
  17. units.add(unit);
  18. }
  19. ///test methods

huangapple
  • 本文由 发表于 2020年8月8日 17:27:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63313785.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定