I have a factory design pattern which returns particular service according to the enum type and it works perfectly when I run the application but factory throws error on unit test.
@Service
public class GaServiceFactory {
@Autowired
private ApplicationContext appContext;
public IGaService getInstance(GaType type) {
if (MAN.equals(type)) {
return appContext.getBean(ManGaService.class);
}
throw new RuntimeException("No matching service could be created");
}
}
Here's my controller class;
@RestController
@RequestMapping(GA)
public class GaController {
@Autowired
private GaServiceFactory factory;
@PostMapping(value = INITIALIZE, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<GaDTO> initialize() {
return status(CREATED).body(factory.getInstance(MAN).initialize());
}
And here's my unit test;
@WebMvcTest(value = GaController.class)
class GaControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private GaServiceFactory factory;
@Mock
private ApplicationContext appContext;
private GaDTO gaDTO;
private List<GaDTO> gaDTOList;
@BeforeEach
void setUp() {
gaDTOList= new ArrayList<>();
Ga ga = new Ga();
gaDTO = new GaDTO();
gaDTO.setId(ga.getId());
gaDTOList.add(gaDTO);
}
@Test
public void initialize_success() throws Exception {
when(factory.getInstance(MAN).initialize()).thenReturn(gaDTO);
mockMvc.perform(post(GA + INITIALIZE)
.contentType(APPLICATION_JSON))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.id", is(gaDTO.getId())));
}
ApplicationContext in the factory returns null and it throws an error when I expect the initialize method in the service to work. How can I mock the factory to work as expected.
Aucun commentaire:
Enregistrer un commentaire