Hi,
Thanks for your replies.
I still cannot get an answer to this question - despite hours of reading the scant documents, and forums, and blog posts.
Which suggests I'm on a tangential plane to Mockito's concepts.
The question is quite simple: can Mockito stub at the class level instead of the object level?
I think the answer is no. But, hopefully I can get a definitive answer...
The problem is with legacy code. We need to intercept a particular method call that's made on an object somewhere deep in the method call sequence.
We know the class name at the top of the sequence, but we don't have access to the actual object instance because it's a local variable deep in the call sequence.
We don't want to refactor the code just so it can be tested (the code works and is in production).
Eric asked for a failing test, so here's the same test project with such a test.
It's this line that's the issue:
Mockito.when(printerMock.CleanString(Mockito.anyString())).thenReturn(MyCleanString());
what I really want to say is:
Mockito.when("class Printer".CleanString(Mockito.anyString())).thenReturn(MyCleanString());
"When there is any call to the method CleanString in any object instance of the class Printer, then replace it with a call to MyCleanString()".
Thanks again!
public class HelloWorldTest {
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
Mockito.reset();
}
/**
* Test method for {@link HelloWorld#main(java.lang.String[])}.
*/
@Test
public void testMain() {
Printer printerMock = mock(Printer.class);
Mockito.when(printerMock.CleanString(Mockito.anyString())).thenReturn(MyCleanString());
HelloWorld hello = new HelloWorld();
assertEquals("UNIT TEST", hello.WhatWillYouSay());
hello.SayHello();
}
/**
* @return
*/
private String MyCleanString() {
return "UNIT TEST";
}
}
public class Printer {
public void doPrint(String mesg) {
System.out.println(SayWhat(mesg));
}
public String SayWhat(String mesg) {
return CleanString(mesg);
}
public String CleanString(String mesg) {
return mesg;
}
}
public class HelloWorld {
String mesg = "Hello World";
/**
* @param args
*/
public static void main(String[] args) {
HelloWorld hello = new HelloWorld();
hello.SayHello();
}
public void SayHello() {
Printer print = new Printer();
print.doPrint(mesg);
}
public String WhatWillYouSay() {
Printer print = new Printer();
return print.SayWhat(mesg);
}
}