我想测试下面的类Sample:

public class Sample{
    public boolean sampleMethod(){
        SequenceCreate seq = new SequenceCreate();
        .... //Code where seq is used
     }
}


SequenceCreate是另一个创建的类,如下所示:

 public class SequenceCreate {
      public String nextSeq() {
      SecureRandom random = new SecureRandom();
      int number = random.nextInt(1000000);
      return String.format("%06d", number);
 }
}


我的测试课如下:

@SpringBootTest(classes = TfaApplication.class)
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class SampleTest{

    @Autowired
    private Sample sample;

    @Mock
    private SequenceCreate seq;

    public void sampleMethodtest(){
          when(sample.nextSeq()).return("123");
          assertTrue(Boolean.True,sample.sampleMethod());
   }
 }


这行不通。和断言失败。
通过调试数小时,我发现每当调用someMethod()方法且不采用模拟值时都会生成序列号。

我怎样才能做到这一点?

提前致谢

最佳答案

当您在SequenceCreate内部手动创建sampleMethod()对象时,这将无法工作。

您可以将SequenceCreate设置为实例字段,并添加一个公共设置程序os,您可以将该依赖项注入并正确地进行模拟:

public class Sample{

    private SequenceCreate seq;

    public boolean sampleMethod(){
        .... //Code where seq is used
     }

    public void setSeq(SequenceCreate seq){
       this.seq=seq;
    }
}


然后在测试中,您将执行以下操作:

@SpringBootTest(classes = TfaApplication.class)
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class SampleTest{

    @Autowired
    private Sample sample;

    @Mock
    private SequenceCreate seq;

    public void sampleMethodtest(){
          sample.setSeq(seq);
          when(seq.nextSeq()).thenReturn("123");
          assertTrue(Boolean.True,sample.sampleMethod());
   }
 }


顺便说一句,您还嘲笑了错误的对象。在seq.nextSeq()方法中应使用when

10-06 02:05