I was trying to write test cases for SpringBoot MVC rest application. I am able to run the test cases successfully. But when i tried to mock one of the methods, its not working. The test case still calls the original implementation.
Test class:-
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = { Initializer.class,
WebConfig.class })
@WebAppConfiguration
public class SampleControllerTest {
@Mock
CounterUtil counterUtil;
@InjectMocks
PreProcessor preProcessor
@Autowired
private WebApplicationContext context;
private static boolean isSetup = false;
@Test
public void sampleTest() {
org.mockito.Mockito.when(
counterUtil
.getCounter()).thenReturn(
"2222");
given().contentType("application/json").when()
.get("/initialize").then()
.statusCode(HttpServletResponse.SC_OK);
}
@Before
public void setUp() {
RestAssured.useRelaxedHTTPSValidation();
counterUtil = (CounterUtil) context
.getBean("counterUtil");
MockitoAnnotations.initMocks(this);
RestAssuredMockMvc.mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}
}
The PreProcessor is a concreate class, with an instance of CounterUtil.
@Component
public class PreProcessor {
@Autowired
private CounterUtil counterUtil
public void myMethod(){
counterUtil.getCounter();
}
}
These are the dependencies in pom.xml.
<!-- test dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.9.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.restassured</groupId>
<artifactId>spring-mock-mvc</artifactId>
<version>2.4.1</version>
<scope>test</scope>
</dependency>
Not getting any error. The execution works fine, but not considering the the mocked implementation.
Any suggestion or pointer is also welcomed.