我正在尝试Spring Web并测试REST控制器。 该应用程序基本上是可以通过Web服务访问的游戏数据库。
当我启动它并用Postman对其进行测试以添加游戏时,我得到了想要的行为。 但是,当我使用SpringJUnit4ClassRunner测试控制器时,似乎我要添加的游戏已经存在于数据库中,因此无法添加。
这是我的考试班:
@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(GameController.class)
public class GameControllerTest {
@MockBean
private IGameService gameService;
@Autowired
private MockMvc mockMvc;
@Test
public void postGameTest() throws Exception {
String mockGameJson = "{\"name\":\"Test Game\",\"description\":\"A test game.\"}";
//Create a post request with an accept header for application\json
RequestBuilder requestBuilder = MockMvcRequestBuilders
.post("/game/")
.accept(MediaType.APPLICATION_JSON).content(mockGameJson)
.contentType(MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = result.getResponse();
//Assert that the return status is CREATED
assertEquals(HttpStatus.CREATED.value(), response.getStatus());
}
}
最后一行中的断言失败,因为状态是http 409冲突
我本人在控制器中返回该状态:
@RestController
public class GameController {
@Autowired
private IGameService gameService;
@PostMapping("/game")
public ResponseEntity<String> addGame(@RequestBody Game game, UriComponentsBuilder builder) {
boolean flag = gameService.addGame(game);
if (!flag) return new ResponseEntity<>("Another game with this name already exists.", HttpStatus.CONFLICT);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(builder.path("/game/{id}").buildAndExpand(game.getId()).toUri());
return new ResponseEntity<>(headers, HttpStatus.CREATED);
}
...
那是没有道理的,因为我的数据库在测试开始时应该是空的,对吗? 这是相关的服务:
@Service
public class GameService implements IGameService { //Service layer
@Autowired
private IGameDAO gameDAO;
@Override
public synchronized boolean addGame(Game game) {
if(gameDAO.gameExists(game.getName()))
return false;
else {
gameDAO.addGame(game);
return true;
}
}
...
还有DAO:
@Transactional
@Repository
public class GameDAO implements IGameDAO {
@PersistenceContext
private EntityManager entityManager;
@Override
public void addGame(Game game) {
entityManager.persist(game);
}
@Override
public boolean gameExists(String name) {
String jpql = "from Game as g WHERE g.name = ?0 ";
int count = entityManager.createQuery(jpql).setParameter(0, name).getResultList().size();
return count > 0;
} ...
这些是我build.gradle中的依赖项
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'com.h2database:h2'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
我在这里做什么错了?
答案 0 :(得分:0)
解决了。 如前所述,最好独立测试各层。 在这里,我试图测试我的控制器(网络)。该服务是经过模拟的,因此默认情况下,对任何应返回布尔值的方法的调用都将返回false。
我必须告诉模拟服务返回true,以充分测试post方法。像这样:
given(gameService.addGame(any())).willReturn(true);