0

I have a private method called getSubject in a class which i have just implemented. I am trying to carry out a unit test on the private method but my issue is that the private method getSubject is calling another method getSubjectOracle() (note:getSubjectOracle is a public method in a jar file) which returns a String subject. A pseoudocode is shown below:

public class Service{

    private oracleDao

    //setter for oracle dao avilable


    private String getSubject(String id,Stringountry){

        String subject = oracleDao.getSubjectOracle(String id,String country)

        return subject;

    }

}

Any idea how i can mock the return of the method oracleDao.getSubjectOracle(String id,String country) in order to carry unit test for method getSubject(String id, String country) pls?

I have search online of helpful resouces but could not get any.

Thanks in advance.

4

2 回答 2

1

一种方法是为 oracleDao 编写一个 setter。在那里你可以设置一个模拟而不是真实的东西。例如,编写您自己的 oracleDao 来满足您的需求。在 @Before 方法中,您将注入模拟 oracleDao。

使用像 Mockito 这样的框架会更好。它看起来像这样:

@Mock
YourDaoThing mock;

@Before
public setUp(){
  MockitoAnnotation.initMocks(this);
  service = new Service();
  service.setDao(mock);
}

@Test
public testGetSubject(){
  String someString = "whatever";
  when(mock.getSubjectOracle(id,country)).thenReturn(someString)

  assertEquals(expect, service.callToTheMethodYouTest())

}
于 2013-09-05T16:00:22.037 回答
1

如果您正在尝试 test Service,那么您也必须模拟oracleDao并使其getSubjectOracle()方法返回您想要的 String 。

我假设你不是在测试getSubject(),而是一个调用getSubject().

于 2013-09-05T15:50:00.833 回答