I have a simple implementation using JMockit for unit test. The implementations are as following
Team
class
public class Team {
private TeamLeader teamLeader;
public Team(TeamLeader teamleader) {
this.teamLeader = teamleader;
}
public boolean hasDiscussion() {
System.out.println("Discussion is hold by " + teamLeader.getName());
Discussion discussion = new Discussion();
return discussion.start();
}
}
TeamLeader
class
public class TeamLeader {
private String name;
public TeamLeader(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Discussion
class
public class Discussion {
public boolean start() {
return false;
}
}
Then, I have a unit test to test function hasDiscussion
as following
@RunWith(JMockit.class)
public class TeamTest {
private Team team;
@Test
public void hasDiscussion(@Mocked TeamLeader teamLeader, @Mocked Discussion discussion) {
new Expectations() {{
teamLeader.getName(); result = "teamleader";
discussion.start(); result = true;
}};
team = new Team(teamLeader);
boolean actualResult = team.hasDiscussion();
new Verifications() {{
assertThat(actualResult, is(true));
}};
}
}
When executing the test, I got the following error
Unexpected invocation of:
entity.Discussion#Discussion()
on instance: entity.Discussion@7b70deb2
when was expecting an invocation of:
entity.Discussion#start()
on mock instance: entity.Discussion@6f93ad02
mockit.internal.UnexpectedInvocation: Unexpected invocation of:
entity.Discussion#Discussion()
on instance: entity.Discussion@7b70deb2
when was expecting an invocation of:
Any ideas for this sort of problem?
This happened because your hasDiscussion
method was creating a new instance of Discussion
class, and in this case, you can’t mock it.
To solve this you can receive the Discuss
class as a parameter of the method and send the mock, our inject the Discuss class in Team
class constructor.