Hi guys,
Im confused when trying to write a unit test for my rest controller as I cannot seem to mock my @Autowire properties in the controller.
Here is my Test
My config in RegistrationControllerTesting-context.xmlCode:@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration() public class RegistrationControllerTesting { private MockMvc mockMvc; private LicenseSecurityContextHelper licenseSecurityContextHelper; private ILicenseAuthentication licenseAuthentication; @Before public void setup() { licenseAuthentication = mock(LicenseAuthentication.class); mockMvc = MockMvcBuilders.standaloneSetup(new RegistrationController()).build(); licenseSecurityContextHelper = mock(LicenseSecurityContextHelper.class); when(licenseSecurityContextHelper.getLicenseAuthentication()).thenReturn(licenseAuthentication); } @Test public void test() throws Exception { DefaultRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/rest/auth/register") .contentType(MediaType.APPLICATION_JSON) .body(JsonHelperProvider.registrationJson.getBytes()); mockMvc.perform(requestBuilder); }
My controller has autowire fieldsCode:<bean id="licenseSecurityContextHelper" class="org.mockito.Mockito" factory-method="mock"> <constructor-arg value="uk.co.company.common.license.spring.LicenseSecurityContextHelper" /> </bean> <bean id="rollupScheduleService" class="org.mockito.Mockito" factory-method="mock"> <constructor-arg value="uk.co.company.product.service.IRollupScheduleService" /> </bean> <bean id="productApplicationContextService" class="org.mockito.Mockito" factory-method="mock"> <constructor-arg value="uk.co.company.product.service.IproductApplicationContextService" /> </bean>
However in my controller the object licenseSecurityContextHelper is null i.eCode:@Autowired private IproductApplicationContextService productApplicationContextService; @Autowired private IRollupScheduleService rollupScheduleService; @Autowired private LicenseSecurityContextHelper licenseSecurityContextHelper;
Im confused because the beans seem to be autowired in the log file. I proved this by removing the mocked bean definitions from my xml config and this produces the errorCode:ILicenseAuthentication licenseAuthentication = licenseSecurityContextHelper.getLicenseAuthentication();
Can someone please tell me what ive done wrong?Code:"Could not autowire field: private uk.co.company.product.service.IproductApplicationContextService"


Reply With Quote