0

I have a service class MyService which is defined and being used in controller like so:

public interface MyService {
  public String someMethod() 
}

@Service("myService")
public class MyServiceImpl implements MyService {
  public String someMethod() {
    return "something";
  }
}

@Controller 
public class MyController {
  @Autowired
  public MyService myService;

  @RequestMapping(value="/someurl", method=RequestMethod.GET)
  public String blah () {
    return myService.getsomeMethod();
  }
}

I'd like to write a test case for the someMethod method, however, the following doesn't work. How can I wire in the implementation class?

public class MyServiceImplTest {
 @Autowired
 private MyService myService;

 @Test
 public void testSomeMethod() {
   assertEquals("something", myService.someMethod());
 }

}

Grzegorz Rożniecki
  • 27,415
  • 11
  • 90
  • 112
birdy
  • 9,286
  • 24
  • 107
  • 171
  • http://stackoverflow.com/questions/13092322/spring-testng-integration-tests-injecting-dao-with-annotations-fails/13093822#13093822 – Boris Treukhov Nov 19 '12 at 15:45

2 Answers2

1
public class MyServiceImplTest {
    private MyService myService = new MyServiceImpl();

    @Test
    public void testSomeMethod() {
        assertEquals("something", myService.someMethod());
    }
}

Why inject the bean in your test rather than creating an instance by yourself?

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

Try this:

@RunWith(SpringJUnit4ClassRunner.class)
 // specifies the Spring configuration to load for this test fixture
@ContextConfiguration("yourapplication-config.xml")

Also see the Spring.IO docs for more detail.

Undo
  • 25,519
  • 37
  • 106
  • 129
fuyou001
  • 1,594
  • 4
  • 16
  • 27