在为MvcMock Post方法编写JUnit测试时出现BadRequest错误

时间:2018-03-06 04:38:25

标签: java spring spring-boot mocking

我正在使用MvcMock编写一个JUnit测试来模拟HTTP post请求。但是我的测试因BadRequest错误而一直失败。如何让测试用例通过

休息结束点 - / transaction

请求格式为JSON -

{   
        "amount" : 12.6,
        "timestamp": 1478192204001
    }
我写的

Transaction.java 类是 -

import java.time.Instant;

public class Transaction {
    private double amount;

    private Instant timestamp;

    public Transaction() {
    }

    public Transaction(double amount, Instant timestamp) {
        this.amount = amount;
        this.timestamp = timestamp;
    }

    public double getAmount() {
        return amount;
    }

    public void setAmount(double amount) {
        this.amount = amount;
    }

    public Instant getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Instant timestamp) {
        this.timestamp = timestamp;
    }

    @Override
    public String toString() {
        return super.toString();
    }
}

我写的JUnit测试如下 -

@RunWith(SpringRunner.class)
@WebMvcTest(controllers=TransactionController.class)
public class TransactionControllerTest {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private TransactionService service;

    @Test
    public void shouldPostTransaction() throws JsonProcessingException, Exception {
        final Transaction transaction = new Transaction(14.1, now());

        when(service.add(transaction)).thenReturn(true);

        ObjectMapper mapper = new ObjectMapper();

        mvc.perform(
                post("/transactions")
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .content(mapper.writeValueAsString(transaction))
                .accept(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(status().isCreated())
                .andExpect(content().string(""))
                .andReturn();

        verify(service).add(transaction);
    }
}
我写的

TransactionController.java 是 -

@RestController
public class TransactionController {
    @Autowired
    private TransactionService service;

    @PostMapping("/transactions")
    ResponseEntity<String> add(@RequestBody Transaction transaction){
        if(service.add(transaction))
            return new ResponseEntity<>(CREATED);
        return new ResponseEntity<>(NO_CONTENT);
    }
}

2 个答案:

答案 0 :(得分:0)

对我有用的解决方案是 - 不知何故,当我们在代码中使用新的java.time.Instant类时,long值的timestamp无法直接映射到Instant。因此在使用MvcMock的单元测试中,它总是抱怨BadRequest错误。通过将Instant更改为long,然后使用Instant进行日期操作,将long转换为Instant,问题得以解决。 204错误的问题也很自然。两个实例都不同。因此,我改变了 when 语句,如 -

when(service.add(Mockito.any(Transaction.class))).thenReturn(true);

这使测试变为绿色

答案 1 :(得分:0)

对我来说,每次我在更改时遇到此错误

when(service.add(transaction)).thenReturn(true);

when(service.add(Mockito.any(Transaction.class))).thenReturn(true);

它有效,但我不知道为什么。