我想测试GetParameters()断言返回值包含值中的"test =".不幸的是,负责这个的方法是私有的.有没有办法为此提供测试覆盖?我遇到的问题如下:
if (info.TagGroups != null)
Run Code Online (Sandbox Code Playgroud)
问题是我的测试中info.TagGroups等于null
谢谢,
测试
[Test]
public void TestGetParameters()
{
var sb = new StringBuilder();
_renderer.GetParameters(sb);
var res = sb.ToString();
Assert.IsTrue(res.IndexOf("test=") > -1, "blabla");
}
Run Code Online (Sandbox Code Playgroud)
实现类来测试
internal void GetParameters(StringBuilder sb)
{
if (_dPos.ArticleInfo != null)
{
var info = _dPos.ArticleInfo;
AppendTag(sb, info);
}
}
private static void AppendTag(StringBuilder sb, ArticleInfo info)
{
if (info.TagGroups != null) // PROBLEM - TagGroups in test equals null
{
foreach (var tGroups in info.TagGroups)
{
foreach (var id in tGroups.ArticleTagIds) …Run Code Online (Sandbox Code Playgroud) 如果构造函数是私有的(.NET),如何设置单元测试?
这是我的班级:
public class Class2
{
// Private constructor.
private Class2()
{
}
public static Class2 getInstance()
{
if (x == null)
{
x= new Class2();
}
return x;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的单元测试:
[TestFixture]
public class Class2Tester
{
private Class2 test;
[SetUp()]
public void SetUp()
{
// I cant do this. How should I setup this up?
test = new Class2();
}
}
Run Code Online (Sandbox Code Playgroud) 我们可以制作@IBOutlets和@IBAction私人。例子:
class MyViewController: UIViewController {
@IBOutlet private weak var myLabel: UILabel!
@IBAction private func nextTapped(sender: UIButton) {
// Do something
}
}
Run Code Online (Sandbox Code Playgroud)
我们无法在类之外访问这些属性和方法,这很好。
但是,如何通过私人渠道和行动来测试课程呢?是否有任何方法可以在 XCTestCase 中测试私有插座或方法,或者我必须将它们暴露在内部的类之外?
出于测试目的,@IBOutlets/ @IBActions 应该是内部可见的吗?
在测试覆盖范围内,有什么方法可以排除私有方法?
在我的.coveragerc中,我尝试了:
[report]
exclude_lines =
__*
Run Code Online (Sandbox Code Playgroud)
但这似乎排除了诸如 long_method_name
是否有任何方法可以在不列出所有方法的情况下进行操作?
编辑
我希望测试中包含诸如__add__私有的类似语法的方法。
我有一个构造函数,它调用两个方法。它们都是无效的,我只是想验证它们是否被调用。
文件
public class Foo {
public Foo(String name, Object obj) {
init(name);
doSomething(obj);
}
}
Run Code Online (Sandbox Code Playgroud)
测试文件
@Test
public void constructor_test throws Exception {
Foo foo = Mockito.mock(Foo.class);
PowerMockito.whenNew(Foo.class).withAnyArguments().thenReturn(foo);
Foo f = new Foo("name");
verify(f).init(Mockito.anyString());
verify(f).doSomething(Mockito.any(Object.class));
}
Run Code Online (Sandbox Code Playgroud)
单元测试失败并显示一条消息,指出与模拟foo.init() 的交互为零;.
如何验证构造函数中的方法调用?
TDD。我有相当复杂的编码练习,如果私有方法非常复杂,我是否要测试它们?
所以我的类只公开了一个公共方法,但包含很少的非常复杂的方法,我认为应该测试哪些方法?
有疑问:我是否测试它们?