Reputation: 597
I have a factory pattern implemented and wanted to test this. Except the fields in this factory method are not getting autowired. It seems like the @Autowired attribute in the factory class is staying null. I can't use @SpringBootTest annotation because of the blockchain configuration file that gets loaded then
Below is the code of the service factory, the parserfactory gets autowired correctly in the test. The problems is with the autowired fields of the parserfactory
@Service
@Slf4j
public class ParserFactory {
@Autowired
OsirisParser osirisParser;
public Parser getParser(String system) {
if (system == null) {
return null;
}
if (system.equalsIgnoreCase("Progress")) {
return ProgressCreateService();
}
if (system.equalsIgnoreCase("Osiris")) {
log.debug("Osiris parsen creëren");
return OsirisCreateService();
}
return null;
}
public OsirisParser OsirisCreateService() {
return osirisParser;
}
public OsirisParser ProgressCreateService() {
return new OsirisParser("ProgressParser");
}
The test
@RunWith(SpringRunner.class)
public class FactoryTest {
@Mock
ParserFactory serviceCallFactory;
@Test
public void testCreateOsirisServiceSuccesFull() {
Parser serv = serviceCallFactory.getParser("Osiris");
assertThat(serv, instanceOf(OsirisParser.class));
}
@Test
public void testCreateProgressServiceSuccesFull() {
Parser serv = serviceCallFactory.getParser("Progress");
assertThat(serv, instanceOf(ProgressParser.class));
}
@Test
public void testCreateProgressServiceUnSuccessFull() {
Parser serv = serviceCallFactory.getParser("Progrddess");
assertThat(serv, is(not(instanceOf(OsirisParser.class))));
}
@Test
public void testCreateWhenStringIsNotCorrect() {
Parser serv = serviceCallFactory.getParser("0$iri$");
assertThat(serv, is(nullValue()));
}
@Test
public void testCreateWhenStringIsNull() {
Parser serv = serviceCallFactory.getParser("");
assertThat(serv, is(nullValue()));
}
}
Upvotes: 3
Views: 1268
Reputation: 12953
You do not have any spring context in your test class, which means that you are testing a POJO with no spring initialization to it, so the autowiring does not happen and the field is null.
There are several ways to solve it:
If you want to test it like a POJO, set the field on the tested class. you can use @InjectMocks
, ReflectionTestUtils.setField
in your current implementation, or move the @Autowire
to a constructor or setter and create the class in the test with the field. I vote for autowiring on a constructor
If you want it to be tested as a spring component, define a @TestConfiguration
and in there either import your real configuration and override the beans you don't want to be used, or use a completely different spring configuration for the test.
either way works, choose the one that suits you more
Upvotes: 1