【发布时间】:2018-07-06 10:18:50
【问题描述】:
我想开始在我的项目中编写单元测试。我试过很多次。而他总是退出,因为他无法理解其中的含义。因为我找不到知识并将其整合为一个整体。我读了很多文章,看到了很多例子,它们都是不同的。结果,我明白了为什么我需要编写测试,我了解如何编写它们,但我不明白如何正确。而且我不明白如何编写它们以便它们有用。我有一些问题:
例如我有服务:
@Service
public class HumanServiceImpl implements HumanService {
private final HumanRepository humanRepository;
@Autowired
public HumanServiceImpl(HumanRepository humanRepository) {
this.humanRepository = humanRepository;
}
@Override
public Human getOneHumanById(Long id) {
return humanRepository.getOne(id);
}
@Override
public Human getOneHumanByName(String firstName) {
return humanRepository.findOneByFirstName(firstName);
}
@Override
public Human getOneHumanRandom() {
Human human = new Human();
human.setId(Long.parseLong(String.valueOf(new Random(100))));
human.setFirstName("firstName"+ System.currentTimeMillis());
human.setLastName("LastName"+ System.currentTimeMillis());
human.setAge(12);//any logic for create Human
return human;
}
}
我尝试为此服务编写单元测试:
@RunWith(SpringRunner.class)
public class HumanServiceImplTest {
@MockBean(name="mokHumanRepository")
private HumanRepository humanRepository;
@MockBean(name = "mockHumanService")
private HumanService humanService;
@Before
public void setup() {
Human human = new Human();
human.setId(1L);
human.setFirstName("Bill");
human.setLastName("Gates");
human.setAge(50);
when(humanRepository.getOne(1L)).thenReturn(human);
when(humanRepository.findOneByFirstName("Bill")).thenReturn(human);
}
@Test
public void getOneHumanById() {
Human found = humanService.getOneHumanById(1L);
assertThat(found.getFirstName()).isEqualTo("Bill");
}
@Test
public void getOneHumanByName() {
Human found = humanService.getOneHumanByName("Bill");
assertThat(found.getFirstName()).isEqualTo("Bill");
}
@Test
public void getOneHumanRandom() {
//???
}
}
我有问题:
1.我应该在哪里填充对象?我看到了不同的实现
在 @Before 中,就像在我的示例中一样,在 @Test 中,混合实现 - 当人类在 @Before 和表达式中创建时
when(humanRepository.getOne(1L)).thenReturn(human);
在@Test方法中
private Human human;
@Before
public void setup() {
human = new Human();
...
}
@Test
public void getOneHumanById() {
when(humanRepository.getOne(1L)).thenReturn(human);
Human found = humanService.getOneHumanById(1L);
assertThat(found.getFirstName()).isEqualTo("Bill");
}
2。如何测试getOneHumanRandom() 方法?
调用此方法时服务不使用存储库。我可以模拟这个方法,但它会提供什么?
when(humanService.getOneHumanRandom()).thenReturn(human);
...
@Test
public void getOneHumanRandom() {
Human found = humanService.getOneHumanRandom();
assertThat(found.getFirstName()).isEqualTo("Bill");
}
我只是从测试类的服务中复制逻辑。这种测试有什么意义,有必要吗?
【问题讨论】:
-
docs.spring.io/spring-boot/docs/current/reference/html/… 而不是模拟存储库,而是使用真正的实现并对其进行测试。
-
@Darren Forsythe 和我是如何测试持久层的例子,如果我问如何测试服务层?
标签: java unit-testing mockito spring-boot-test