gpt4 book ai didi

java - Spring Boot Rest MVC。 Mockito 和放心。无法模拟实例

转载 作者:行者123 更新时间:2023-11-30 03:28:21 24 4
gpt4 key购买 nike

我有 Rest Controller 来构建事务

@RestController
@RequestMapping(value = "/transactions")
public class Transactions {

@Autowired
private Currency currency;

@RequestMapping(value = "/build", method = RequestMethod.POST)
@ResponseBody
public JsonData build(@RequestBody JsonNode json) throws Exception {

.......

System.out.println(currency.getBalance().get());
return result;
}

单元测试代码非常简单:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebIntegrationTest
@ActiveProfiles(profiles = "test")
public class TransactionsTest {

@Mock
@Autowired
private Currency currency;

@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this); }

@Test
public void testBuild() {
json = ".......";

when(currency.getBalance()).thenReturn(Optional.of("7777"));

given().contentType(ContentType.JSON).body(json).when().post("/transactions/build/")
.then()
.statusCode(HttpStatus.SC_OK)
.body(Matchers.containsString("fee"));

verify(currency).getBalance();
}

这不起作用。我的测试不与模拟交互。看起来正在使用货币的非模拟实例。

UPD

我做了一个简单的 Currecy 类来找出问题所在。

@Component
public class Currency {
public Optional<String> getBalance() {
System.out.println("Get Balance!!!!!");
return Optional.of("1111");
}
}

并更改了模拟:

when(currency.getBalance()).thenReturn(Optional.of("7777"));

在我的 Controller 中,我只是调用 getBalance,检查上面的代码。我希望得到 7777 而不是 1111。但它不起作用。

最佳答案

我认为您不需要使用@Autowired 注释。我通常只使用@Mock

关于java - Spring Boot Rest MVC。 Mockito 和放心。无法模拟实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29655280/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com