- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在Kotlin中编写了一个非常简单且通用的CRUD。我想做基本测试,如测试发布,删除,获取和放置。
可能我理解错了:我使用Beforeeach的目的是插入一个寄存器,以便可以在get测试期间进行检查。我没有得到异常,但似乎在进行get测试时,如果在波纹管测试中对于任何其他不同于1的id都应为NOT_FOUND,则它总是返回ok。
即使看到其他基于我的目的的不良做法(简单的CRUD测试),也会向正确的方向提供任何线索或指导。
测试
package com.mycomp.jokenpo
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.mycomp.jokenpo.controller.UserController
import com.mycomp.jokenpo.model.User
import com.mycomp.jokenpo.respository.UserRepository
import com.mycomp.jokenpo.service.UserService
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.MockitoAnnotations
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.web.client.TestRestTemplate
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
import org.springframework.test.context.junit.jupiter.SpringExtension
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders
import org.springframework.test.web.servlet.result.MockMvcResultHandlers
import org.springframework.test.web.servlet.result.MockMvcResultMatchers
import org.springframework.test.web.servlet.setup.MockMvcBuilders
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ExtendWith(SpringExtension::class)
@AutoConfigureMockMvc
class JokenpoApplicationTests {
@Autowired
lateinit var testRestTemplate: TestRestTemplate
@Autowired
private lateinit var mvc: MockMvc
@InjectMocks
lateinit var controller: UserController
@Mock
lateinit var respository: UserRepository
@Mock
lateinit var service: UserService
//private fun <T> any(type: Class<T>): T = Mockito.any<T>(type)
@BeforeEach
fun setup() {
MockitoAnnotations.initMocks(this)
mvc = MockMvcBuilders.standaloneSetup(controller).setMessageConverters(MappingJackson2HttpMessageConverter()).build()
`when`(respository.save(User(1, "Test")))
.thenReturn(User(1, "Test"))
}
@Test
fun createUser() {
//val created = MockMvcResultMatchers.status().isCreated
var user = User(2, "Test")
var jsonData = jacksonObjectMapper().writeValueAsString(user)
mvc.perform(MockMvcRequestBuilders.post("/users/")
.contentType(MediaType.APPLICATION_JSON)
.content(jsonData))
.andExpect(MockMvcResultMatchers.status().isOk)
//.andExpect(created)
.andDo(MockMvcResultHandlers.print())
.andReturn()
}
@Test
fun findUser() {
val ok = MockMvcResultMatchers.status().isOk
val builder = MockMvcRequestBuilders.get("/users?id=99") //no matther which id I type here it returns ok. I would expect only return for 1 based on my @BeforeEach
this.mvc.perform(builder)
.andExpect(ok)
}
}
package com.mycomp.jokenpo.controller
import com.mycomp.jokenpo.model.User
import com.mycomp.jokenpo.respository.UserRepository
import com.mycomp.jokenpo.service.UserService
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import java.util.concurrent.atomic.AtomicLong
import javax.validation.Valid
@RestController
@RequestMapping("users")
class UserController (private val userService: UserService, private val userRepository: UserRepository){
val counter = AtomicLong()
// @GetMapping("/user")
// fun getUser(@RequestParam(value = "name", defaultValue = "World") name: String) =
// User(counter.incrementAndGet(), "Hello, $name")
@GetMapping()
fun getAllUsers(): List<User> =
userService.all()
@PostMapping
fun add(@Valid @RequestBody user: User): ResponseEntity<User> {
//user.id?.let { userService.save(it) }
val savedUser = userService.save(user)
return ResponseEntity.ok(savedUser)
}
@GetMapping("/{id}")
fun getUserById(@PathVariable(value = "id") userId: Long): ResponseEntity<User> {
return userRepository.findById(userId).map { user ->
ResponseEntity.ok(user)
}.orElse(ResponseEntity.notFound().build())
}
@DeleteMapping("/{id}")
fun deleteUserById(@PathVariable(value = "id") userId: Long): ResponseEntity<Void> {
return userRepository.findById(userId).map { user ->
userRepository.deleteById(user.id)
ResponseEntity<Void>(HttpStatus.OK)
}.orElse(ResponseEntity.notFound().build())
}
// @DeleteMapping("{id}")
// fun deleteUserById(@PathVariable id: Long): ResponseEntity<Unit> {
// if (noteService.existsById(id)) {
// noteService.deleteById(id)
// return ResponseEntity.ok().build()
// }
// return ResponseEntity.notFound().build()
// }
/////
// @PutMapping("{id}")
// fun alter(@PathVariable id: Long, @RequestBody user: User): ResponseEntity<User> {
// return userRepository.findById(userId).map { user ->
// userRepository. deleteById(user.id)
// ResponseEntity<Void>(HttpStatus.OK)
// }.orElse(ResponseEntity.notFound().build())
// }
}
package com.mycomp.jokenpo.respository
import com.mycomp.jokenpo.model.User
import org.springframework.data.repository.CrudRepository
interface UserRepository : CrudRepository<User, Long>
package com.mycomp.jokenpo.model
import javax.persistence.*
@Entity
data class User(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long,
@Column(nullable = false)
val name: String
)
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("org.springframework.boot") version "2.2.6.RELEASE"
id("io.spring.dependency-management") version "1.0.9.RELEASE"
kotlin("jvm") version "1.3.71"
kotlin("plugin.spring") version "1.3.71"
kotlin("plugin.jpa") version "1.3.71"
}
group = "com.mycomp"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_1_8
val developmentOnly by configurations.creating
configurations {
runtimeClasspath {
extendsFrom(developmentOnly)
}
}
repositories {
mavenCentral()
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
developmentOnly("org.springframework.boot:spring-boot-devtools")
runtimeOnly("com.h2database:h2")
//runtimeOnly("org.hsqldb:hsqldb")
testImplementation("org.springframework.boot:spring-boot-starter-test") {
exclude(group = "org.junit.vintage", module = "junit-vintage-engine")
}
testImplementation ("com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0")
}
tasks.withType<Test> {
useJUnitPlatform()
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "1.8"
}
}
spring:
datasource:
url: jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
username: sa
password:
driver-class-name: org.h2.Driver
platform: h2
h2:
console:
enabled: true
path: /h2-console #jdbc:h2:mem:testdb
最佳答案
为了解决您的问题,我建议使用@MockBean,这是一个可用于向Spring ApplicationContext
添加模拟的注释。
我将按照以下方式重新编写您的测试(注意,我已经利用mockito-kotlin已经成为您项目的测试依赖项):
package com.mycomp.jokenpo
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.mycomp.jokenpo.model.User
import com.mycomp.jokenpo.respository.UserRepository
import com.nhaarman.mockitokotlin2.whenever
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.junit.jupiter.MockitoExtension
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.http.MediaType
import org.springframework.test.context.junit.jupiter.SpringExtension
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.get
import org.springframework.test.web.servlet.post
import org.springframework.web.util.NestedServletException
@AutoConfigureMockMvc. // auto-magically configures and enables an instance of MockMvc
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
// Why configure Mockito manually when a JUnit 5 test extension already exists for that very purpose?
@ExtendWith(SpringExtension::class, MockitoExtension::class)
class JokenpoApplicationTests {
@Autowired
private lateinit var mockMvc: MockMvc
@MockBean
lateinit var respository: UserRepository
@BeforeEach
fun setup() {
// use mockito-kotlin for a more idiomatic way of setting up your test expectations
whenever(respository.save(User(1, "Test"))).thenAnswer {
it.arguments.first()
}
}
@Test
fun `Test createUser in the happy path scenario`() {
val user = User(1, "Test")
mockMvc.post("/users/") {
contentType = MediaType.APPLICATION_JSON
content = jacksonObjectMapper().writeValueAsString(user)
accept = MediaType.APPLICATION_JSON
}.andExpect {
status { isOk }
content { contentType(MediaType.APPLICATION_JSON) }
content { json("""{"id":1,"name":"Test"}""") }
}
verify(respository, times(1)).save(user)
}
@Test
fun `Test negative scenario of createUser`() {
val user = User(2, "Test")
assertThrows<NestedServletException> {
mockMvc.post("/users/") {
contentType = MediaType.APPLICATION_JSON
content = jacksonObjectMapper().writeValueAsString(user)
accept = MediaType.APPLICATION_JSON
}
}
verify(respository, times(1)).save(user)
}
@Test
fun findUser() {
mockMvc.get("/users?id=99")
.andExpect {
status { isOk }
}
verify(respository, times(1)).findAll()
}
}
ApplicationContext
( H2 )中已经有一个测试数据库设置,那么为什么不使用它来创建测试记录,而不仅仅是模拟存储库层?然后,您可以验证数据库包含任何新创建的记录。 关于spring-boot - Kotlin + SpringBootTest + Junit 5 + AutoConfigureMockMvc:应该在失败时测试通过(似乎@BeforeEach无效),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61416636/
本着this question from JUnit 3 to JUnit 4的精神, 是否有任何正则表达式列表到 有效地从 junit 4 API 迁移到 junit 5 API ,不管代码大小?
就目前情况而言,这个问题不太适合我们的问答形式。我们希望答案得到事实、引用资料或专业知识的支持,但这个问题可能会引发辩论、争论、民意调查或扩展讨论。如果您觉得这个问题可以改进并可能重新开放,visit
我需要以下测试 @runwith(cache, memory) class CollectionA is -- this is a suite (aka folder) class Cache {
当尝试在JUNITTEST的内存数据库中使用derby时,出现以下异常。 java.sql.SQLNonTransientConnectionException: Database 'memory:t
我需要以下测试 @runwith(cache, memory) class CollectionA is -- this is a suite (aka folder) class Cache {
这个问题在这里已经有了答案: 关闭 11 年前。 Possible Duplicate: How to run Junit testcases from command line? 如何在 Linu
可以将 Junitperf 与 junit4 一起使用吗?我有一个带有多个测试的简单 Junit4 测试类,我想对该类的单个测试进行 TimedTest。我该怎么做? 更清楚地说,我的 Junit4
我想将 JUnit 4 测试添加到使用 JUnit 3 测试套件(“AllTests”)来组织测试的遗留项目中。 测试已经用 JUnit 4 执行了,所以我知道 JUnit 4 测试在原则上是有效的。
我正在将我的代码库从 junit4 迁移到 junit5。我在我的测试用例中使用了 mockito。下面是我用于依赖项的不同版本。 5.2.0 1.2.0 1.10.19 or
我刚刚使用 qunit-reporter-junit 生成了以下 XML: 但是当我运行它时,我在以下位置找到了 xsd:http
我已经编写了一个自定义 JUnit 运行器,我希望它成为 eclipse 插件的一部分,该插件将使用该运行器启动测试,而无需将 @RunWith 注释应用于该类。我已经设法使用 org.eclipse
我发现我的Sonar实例5.1或5.1.1(带有最新的声纳运行器2.x)停止在项目的仪表板上显示部分单元测试信息(单元测试小部件)。 我拥有的属性是(在Gradle的sonarRunner> sona
我有一个 JUnit 测试。但是当我使用“Run as -> JUnit”时它会成功,而当我使用“Cover as -> JUnit”时它会失败。这是为什么?代码确实有问题。在代码中,我使用了一些遗留
这个问题在这里已经有了答案: How to test code dependent on environment variables using JUnit? (20 个答案) 关闭 8 年前。 我
当我们的临时服务器因每周维护而停机时,我们有许多集成测试失败。当临时服务器关闭时,我们会发送一个特定的响应,我可以在集成测试中检测到该响应。当我得到这个响应而不是测试失败时,我想知道是否可以跳过/忽略
我需要测试一个程序,它首先预处理一些数据,然后使用这些预处理过的数据计算几个不同的结果——为每个计算编写单独的测试是有意义的。 官方 JUnit 政策似乎是我应该在每次计算测试之前运行预处理。 我如何
JUnit 是否可以为每个测试方法添加描述文本,以便描述文本稍后出现在surefire/failsave xml 报告中!? 背景:我在受监管的环境中工作,必须编写大量文档、测试规范和测试报告。 JU
当 JUnit 中的断言失败时,我想做一些“自己的事情”。我想要这个: public class MyAssert extends org.junit.Assert { // @Overrid
关闭。这个问题是off-topic .它目前不接受答案。 想改善这个问题吗? Update the question所以它是 on-topic对于堆栈溢出。 8年前关闭。 Improve this q
我想将参数从运行配置传递给我的 JUnit 测试。我如何到达 JUnits 的主要方法来访问这些参数?有谁知道如何做到这一点? 谢谢 最佳答案 您可以使用 -D 系统属性运行单元测试,并使用 Syst
我是一名优秀的程序员,十分优秀!