'Spring Boot kotlin testing service method with Mockito which saves duplicated names
This is my service logic.
fun createTags(post: Post, names: List<String>) {
val tagsToSave = names.stream()
.distinct()
.filter { name -> !tagRepository.existsByName(name) }
.map { name -> Tag(name = name) }
.collect(Collectors.toList())
tagRepository.saveAll(tagsToSave)
}
It's executed before every test method starts.
val namesWithDuplication = arrayListOf("defaultTag1", "defaultTag1", "tag1", "tag1", "tag2", "tag3")
fun getMockTagsWithDuplicatedNames() = namesWithDuplication.distinct().map { name -> Tag(name = name) }
@BeforeEach
fun init() {
post = Post(id = 1, title = "test title", body = "test body")
val tags = arrayListOf(
Tag(id = 1, name = "defaultTag1"),
Tag(id = 2, name = "defaultTag2"),
Tag(id = 3, name = "defaultTag3")
)
val postTags = arrayListOf(
PostTag(id = 1, post = post, tag = tags[0]),
PostTag(id = 2, post = post, tag = tags[1]),
PostTag(id = 3, post = post, tag = tags[2])
)
postRepository.save(post)
tags.forEach { tag -> tagRepository.save(tag) }
postTags.forEachIndexed { index, postTag ->
postTagRepository.save(postTag)
post.postTags.add(postTag)
tags[index].postTags.add(postTag)
}
}
Here's my test code.
@Test
fun createTagsWithDuplicatedNames() {
tagService.createTags(post, namesWithDuplication)
val tags = getMockTagsWithDuplicatedNames()
verify(tagRepository, times(1)).saveAll(refEq(tags))
}
I expect this test won't succeeded because getMockTagsWithDuplicatedNames() returns tags("defaultTag1", "tag1", "tag2", "tag3"). But createTags() saves tags("tag1", "tag2", "tag3") because post already saved "defaultTag1" by @BeforeEach method.
verify(tagRepository, times(1)).saveAll(refEq(tags))
But mockito actually doesn't save tags, so the test doesn't fail.
How should I handle it to make it fail?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
