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

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

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(&quot;Unit is not found&quot;);
}
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&lt;Unit&gt; 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 = &quot;/unit&quot;, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity&lt;Iterable&lt;Unit&gt;&gt; getAllUnits() {
final Iterable&lt;Unit&gt; allUnits = managementService.getAllUnits();
return new ResponseEntity&lt;&gt;(allUnits, HttpStatus.OK);
}
@PostMapping(value = &quot;/unit&quot;, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity&lt;Unit&gt; addUnit(HttpServletRequest request) throws FieldsIsAbsentException {
final String unitName = managementService.getParameter(request, &quot;unit_name&quot;);
final Unit unit = managementService.addUnit(unitName);
return new ResponseEntity&lt;&gt;(unit, HttpStatus.CREATED);
}
@GetMapping(value = &quot;/unit/{id}&quot;, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity&lt;Unit&gt; getUnitById(@PathVariable(&quot;id&quot;) int id) {
final Unit unit = managementService.getUnit(id);
return new ResponseEntity&lt;&gt;(unit, HttpStatus.OK);
}
@PutMapping(value = &quot;/unit/{id}&quot;, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity&lt;Unit&gt; updateUnit(HttpServletRequest request, @PathVariable(&quot;id&quot;) int id) {
final String unitName = managementService.getParameter(request, &quot;unit_name&quot;);
return new ResponseEntity&lt;&gt;(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&lt;Unit&gt; units = new ArrayList&lt;&gt;();
@BeforeEach
public void initUnits() {
this.mockMvc = MockMvcBuilders.standaloneSetup(unitController)
.setControllerAdvice(new ExceptionHandlingController()).build();
Unit unit = new Unit();
unit.setUnitName(&quot;someUnit 1&quot;);
unit.setId(1);
units.add(unit);
unit = new Unit();
unit.setId(2);
unit.setUnitName(&quot;Some unit 2&quot;);
units.add(unit);
}
@Test
void testGetAllUnits() throws Exception {
when(this.unitService.getAllUnits()).thenReturn(units);
mockMvc.perform(get(&quot;/unit&quot;))
.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(&quot;/unit/&quot; + 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(&quot;NameUnit&quot;);
given(unitService.getUnit(id)).willReturn(unitWithName);
mockMvc.perform(get(&quot;/unit/&quot; + id).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath(&quot;$.id&quot;).value(id))
.andExpect(jsonPath(&quot;$.unitName&quot;).value(unitWithName.getUnitName()));
}
@Test
void testAddUnit() throws Exception {
Unit unit = new Unit();
unit.setId(1);
unit.setUnitName(&quot;TestUnit&quot;);
given(unitService.addUnit(&quot;TestUnit&quot;)).willReturn(unit);
mockMvc.perform(post(&quot;/unit&quot;).param(&quot;unit_name&quot;, &quot;TestUnit&quot;))
.andExpect(status().isCreated())
.andExpect(jsonPath(&quot;$.unitName&quot;).value(unit.getUnitName()))
.andExpect(jsonPath(&quot;$.id&quot;).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&lt;Unit&gt; units = new ArrayList&lt;&gt;();
@BeforeEach
public void initUnits() {
Unit unit = new Unit();
unit.setUnitName(&quot;someUnit 1&quot;);
unit.setId(1);
units.add(unit);
unit = new Unit();
unit.setId(2);
unit.setUnitName(&quot;Some unit 2&quot;);
units.add(unit);
}
///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:

确定