Home > Software design >  How to mock model in service test?
How to mock model in service test?

Time:11-25

I try write service test, for example, I have this ExamServiceImpl:

@Service
public class ExamServiceImpl implements ExamService {

@Autowired
private final SubjectService scoreService;
private final ScoreDAO scoreDAO;

@Autowired
public ExamServiceImpl(ScoreDAO scoreDAO) {
    this.scoreDAO = scoreDAO;
}

@Override
public ResponseModel insertScore(RequestModel request) throws IOException {
    SubjectModel subject = scoreService.getNameSubject(request);

    ScoreModel score = new ScoreModel();

    score.setStudentName(request.getStudentName);
    score.setScore(request.getStudentScore);
    score.setSubject(subject.getName);

    int result = scoreDAO.insert(score);

    return result;
    }
}

Sample my test:

@SpringBootTest
public class ExamServiceImplTest {

@MockBean
private ScoreDAO scoreDAO;

@Autowired
private SubjectService subjectService;

@Autowired
private ExamService examService;


@Test
void insertScoreTest() {
    SubjectModel resFromSubject = new SubjectModel();
    resFromSubject.setSubject("Math");

    Mockito.when(subjectService.getNameSubject(new RequestModel())).thenReturn(resFromSubject);
    Mockito.when(scoreDAO.insert(new ScoreModel())).thenReturn(1);

    int resultTest = examService.insertScore(new RequestModel());
    assertSame(ex, 1);

}

But output resultTest is 0. I try debugger, I found mock scoreDAO.insert() return 0 >> is not working.

And I try like this:

@SpringBootTest
@RunWith(MockitoJUnitRunner.class)
public class ExamServiceImplTest {

@Mock
private ScoreDAO scoreDAO;

@Mock
private SubjectService subjectService;

@InjectMocks
private ExamService examService = ExamServiceImpl(scoreDAO);

@Before 
public void setup() {
    MockitoAnnotations.initMocks(this); 
}

@Test
void insertScoreTest() {
    SubjectModel resFromSubject = new SubjectModel();
    resFromSubject.setSubject("Math");

    Mockito.when(subjectService.getNameSubject(new RequestModel())).thenReturn(resFromSubject);
    Mockito.when(scoreDAO.insert(new ScoreModel())).thenReturn(1);

    int resultTest = examService.insertScore(new RequestModel());
    assertSame(ex, 1);

}

It's not work too.

Please, could you help write me test methods? I covered with tests more simple other services.

Thank you!

CodePudding user response:

It doesn't work because new ScoreModel() inside Mockito.when() and inside ExamServiceImpl are two different objects. If you want scoreDAO to return 1 for every ScoreModel passed to it you can use:

Mockito.when(scoreDAO.insert(Mockito.any(ScoreModel.class)).thenReturn(1);
  • Related