Bastl
Bastl

Reputation: 2996

how can I inject "nulls" into autowired spring beans?

I am writing unit-tests and have a quite complex setting.

A dependent bean sets up some listeners and passes them autowired services.

I want to test that the listeners are present, but not call them, so I want to pass 'null' instead of the autowired service. (specifically: I do not have setters ...)

@Autowired
SomeService1 service1

@Autowired
SomeService2 service2


public List getListeners() {
  List l = new ArrayList();
  l.add(new AaaListener(service1));
  l.add(new BbbListener(Service2));
  return l;
}

@Test
public void testListeners() {
  int exptecedSize = 2;

  sut.doSomething();

  List l = sut.getX().getY().getListeners()

  assertEquals(expectedSize,l.size());
}

Note that the SUT does depend indirectly from the class that returns the listeners.

Since this is a very small example from a big setting, I do specifically do not want to use mocks here as I want to test only presence not behavior of the listeners.

Mocking 20 or 30 of such services will slow down the tests massively.

Question: What is the easiest way to inject these nulls into the autowired instance variables?

A) Add setters ?

B) ReflectionUtils ?

C) java-config + @Beans + return null ?

Upvotes: 0

Views: 168

Answers (2)

John B
John B

Reputation: 32949

  1. Don't use the Spring context and create the class manually
  2. Use ReflectionTestUtils to set the field. ReflectionTestUtils allows for the setting of private fields where ReflectionUtils does not.

Upvotes: 1

blank
blank

Reputation: 18170

They're already null when the class is instantiated ... or are you actually running them in a spring context?

You can set properties to null in the xml config like this (from the documentation)

<bean class="ExampleBean">
    <property name="email"><null/></property>
</bean>

Upvotes: 1

Related Questions