英文:
the stubbed value is not being return when I mock on a class
问题
以下是翻译好的内容:
我正在模拟一个类并对其中的一个方法进行桩测试,以便返回我想要的值,但由于我需要传递 .class 值,模拟的数据没有被返回。如果有任何见解,将不胜感激。
public class Generator {
public int getSomething() {
return 1;
}
}
public class Utility {
public void generate(java.lang.Class<?> clazz) {
}
}
@RunWith(SpringRunner.class)
public class TestClass extends Utility {
@Test
public void test() {
Generator gen = Mockito.spy(Generator.class);
Mockito.when(gen.getSomething()).thenReturn(4);
int x = generate(gen.getClass());
// 在这里,返回的是 1 而不是 4
}
}
英文:
I am mocking a class and stubbing one of the method to return the value i want but since i need to pass .class value the mocked data is not being returned. any insights is appreciated.
public class Generator{
public int getSomething(){
return 1;
}
}
public class Utility{
public void generate(java.lang.Class<?> class){
}
}
@RunWith(SpringRunner.class)
public class TestClass extends Utility{
@Test
public void test()
Generator gen = Mockito.spy(Generator.class)
Mockito.when(gen.getSomething()).thenReturn(4);
Int x = generate(gen.getClass())
// in here 1 is being returned instead of 4
}
}
答案1
得分: 0
以下是翻译好的部分:
for spy Object that is diferent from mock object
try
Mockito.doReturn(4).when(gen).getSomething();
below code works for me perfectly fine
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
public class TestClass {
@Test
public void test() {
Generator gen = Mockito.spy(Generator.class);
Mockito.doReturn(4).when(gen).getSomething();
assertEquals(4, gen.getSomething());
}
}
class Generator{
public int getSomething(){
return 1;
}
}
希望这对你有所帮助。如果你有任何其他问题,可以继续提问。
英文:
for spy Object that is diferent from mock object
try
Mockito.doReturn(4).when(gen).getSomething();
<br>
below code works for me perfectly fine
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
public class TestClass {
@Test
public void test() {
Generator gen = Mockito.spy(Generator.class);
Mockito.doReturn(4).when(gen).getSomething();
assertEquals(4, gen.getSomething());
}
}
class Generator{
public int getSomething(){
return 1;
}
}
专注分享java语言的经验与见解,让所有开发者获益!
评论