PaintedRed
PaintedRed

Reputation: 1418

Spring Boot Rest MVC. Mockito and Rest Assured. Can't mock the instance

I have Rest controller to build transaction

@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;
}

The unit-test code is pretty simple:

@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();
}

It doesn't work. My test is not interacting with mock. Looks like non-mocked instance of Currency is being used.

UPD

I made a simple class Currecy to figure out what is the problem.

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

And changed the mock:

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

In my controller I just call getBalance, check the code above. I expect to get 7777 instead of 1111. But it's not working.

Upvotes: 1

Views: 4897

Answers (2)

PaintedRed
PaintedRed

Reputation: 1418

I found what was wrong. Here is fixed part of the code

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

private MockMvc mockMvc;

@Autowired
private WebApplicationContext context;

@Mock
private Currency currency;

@InjectMocks
private Transactions transactions;

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    RestAssuredMockMvc.mockMvc = MockMvcBuilders.standaloneSetup(transactions).build();
}

Upvotes: 0

maximede
maximede

Reputation: 1823

I don't think you need to use the @Autowired annotation. I usually just use the @Mock

Upvotes: 2

Related Questions