【问题标题】:Unit test POST API in spring-boot + kotlin + Junitspring-boot + kotlin + Junit中的单元测试POST API
【发布时间】:2019-03-09 08:59:47
【问题描述】:

我对 spring boot 和 kotlin 还是很陌生。我已经开始使用来自网络的一个基本应用程序并编写单元测试,但我收到以下错误:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: articleRepository.save(article) must not be null

让我给你看代码:实体类

@Entity
data class Article (
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Long = 0,

    @get: NotBlank
    val title: String = "",

    @get: NotBlank
    val content: String = ""
)

控制器:

@PostMapping("/articles")
fun createNewArticle(@Valid @RequestBody article: Article) : Article {
    return articleRepository.save(article)
}

存储库:

@Repository
interface ArticleRepository : JpaRepository<Article, Long>

测试文件:

RunWith(SpringRunner::class)
@SpringBootTest
class KotlinDemoApplicationTests {

lateinit var mvc: MockMvc

@InjectMocks
lateinit var controller: ArticleController

@Mock
lateinit var respository: ArticleRepository

@Before
fun setup() {
    MockitoAnnotations.initMocks(this)
    mvc = MockMvcBuilders.standaloneSetup(controller).setMessageConverters(MappingJackson2HttpMessageConverter()).build()
}

@Test
fun createBlog() {
    var article = Article(1, "Test", "Test Content")
    var jsonData = jacksonObjectMapper().writeValueAsString(article)
    mvc.perform(MockMvcRequestBuilders.post("/api/articles/").contentType(MediaType.APPLICATION_JSON).content(jsonData))
            .andExpect(MockMvcResultMatchers.status().isOk)
            .andDo(MockMvcResultHandlers.print())
            .andReturn()
}
}

当我运行这个测试文件时,出现上述错误。 请帮我解决这个问题。

【问题讨论】:

    标签: spring-boot junit kotlin


    【解决方案1】:

    问题在于您的 ArticleRepository 模拟。

    虽然您正确地将其注入到您的控制器中,但您并没有指定对 save 的调用应该返回什么。因此,它返回 null,这在 Kotin 中是不允许的,因为您将其指定为非可选的。

    您要么允许控制器的createNewArticle 返回null,通过添加?,将其签名更改为

    fun createNewArticle(@Valid @RequestBody article: Article) : Article? {...}
    

    或者您将模拟设置为不返回null,而是返回一篇文章。

    @Before
    fun setup() {
        MockitoAnnotations.initMocks(this)
        ...
        `when`(respository.save(any())
            .thenReturn(Article()) // creates a new article
    }
    

    (或者,如果您不想调用构造函数,也可以使用 Mockito's returnsFirstArg()。)


    请注意,在这种情况下使用 any() 仅在您使用 mockito-kotlin 时才有效
    如果不想用,请查看this answer

    【讨论】:

      猜你喜欢
      • 2020-08-08
      • 2018-10-17
      • 1970-01-01
      • 2017-02-12
      • 2019-03-27
      • 2019-10-26
      • 2017-02-08
      • 2017-11-02
      • 2016-05-28
      相关资源
      最近更新 更多