2

So I have an interface, let's call it X

So in the regular code i have:

public class doStuff()
{
@Autowired
private X x;

public stuff()
{
x.doYourThing();
}
}

I have no idea how to test this though.

If i try:

public class XTest()
{
  @Autowired
  private X x;
  public void test(){
  string val = x.FillUpVal();
  assertTrue("It didn't work",val=="hi");
  }

}

I get x as null so it immediately throws a NullPointerException and fails the test. I'm looking for some guidance as to the proper way to go about this.

epsalon
  • 2,294
  • 12
  • 19
NolanPower
  • 409
  • 3
  • 11
  • 1
    Needs more clarification on what you want to test: 1) how `doStuff()` behaves when `X` behaves in certain ways (use a mock) or 2) how `doStuff()` behaves when wired up with the real X that would be used at runtime (use Spring's Test Context library) – matt b Sep 13 '12 at 20:20

1 Answers1

2

You can in fact @Autowire a mock object. I recommend Mockito framework. More info and examples: http://code.google.com/p/mockito/

Injecting Mockito mocks into a Spring bean

More on mocks:

In object-oriented programming, mock objects are simulated objects that mimic the behavior of real objects in controlled ways. A programmer typically creates a mock object to test the behavior of some other object, in much the same way that a car designer uses a crash test dummy to simulate the dynamic behavior of a human in vehicle impacts.

http://en.wikipedia.org/wiki/Mock_object

Community
  • 1
  • 1
Maciej Ziarko
  • 11,494
  • 13
  • 48
  • 69