0

I am quite new in Spring and I am facing an issue right now with testing:

I have the following Service:

@Service
public class MyService {

public Integer getKey() {
    List<Integer> keys = getKeys(1);
    if (keys.size() == 1) {
        return keys.get(0);
    }
    throw new IllegalArgumentException("Error!");
}

... and a getKeys() method, which provides a list based ona  rest call...
}

And I use this service class in antother class:

@NoArgsConstructor
public class MyOtherClass extends MyClass {

@Autowired
private MyService myService;

....
@Override public KeyValue<Object, Object> doSomething(Object key, Object value) {
    if (conditionIsTrue(key, value)) {
            MyObject obj = new MyObject();
            myObject.setKey(keyService.getKey());  ----- here is always null the keyService
            .....
    } else {
        return KeyValue.pair(null, null);
    }
}

And I try to write a test but the MyService is always null..

@ActiveProfiles("my-test")
@SpringBootTest(classes = Application.class)
@Testcontainers
@Slf4j
public class MyTest extends TestContext {

@BeforeEach
void init(final TestInfo testInfo) {
   ....
}

@AfterEach
void deinit() {
    ....
}

@Test
public void myTest() {
....
}

How can I inject a mock MyService into the test container?

Thank you!

dorcsi
  • 295
  • 2
  • 6
  • 24
  • MyOtherClass has not annotation so it's not a spring bean and will not provided with dependency injection. That's why myService is null – Simon Martinelli Feb 24 '21 at 17:16
  • @simon Thank you, but I tried to annotate it with *@Component and *@Service as well, but still null... – dorcsi Feb 24 '21 at 17:29
  • In case you want a mocked bean inside your Spring TestContext, use `@MockBean MyService myService;` inside your test. Are your My* classes in the same or in a package below your `Application` class, so that the default component scanning can find them? – rieckpil Feb 25 '21 at 06:29

0 Answers0